2011-04-19 110 views
1

我有兩個實體Person和Order由JPA/Hibernate Entity Manager管理。我試圖通過註釋他們創造一個雙向一到兩個實體來說之間一對多的關係如下:JPA雙向一對多外鍵問題

人:

@Id 
@Column(name="PERSON_ID") 
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PERSON_SEQ") 
@SequenceGenerator(name = "PERSON_SEQ", sequenceName = "PERSON_SEQ") 
private Integer personId; 

@OneToMany(mappedBy="person", cascade=CascadeType.ALL) 
private List<Order> orders = new ArrayList<Order>(); 

public void addOrder(Order o) 
{ 
    getOrders().add(o); 
    o.setPerson(this); 
} 

訂單:

@ManyToOne 
@JoinColumn(name="PERSON_ID") 
private Person person; 

我再測試代碼:

@Test 
@Transactional 
@Rollback(value=false) 
public void populateTable() { 
    WatchUtil.startTask("Persist Person"); 

    for (int i = 0; i < 25; i++) { 
     Person tmpPerson= new Person(); 
     tmpPerson.setName("Person1"); 
     Order order = new Order(); 
     order.setOrderNumber("Order1"); 
     tmpPerson.addOrder(order); 
     dao.persist(tmpPerson); //calls entitymanager.persist(); does not call flush 
    } 
    WatchUtil.endTask(); 
} 

這給了我一個約束例外:

2011-04-19 06:25:12,713 INFO [org.springframework.test.context.transaction.TransactionalTestExecutionListener] - <Began transaction (9): transaction manager [[email protected]]; rollback [false]> 
2011-04-19 06:25:12,713 DEBUG [org.hibernate.SQL] - <insert into PERSON (PERSON_ID, NAME) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)> 
2011-04-19 06:25:12,775 DEBUG [org.hibernate.SQL] - <insert into ORDER (ORDER_NUMBER PERSON_ID, ORDER_ID) values (?, ?, ?, ?, ?, ?)> 
2011-04-19 06:25:12,947 WARN [org.hibernate.util.JDBCExceptionReporter] - <SQL Error: 2291, SQLState: 23000> 
2011-04-19 06:25:12,947 ERROR [org.hibernate.util.JDBCExceptionReporter] - <ORA-02291: integrity constraint (BLUE_SITE.FKE2BCFD5374D88D96) violated - parent key not found> 
2011-04-19 06:25:12,947 WARN [org.hibernate.util.JDBCExceptionReporter] - <SQL Error: 2291, SQLState: 23000> 
2011-04-19 06:25:12,947 ERROR [org.hibernate.util.JDBCExceptionReporter] - <ORA-02291: integrity constraint (BLUE_SITE.FKE2BCFD5374D88D96) violated - parent key not found> 
2011-04-19 06:25:12,947 ERROR [org.hibernate.event.def.AbstractFlushingEventListener] - <Could not synchronize database state with session> 
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update 
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) 
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) 
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) 
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266) 
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) 
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) 
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) 
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) 
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:304) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
    at java.lang.reflect.Method.invoke(Method.java:597) 
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240) 
    at $Proxy32.flush(Unknown Source) 
    at test.JpaDao.persist(JpaDao.java:37) 
    at test.PersonJpaDaoTests.populateTable(MemberJpaDaoTests.java:156) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
    at java.lang.reflect.Method.invoke(Method.java:597) 
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) 
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) 
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) 
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) 
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) 
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) 
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) 
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) 
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) 
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) 
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) 
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) 
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) 
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) 
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) 
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) 
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) 
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 
Caused by: java.sql.BatchUpdateException: ORA-02291: integrity constraint (BLUE_SITE.FKE2BCFD5374D88D96) violated - parent key not found 
    at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:367) 
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:9119) 
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70) 
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268) 
    ... 44 more 
StopWatch '-- DEBUGGING --': running time (millis) = 0 

收到此錯誤後,我從數據庫中刪除約束。然而,兩張表都填充了父母和孩子之間的密鑰錯位。任何人都可以引導我走向正確的方向嗎?我查看了一堆帖子,他們聲稱創建一個像Person.addOrder(Order o)這樣的方法應該處理一些事情。

注意到我正在使用Oracle序列來生成我的ID也很重要。 我也爲每個類創建了hashCode和Equals方法。

+0

'addOrder()'應該調用'setPerson()',但它調用'setMember()' - 是否是一個錯字? – axtavt 2011-04-19 11:29:56

+0

好趕上axtavt。我不得不簡化我的發帖示例,我一定錯過了。 – 2011-04-19 11:49:32

+0

我發現了這個問題。 PERSON表上有一個從不同序列插入的觸發器。這導致訂單中的Foriegn密鑰未對齊。我不知道觸發器是如何到達那裏的,但我懷疑它可能是通過自動DDL生成的,我可能忘記了我做了它或可疑的DBA j/k。我讀了另一篇文章,有人有這個問題,並沒有點擊,因爲我不相信我有觸發器。如果你有同樣的問題,我會建議檢查觸發器以防萬一。 – 2011-04-19 11:50:41

回答

2

我在查看數據庫中的對象後發現問題。在我的項目的初始設置過程中,我沒有使用序列,但是我已經自動生成DDL開啓。這在數據庫中創建了一個觸發器。

過了一段時間,我決定使用一個序列。包含序列的新配置與舊觸發器衝突,產生約束錯誤。一旦我刪除這些觸發器,異常就消失了。