简体   繁体   English

Hibernate中的CRUD与一对多映射

[英]CRUD in Hibernate with one-to-many mapping

I have three entities and three tables in database with their relation: 我在数据库中有三个实体和三个表及其关系:

 Class person {

 int id;

 @OneToMany(mappedBy = "person", fetch = FetchType.LAZY)
 List<Comment> comments;

 @OneToMany(mappedBy = "person", fetch = FetchType.LAZY)
 List<CellPhone> cellPhones;

 }

 Class Comment {

 String content;    

 @ManyToOne
 @JoinColumn(name = "id")
 Person person;

 }

 Class CellPhone {

 String mark;    

 @ManyToOne
 @JoinColumn(name = "id")
 Person person;

 }

Does Hibernate support me to do something like that ? Hibernate是否支持我做类似的事情?

  • Insert a new person, it automatically inserts into CellPhone and Comment, not insert by every entity. 插入一个新人,它会自动插入到CellPhone和Comment中,而不是每个实体都插入。
  • Delete a person with given id, then automatic delete CellPhone and Comment with their relation by id of person ? 删除具有给定id的人,然后通过person的ID自动删除CellPhone和Comment及其关系。
  • Let's give a person id, it gets person with all Comments and CellPhones ? 让我们给一个人id,它让所有评论和手机的人?
  • Update something in Comment and CellPhone of a person, and save a person, it will save CellPhone and Comment automatically ? 更新某人的Comment和CellPhone中的某个内容并保存一个人,它将自动保存CellPhone和Comment。

In general, I just want to set/get CellPhone and Comment for person object, and then call getPerson(person), save(person), or delete(person) ect without get(comment), save(comment) or delete(cellPhone).. 通常,我只想为person对象设置/获取CellPhone和Comment,然后调用getPerson(person),save(person)或delete(person)ect,而无需get(comment),save(comment)或delete(cellPhone) )..

Please help me to clarify it. 请帮我澄清一下。 Thanks. 谢谢。

The answer is yes to all of your questions. 答案是肯定的。

Specifically, for questions 1, 2, and 4 take a look at Hibernate cascading: 具体来说,对于问题1、2和4,请看一下Hibernate级联:

  1. Hibernate Documentation on cascading 有关级联的Hibernate文档
  2. Mkyong Article on cascading Mkyong有关级联的文章

For question 3, Hibernate will automatically fetch the other entities once you request them (by calling their get method). 对于问题3,Hibernate将在您请求其他实体后自动获取它们(通过调用它们的get方法)。

Have you look into CascadeType? 你看过CascadeType吗? Here is a tutorial on this subject. 是有关此主题的教程。 HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM