帮我写一个spring boot +jpa 一对多的添加和删除的程序
时间: 2023-03-30 08:01:27 浏览: 90
好的,我可以为您提供一个 Spring Boot JPA 的一对多添加和删除的程序。首先,您需要定义两个实体类,一个是一的一方,另一个是多的一方。在一的一方实体类中,使用 @OneToMany 注解来定义与多的一方实体类的关系。在多的一方实体类中,使用 @ManyToOne 注解来定义与一的一方实体类的关系。然后,您可以使用 JPA 的 save() 方法来添加数据,使用 delete() 方法来删除数据。具体的代码实现可以参考以下示例:
一的一方实体类:
```
@Entity
public class OneEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "oneEntity", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ManyEntity> manyEntities = new ArrayList<>();
// getter 和 setter 方法
}
```
多的一方实体类:
```
@Entity
public class ManyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "one_entity_id")
private OneEntity oneEntity;
// getter 和 setter 方法
}
```
添加数据:
```
OneEntity oneEntity = new OneEntity();
ManyEntity manyEntity1 = new ManyEntity();
ManyEntity manyEntity2 = new ManyEntity();
manyEntity1.setOneEntity(oneEntity);
manyEntity2.setOneEntity(oneEntity);
oneEntity.getManyEntities().add(manyEntity1);
oneEntity.getManyEntities().add(manyEntity2);
oneRepository.save(oneEntity);
```
删除数据:
```
OneEntity oneEntity = oneRepository.findById(id).orElse(null);
oneRepository.delete(oneEntity);
```
希望这个程序能够帮到您。