父类
public class Father {
private Integer id;
private String name;
private Set<Child> children=new HashSet<Child>();
...
父类的hibernate配置
<set name="children" cascade="all" inverse="true">
<!-- key是确定关联的外键列,就是many-to-one中的column-->
<key column="fatherId"></key>
<one-to-many class="Child"/>
</set>
子类
public class Child {
private Integer id;
private String name;
private Father father;
...
子类的hibernate配置
<many-to-one name="father" class="Father">
<column name="fatherId"></column>
</many-to-one>
下面是测试
@SuppressWarnings("deprecation")
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
Father f=new Father();
f.setName("父1号");
Child c=new Child();
c.setName("子1号");
Child c2=new Child();
c2.setName("子2号");
f.getChildren().add(c);
f.getChildren().add(c2);
c.setFather(f);
c2.setFather((Father)session.get(Father.class, 47));
session.save(f);
tx.commit();
session.close();
1.这个时候inverse设置为true表示是否反转设置为了是,就是反转给子类就是多的一方来控制主外键的关联.这里就是由子类来控制主外键所以后台运行后生成的sql语句只有3句
Hibernate: insert into test_father (name, id) values (?, ?)
Hibernate: insert into test_child (name, fatherId, id) values (?, ?, ?)
Hibernate: insert into test_child (name, fatherId, id) values (?, ?, ?)
结果就是数据库中的子类,子2号的fatherId是以子类就是主控方来设置,即session.get(Father.class,47)这个父类的id
2.如果inverse设置为了false表示是否反转设为了否,就是不反转,主控方在自己,那么结果就是主外键的关联关系是有自己,也就是一的一方来控制.
这样后台的sql语句就变成了5句:
Hibernate: insert into test_father (name, id) values (?, ?)
Hibernate: insert into test_child (name, fatherId, id) values (?, ?, ?)
Hibernate: insert into test_child (name, fatherId, id) values (?, ?, ?)
Hibernate: update test_child set fatherId=? where id=?
Hibernate: update test_child set fatherId=? where id=?
因为这个时候子类的fatherId不知道是"父1号"还是 session.get(Father.class,47).所以都更新为f.getChildren().add(c2)这里所表现的fatherId也就是说是从"父1号"的对象中
直接获取id来作为子类的fatherId.