我在尝试将记录插入我的桌子时遇到错误。
这是hbm.xml
<hibernate-mapping>
<class name="com.pojo.Child" table="SOME_SCHEMA.CHILD" lazy="true">
<id name="primKey" column="ID" type="java.lang.Integer">
<generator class="foreign">
<param name="property">pr</param>
</generator>
</id>
<property name="isAllowed" column="IS_ALLOWED"/>
<property name="ts" column="UPDATE_TS"/>
<one-to-one name="pr" class="com.pojo.Parent" constrained="true"/>
</class>
我的实体对象:Parent.java包含Parent表的所有getter和setter。 Child.java包含&#34; id&#34;作为整数,&#34; pr&#34;作为实例变量(表示外表),IS_ALLOW和UPDATE_TS的getter和setter。
以下是我在CHILD表中插入记录的代码:
public List<Child> insertChildRecords(List<Child> childList, Timestamp timestamp) {
List<Child> notInsertedList = null;
final Session session = sessionFactory.openSession();
for (final Child child : childList) {
if (null != child) {
Transaction transaction = session.beginTransaction();
try {
final Parent pr = new Parent();
pr.setStatusCode("AVAILABLE");
pr.setName("SURNAME");
child.setPr(pr);
child.setTS(timestamp);
session.saveOrUpdate( child);
transaction.commit();
} catch (Exception ex) {
try {
if(null != transaction) {
transaction.rollback();
}
} catch (HibernateException e) {
LOGGER.error("Rollback exception:" +e.getMessage());
}
LOGGER.error("Exception: "
+ ex.getMessage());
LOGGER.error( child.toString());
if (null == notInsertedList) {
notInsertedList = new ArrayList<Child>();
}
notInsertedList.add(child);
}
}
}
return propListNotInserted;
}
我担心的是,我不应该在PARENT表中创建任何记录。我只是使用父ID并尝试使用该ID插入Child。要检索父ID,我设置了各种参数(我假设它等同于本机SQL的WHERE子句)。
当我执行这段代码时,Hibernate会对&#39; childList&#39;中的所有元素抛出异常。
Hibernate: insert into SOME_SCHEMA.CHILD (IS_ALLOWED, UPDATE_TS, ID) values (?, ?, ?)
TRACE type.StringType: binding 'N' to parameter: 1
type.TimestampType: binding '2016-06-29 15:04:10' to parameter: 2
TRACE type.IntegerType: binding '0' to parameter: 3
ERROR util.JDBCExceptionReporter: DB2 SQL Error: SQLCODE=-530, SQLSTATE=23503, SQLERRMC=SOME_SCHEMA.CHILD.FK_CHILD_PARENT_01, DRIVER=3.62.56
ERROR def.AbstractFlushingEventListener: Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: could not insert: [com.pojo.Child]
我想到的主要问题是,Hibernate并没有尝试根据我设置的内容从Parent中获取ID;而是指定&#39; 0&#39; 0到儿童身份证。
我该如何解决这个问题?
提前感谢您的所有答案,感谢您。
答案 0 :(得分:0)
我不应该在PARENT表中创建任何记录。我只是使用父ID并尝试使用该ID插入Child。
那你为什么要这个代码?
final Parent pr = new Parent();
如果要将现有的Parent分配给您正在创建的Child类,则需要查找它,然后将其分配给Child。