2011-11-22 123 views
6

前自動保存父我有一個父子關係:休眠:節電兒童

@Entity 
@Table(name = "user") 
public final class User 
{ 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Integer userID; 

    @Column(name = "username") 
    private String userName; 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "admin") 
    private Set<News> news; 
} 

@Entity 
@Table(name = "news") 
public final class News 
{ 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private int newsID; 

    @ManyToOne(cascade = CascadeType.PERSIST) 
    @JoinColumn(name = "userID") 
    private User admin; 

    @Column(name = "newsText") 
    private String newsText; 

    @Column(name = "dateOfPost") 
    private Date dateOfPost; 
} 

這裏User是家長和News是孩子。之所以我有級聯操作,是因爲我希望刪除/保留所有News對象時刪除/保留相應的User。另外,當我堅持一個News對象時,我希望相應的User被保留[但如果News被刪除則不會被刪除]。我有如下節省了News對象服務的方法:

User u = new User("administrator"); 
News n = new News("News text"); 
n.setUser(u);  
u.addNews(n); 

session.save(n); 

對於上面的代碼中,我得到以下異常:

org.hibernate.exception.ConstraintViolationException: could not insert: [com.maximus.db.model.News] 
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96) 
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) 
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64) 
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345) 
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852) 
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71) 
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273) 
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320) 
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203) 
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129) 
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210) 
    at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56) 
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195) 
    at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50) 
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93) 
    at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713) 
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701) 
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697) 
    at com.maximus.db.dao.NewsDAOImpl.addNews(NewsDAOImpl.java:17) 
    at com.maximus.db.service.NewsServiceImpl.addNews(NewsServiceImpl.java:31) 
    at com.maximus.test.db.service.NewsServiceTest.testAddNewsWithNewUser(NewsServiceTest.java:36) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    at java.lang.reflect.Method.invoke(Unknown Source) 
    at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99) 
    at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81) 
    at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) 
    at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75) 
    at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45) 
    at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:66) 
    at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35) 
    at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42) 
    at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) 
    at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52) 
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) 
    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: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'userId' cannot be null 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) 
    at java.lang.reflect.Constructor.newInstance(Unknown Source) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) 
    at com.mysql.jdbc.Util.getInstance(Util.java:384) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498) 
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959) 
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113) 
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568) 
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113) 
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2409) 
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2327) 
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2312) 
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94) 
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57) 
    ... 38 more 

可能是什麼問題嗎?

我在嘗試保存孩子的服務方法不正確嗎?我應該總是保存父母嗎?

謝謝。

更新:如果我將用戶保存爲session.save(u)而不是新聞,則一切正常。所以現在仍然存在的問題是,拯救孩子而不是父母是不正確的?如果不是,那麼我該如何實現它?

+0

你試過** session.save(u)**代替嗎? – ManuPK

+1

@ManuPK如果我使用'session.save(u)',那麼一切都很好。我問,如果我做'session.save(n)'是不正確的?如果沒有錯,那我該怎麼做? –

回答

6

你必須做以下things.These是: - 從消息面

  • 級聯刪除選項。
  • 在您的使用案例中,您擁有全新的新聞項目和新用戶。爲什麼您要保留新聞項目 。堅持用戶對象。兩者都將持續。
  • 在另一個使用案例中,如果您有現有用戶並且您想要添加新的新聞項目 。在service/dao實現中,創建一個方法 以保持消息對象傳遞用戶標識。然後你可以使用 加載/獲取關聯使用並堅持新聞項目
+0

所以要在評論中明確回答OP的問題:'session.save(n)'是不正確的。 – Stewart

1

我相信你不需要在子端設置級聯。只需在父級(User.news)上使用Cascade.ALL即可。

還有一件事,如果你要在刪除用戶時刪除新聞(就像你在文章中提到的那樣),我相信你需要在父節點上添加級聯類型Delete Orphan。