当我通过POST请求创建一个母实体时,我希望自动创建一个子实体。使用@OneToMany和@ManyToOne注释,效果很好。至少,只要我在MotherService中提供孩子的信息。
Mother.java
@Entity
@Table(name="mother")
public class Mother{
@Id
@Column(name="id", updatable = false, nullable = false)
private Long id;
@Column(name="name")
private String name;
@OneToMany(mappedBy = "mother", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Kid> kidList = new ArrayList<>();
//constructor, getter, setter
private void addKid(Kid kid) {
this.kidList.add(kid);
kid.setMother(this);
}
}
@Entity
@Table(name="kid")
public class Kid{
@Id
@Column(name="id", updatable = false, nullable = false)
private Long id;
@Column(name="name")
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "mother_id", nullable=false)
private Mother mother;
//constructor, getter, setter
}
MotherController.java
@RestController
@RequestMapping("mothers")
public class MotherController {
@Autowired
private MotherService motherService;
MotherController(MotherService motherService) {
this.motherService = motherService;
}
@PostMapping
Mother createMother(@RequestBody Mother mother) {
return this.motherService.createMother(mother);
}
}
MotherService.java
@Service
public class MotherService {
private MotherRepository motherRepository;
@Autowired
public MotherService (MotherRepository motherRepository) {
super();
this.motherRepository= motherRepository;
}
public Mother createMother(Mother mother) {
Kid kid = new Kid("Peter");
mother.addKid(kid);
return this.motherRepository.save(mother);
}
}
母亲和孩子的存储库扩展了JpaRepository,到目前为止没有任何自定义方法。
我的发帖请求类似(使用邮递员)
{
"name":"motherName"
}
现在一个母亲的名字是“motherName”,一个孩子的名字是“Peter”。
我的想法:使用DTO
我现在尝试实现一个DTO,它包含母亲的名字和孩子的名字,将母亲服务中的信息映射到实体,并通过相应的存储库保存它们,这样我就可以在POST请求中定义这两个名字。
motherDto.java
public class mother {
private String motherName;
private String kidName;
//getter, setter
}
{
"motherName":"Susanne",
"kidName":"Peter"
}
甚至更好
{
"mother": {
"name":"Susanne"
},
"kid": {
"name":"Peter"
}
}
一个名叫苏珊娜的母亲和一个名叫彼得的孩子被创造出来。
我的问题是
还是我做的不对?有没有更简单的方法来实现我的目标?