简体   繁体   English

Hibernate一对多更新一个孩子

[英]Hibernate update one child in one to many

I'm new to hibernate so I don't understand some basic things. 我是冬眠的新手,所以我不了解一些基本的知识。 I have Entity A and B. And it's a one to many relationship. 我有实体A和实体B。这是一对多的关系。 So A can have multiple B's. 因此,A可以有多个B。 Below is code to save when adding a new B to A. That's working. 下面是将新B添加到A时要保存的代码。

    A a= this.aService.getAById(AID);
    b.setA(a);
    a.getBSet().add(b);
    this.aService.saveA(a);

But how can I edit one B entity? 但是如何编辑一个B实体? Do I first have to remove the B entity that I want to edit from the Set? 我是否首先必须从集合中删除要编辑的B实体? Really sorry if it's an obvious question. 真的很抱歉,如果这是一个明显的问题。 But I already searched with Google and the only examples I can find is when you make new entities and not edit. 但是我已经在Google搜索过,唯一可以找到的例子是创建新实体而不进行编辑时。

You need to first get B from the database. 您需要首先从数据库中获取B。

B b = this.bService.getBById(BID);
...
//update b
this.bService.updateB(b);
//Whether you want update entity B:
Public void updateBEntity(Integer idB) {
 B b = session.get(B.class, idB);
//For edit you only have to use the set's methods:
b.setName(anything);
b.setPosition(2);
//final y, that's all
session.merge(b);
} 
//In your class controller or Action 

More information about merge/persist: 有关合并/持久性的更多信息:

What is the difference between persist() and merge() in Hibernate? Hibernate中的persist()和merge()有什么区别?

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

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