org.hibernate.PersistentObjectException: detached entity passed to persist異常

來源:互聯網
上載者:User

標籤:io   java   sp   資料   on   問題   cti   bs   as   

再用jpa+spring+struts2開發的是時候遇到一個問題(採用了註解的方式,xml配置的道理是一樣的),當我在註冊使用者的時候,註冊第一個使用者沒有問題,但註冊第二個使用者開始就會拋出一個異常:

javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.dalton.domain.User

 

原因是第二次插入使用者的時候,還沒有執行個體化到資料庫就有了ID值,而且這個ID值是我第一次插入使用者的ID,這是不正常,因為ID沒有設定過,而且JPA預設的行為是只要指定了主鍵建置原則,主鍵就不能設定了,一旦不為空白或者0就被認為是已經儲存到了資料庫中,一旦調用persist()方法就會拋出上面的異常。

為什麼會還有第一次的插入使用者的資訊呢,原因就是action的範圍設定錯誤了,採用了預設單例的設定,對於Action來說必須採用prototype(每次調用建立一個對象)的範圍,修改方法是:在Action上就一個註解@Scope("prototype")

就可以輕鬆搞定。

org.hibernate.PersistentObjectException: detached entity passed to persist異常

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.