在一对多关系中,通常用 @ManyToOne 注释的字段是所有者 - 另一方具有“mappedBy”属性。但是,如果我跳过'mappedBy'并用@JoinColumn(同一列)注释双方,我可以更新双方 - 更改被传播到数据库。
我没有两个单向关系而不是一个双向关系——只有一个连接列。
如果不选择一方作为关系所有者,我会遇到什么问题?
我的实体看起来类似于以下内容:
@Entity
public class B {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "parent_id")
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
private B parent;
@OneToMany()
@JoinColumn(name = "parent_id")
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
private List<B> children = new ArrayList<B>();
...
}
它似乎对性能没有任何影响(至少插入看起来不错)这是一个简单的测试和日志输出:
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
B a = new B("a");
B b = new B("b");
B c = new B("c");
B d = new B("d");
B e = new B("e");
session.save(a);
session.save(b);
session.save(c);
session.save(d);
session.save(e);
session.getTransaction().commit();
System.out.println("all objects saved");
session.beginTransaction();
a.getChildren().add(b);
a.getChildren().add(c);
session.save(a);
session.getTransaction().commit();
System.out.println("b and c added as children");
session.beginTransaction();
a.getChildren().add(d);
a.getChildren().add(e);
session.getTransaction().commit();
System.out.println("e and f added as children");
session.close();
Hibernate: insert into B (fieldInB, parent_id) values (?, ?)
Hibernate: insert into B (fieldInB, parent_id) values (?, ?)
Hibernate: insert into B (fieldInB, parent_id) values (?, ?)
Hibernate: insert into B (fieldInB, parent_id) values (?, ?)
Hibernate: insert into B (fieldInB, parent_id) values (?, ?)
all objects saved
Hibernate: update B set parent_id=? where id=?
Hibernate: update B set parent_id=? where id=?
b and c added as children
Hibernate: update B set parent_id=? where id=?
Hibernate: update B set parent_id=? where id=?
e and f added as children