SpringBoot: Is this correct way to save a new entry which has ManyToOne relationship?
我有两个实体
我想知道是否要保存一个新的Visit条目,以及是否要使用RestController。我的方法正确吗?还是有另一种更有效的方法?
因此,我有以下控制器从RequestBody中获取
VisitModel具有人员ID,以及Visit实体所需的属性。我使用person的ID在personRepository中查找相关的Person条目,然后将其发布到Visit的新实例,然后使用visitRepository进行保存。
1 2 3 4 5 6 7 8 9 10 | @RequestMapping(value="", method=RequestMethod.POST) public String checkIn(@RequestBody VisitModel visit) { Person person = personRepository.findById(visit.personId); Visit newVisit = new Visit(visit.getCheckIn, person); visitRepository.save(newVisit); return"success"; } |
Visit实体如下所示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | @Entity public class Visit { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @JsonProperty("check_in") private Date checkIn; @JsonProperty("check_out") private Date checkOut; @ManyToOne @JoinColumn(name="personId") private Person person; public Visit(Date checkIn, Person person) { this.checkIn = checkIn; this.person = person; } public Date getCheckIn() { return checkIn; } public void setCheckIn(Date checkIn) { this.checkIn = checkIn; } public Date getCheckOut() { return checkOut; } public void setCheckOut(Date checkOut) { this.checkOut = checkOut; } public Person getPerson() { return person; } } |
我想知道以下方法是正确的。还是有另一种更好的方法?
您当然不需要从数据库中获取
如果使用JPA
1 | Person person = entityManager.getReference(Person.class, visit.personId); |
对于hibernate
1 | Person person = session.load(Person.class, visit.personId); |
此方法仅创建代理,不执行任何数据库请求。
使用Hibernate
EntityManager.find()和EntityManger.getReference()有什么区别?
hibernate:session.get和session.load之间的区别
是的,在我看来,这是映射
1 2 | @Id private Long id; |
更新:1:VisitModel是" DTO"或数据传输对象。任何单独的package都可以。您可以考虑将它们放在单独的jar中,以便使用您的API(带有Java)的任何人都可以在进行调用之前使用jar创建数据。 2)据我所知,保存它的方式还不错。