我有3个实体。即A B C实体A和B具有一对一的关系。 B和C有多对多的关系。
@Entity
@Access(AccessType.FIELD)
class A{
@OneToOne(cascade=CascadeType.ALL)
private B b;
}
@Entity
@Access(AccessType.FIELD)
class B{
@ManyToMany(cascade = CascadeType.ALL, mappedBy="b")
@JoinTable(name ="C_B", joinColumns=@JoinColumn(name="B_id"), inverseJoinColumns=@JoinColumn(name="C_id"))
Set<C> C = new HashSet<C>();
@OneToOne(cascade=CascadeType.ALL)
private A a;
}
@Entity
@Access(AccessType.FIELD)
class C{
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name ="C_B", joinColumns=@JoinColumn(name="C_id"), inverseJoinColumns=@JoinColumn(name="B_id"))
Set<B> b = new HashSet<B>();
}
我为A创建实体并创建实体B并设置a.setB(b)
和b.setA(a)
并保持不变。它保存在表格中。但是如何设置B与B之间的关系,因为它不是所有者?
我试过了
a.setB(b);
b.setA(a);
b.setC(c);
它没有在连接表C_B中创建任何条目。
创建
a.setB(b);
b.setA(a);
b.setC(c);
c.setB(b);
抛出空指针异常。 堆栈跟踪
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) Caused by: java.lang.NullPointerException
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.type.IntegerType.next(IntegerType.java:59)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.engine.Versioning.increment(Versioning.java:108)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.event.def.DefaultFlushEntityEventListener.getNextVersion(DefaultFlushEntityEventListener.java:365)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.event.def.DefaultFlushEntityEventListener.scheduleUpdate(DefaultFlushEntityEventListener.java:257)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:128)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:196)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) at org.hibernate.ejb.AbstractEntityManagerImpl$1.beforeCompletion(AbstractEntityManagerImpl.java:515)
2013-10-30 22:22:39,652 ERROR [STDERR] (http-0.0.0.0-8080-3:) ... 77 more
如何建立B和C之间的关系
Setters看起来像这样
setB(B b){
this.B.add(b);
}
setC(C c){
this.C.add(c);
}