通过前端传过来的id删除数据库中的一栏前端用Thymeleaf后端用springboot + jpa 完整代码 查询整个表单service层怎么写
删除数据操作的Service层代码:
@Service
public class DataService {
@Autowired
private DataRepository dataRepository;
// 删除数据
public void deleteDataById(Long id) {
dataRepository.deleteById(id);
}
// 查询所有数据
public List<Data> findAllData() {
return dataRepository.findAll();
}
}
其中,DataRepository是继承JpaRepository的接口,用于对数据库进行操作。示例代码如下:
@Repository
public interface DataRepository extends JpaRepository<Data, Long> {
}
其中,Data是对应数据库表的实体类。示例代码如下:
@Entity
@Table(name = "data")
public class Data {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
// 省略getter和setter方法
}
在Controller层中,可以通过调用DataService的方法来实现删除和查询操作。示例代码如下:
@Controller
public class DataController {
@Autowired
private DataService dataService;
// 删除数据
@GetMapping("/delete/{id}")
public String deleteData(@PathVariable("id") Long id) {
dataService.deleteDataById(id);
return "redirect:/list";
}
// 查询所有数据
@GetMapping("/list")
public String listData(Model model) {
List<Data> dataList = dataService.findAllData();
model.addAttribute("dataList", dataList);
return "list";
}
}
其中,@GetMapping("/delete/{id}")用于处理删除操作的请求,@GetMapping("/list")用于处理查询操作的请求。在查询操作中,将查到的数据放入Model中传递给视图层。视图层可以通过Thymeleaf模板引擎进行渲染。例如:
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="data : ${dataList}">
<td th:text="${data.id}"></td>
<td th:text="${data.name}"></td>
<td th:text="${data.age}"></td>
<td><a th:href="@{/delete/{id}(id=${data.id})}">删除</a></td>
</tr>
</tbody>
</table>
以上就是一个简单的删除和查询操作的示例代码
原文地址: https://www.cveoy.top/t/topic/crq6 著作权归作者所有。请勿转载和采集!