本文主要是介绍hibernate中inverse=true粗解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一个Person可以参加多个Event,一个Event有多个Person参加。
映射文件如下:
< hibernate-mapping package ="events" >
< class name ="Person" table ="person" >
< id name ="id" column ="person_id" >
< generator class ="native" />
</ id >
< property name ="age" length ="0" />
< property name ="firstname" />
< property name ="lastname" />
< set name ="events" table ="person_event" >
< key column ="person_id" />
< many-to-many column ="event_id" class ="events.Event" />
</ set >
</ class >
</ hibernate-mapping >
< hibernate-mapping >
< class name ="events.Event" table ="events" >
< id name ="id" column ="event_id" >
< generator class ="native" />
</ id >
< property name ="date" column ="events_date" type ="timestamp" />
< property name ="title" column ="events_title" />
< set name ="participants" table ="person_event" inverse ="true" >
< key column ="event_id" />
< many-to-many column ="person_id" class ="events.Person" />
</ set >
</ class >
</ hibernate-mapping >
inverse=true的含义: 由双向关联另一方维护该关联,己方不维护该关联(只能进行查询操作)。在上述代码中,由Person方维护该<many-to-many>关系,示例代码如下(以向Person参与的Event中加入新的Event为例):
session.beginTransaction();
Person p = (Person) session.load(Person. class , personId);
Event e = (Event) session.load(Event. class , eventId);
p.getEvents().add(e);//执行该代码时,hibernate会向中间表 person_event中插入person_id和event_id记录,如果换成e.getParticipants().add(p)的话,该代码将不会被执行,即hibernate不会向表person_event中插入记录。
session.getTransaction().commit();
要注意的一点:在双向关联的关系中,映射的column(和table)的值要一致(即要用相同的表名和列名),不然设置为inverse="true"的这方将失去这个双向关系,而变成了一个单向关联。
这篇关于hibernate中inverse=true粗解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!