標題問題出現的可能比較多,現在將原因及解決辦法彙總如下:
例子1: 因爲實體類中id的屬性和hbm.xml配置文件中id的屬性不一致造成的
實體類中的id屬性是:
-
public class ThreadPushFail {
-
private long id;
-
-
-
-
private long pushMessageId;
hbm.xml配置文件中id的屬性:
-
<hibernate-mapping>
-
<class name="com.tdr.push.entity.ThreadPushFail" table="t_threadPushFail" lazy="true">
-
<id name="id" type="int">
-
<column name="ID" precision="19" scale="0">
-
<comment>主鍵id</comment>
-
</column>
-
<generator class="identity"/>
-
</id>
一個是int,一個是long
解決方案:是id的屬性保持一致。
|
例子2:對象複製時導致,因爲hibernate的sessionFactory().getSession中不能存在2個相同id的對象
用BeanUtils.copyProperties(B,A)把A對象的所有屬性都copy的B對象中 並把B的主鍵setId(null)放空掉 |