0

我们从 Hibernate 尝试到update一个不存在的表时遇到了一个奇怪的异常。下面是一个简单的例子(Hibernate 3.6.0 Final + Oracle 11g + Pure Java)。

这里 Class_A 在 TABLE_PER_CLASS 层次结构策略中是抽象的(每个具体类的表)。这是简单的版本,请告诉我我们的代码有什么问题:

Class_A

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Class_A {
    @Id
    @Column(name="blabla")
    public long myId = 0;
}

Class_B

@Entity
public class Class_B extends Class_A {
    private String myString = "Hellos - I'm Class_B!";
}

Class_C

@Entity
public class Class_C extends Class_A {
    private String myString = "Hellos - I'm Class_C!";

    @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn
    @OrderColumn(name="list_order")
    public List<Class_A> as;
}

代码

Class_C c = new Class_C();
c.myId = 92;
Class_B b = new Class_B();
b.myId = 10;
List<Class_A> bs = new ArrayList<Class_A>();
bs.add(0, b);
c.as = bs;

Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(c);
session.getTransaction().commit();
session.close();

碰撞

commit(),Hibernate 尝试这个 SQL:
Hibernate: update Class_A set as_blabla=?, list_order=? where blabla=?

然后崩溃:

java.sql.BatchUpdateException: ORA-00942: table or view does not exist

    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:17660)
    at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:771)
    at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:188)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)

为什么 Hibernate 会这样做?

非常感谢!
-十种

4

1 回答 1

1

我认为您需要使关系成为双向的,并将一对多映射为多对一的反向关系。实际上,如果您查看http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/inheritance.html#inheritance-limitations,您会注意到多态一对多是仅限于inverse="true"每个具体类策略的表中。

因此,试试这个:

在 A 类:

@ManyToOne
@JoinColumn
private Class_C c;

在 C 类:

@OneToMany(mappedBy = "c")
private List<Class_A> as;
于 2011-02-24T15:30:59.823 回答