jpa删除父节点,同时把子节点也删了,怎么写具体代码
时间: 2023-04-05 19:03:43 浏览: 90
可以使用级联删除的方式来实现,具体代码如下:
@Entity
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Child> children = new ArrayList<>();
// getters and setters
}
@Entity
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Parent parent;
// getters and setters
}
@Repository
public interface ParentRepository extends JpaRepository<Parent, Long> {
}
@Service
public class ParentService {
@Autowired
private ParentRepository parentRepository;
@Transactional
public void deleteParent(Long parentId) {
parentRepository.deleteById(parentId);
}
}
在上面的代码中,使用了 JPA 的级联删除和孤儿删除功能,当删除父节点时,子节点也会被删除。同时,使用了事务来保证操作的原子性。