使用springboot编写一套实体类为Approval的基本的crud接口
时间: 2024-03-23 09:40:55 浏览: 153
好的,下面是Approval实体类的基本CRUD接口实现:
1. 定义Approval实体类
```java
@Entity
@Table(name = "approval")
public class Approval {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
// getters and setters
}
```
2. 创建ApprovalRepository接口
```java
@Repository
public interface ApprovalRepository extends JpaRepository<Approval, Long> {}
```
3. 创建ApprovalService接口和实现类
```java
public interface ApprovalService {
Approval create(Approval approval);
Approval update(Long id, Approval approval);
void delete(Long id);
Approval findById(Long id);
List<Approval> findAll();
}
@Service
public class ApprovalServiceImpl implements ApprovalService {
@Autowired
private ApprovalRepository approvalRepository;
@Override
public Approval create(Approval approval) {
return approvalRepository.save(approval);
}
@Override
public Approval update(Long id, Approval approval) {
Approval existingApproval = findById(id);
existingApproval.setName(approval.getName());
existingApproval.setDescription(approval.getDescription());
return approvalRepository.save(existingApproval);
}
@Override
public void delete(Long id) {
approvalRepository.deleteById(id);
}
@Override
public Approval findById(Long id) {
return approvalRepository.findById(id)
.orElseThrow(() -> new NoSuchElementException("Approval not found with id " + id));
}
@Override
public List<Approval> findAll() {
return approvalRepository.findAll();
}
}
```
4. 创建ApprovalController类
```java
@RestController
@RequestMapping("/approvals")
public class ApprovalController {
@Autowired
private ApprovalService approvalService;
@PostMapping
public Approval create(@RequestBody Approval approval) {
return approvalService.create(approval);
}
@PutMapping("/{id}")
public Approval update(@PathVariable Long id, @RequestBody Approval approval) {
return approvalService.update(id, approval);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
approvalService.delete(id);
}
@GetMapping("/{id}")
public Approval findById(@PathVariable Long id) {
return approvalService.findById(id);
}
@GetMapping
public List<Approval> findAll() {
return approvalService.findAll();
}
}
```
至此,我们就完成了一个基本的Approval实体类的CRUD接口。
阅读全文