0

我有 3 个实体。即 ABC 实体 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设置B和C之间的关系呢?

我试过以下

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之间的关系

二传手看起来像这样

setB(B b){
        this.B.add(b);
    }

    setC(C c){
        this.C.add(c);
    }
4

0 回答 0