1>
错误显示:
net.sf.hibernate.PropertyValueException: not-null property references a null or transient value: com.Order.customer
部分原文件:(
customer
和
order
类关系:一对多关联)
Order.hbm.xml
……………
<
many-to-one
name
=
"customer"
column
=
"CUSTOMER_ID"
class
=
"com.Customer"
not-null
=
"true"
cascade
=
"save-update"
/>
执行文件:
………
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
// Create some data and persist it
tx = session.beginTransaction();
Customer customer=new Customer();
customer.setName("Jack");
Order order=new Order();
order.setOrderNumber("Jack_Order001");
session.save(customer);
session.save(order);
tx.commit();
原因分析:因为在执行代码中,没有将
customer
和
order
类一对多关联起来,若单独持久化两个类:
session.save(customer);session.save(order);
则在保存
order
的时候,由于
CUSTOMER_ID
是与
customer
类外键,因此无法读取
customer_id,
而在
order.hbm.xml
中指定其不为空,则产生了以上错误。
问题解决:
not-null
=
"true"
改为:not-null="false" 虽然程序无问题,但order表 CUSTOMER_ID为空,不符合逻辑。应该将指定其一对多的关联。
order.setCustomer(customer);
customer.getOrders().add(order);
2
〉
错误显示:
RROR SessionImpl:2400 - Could not synchronize database state with session
net.sf.hibernate.exception.GenericJDBCException: could not delete collection: [com.Customer.orders#2]
部分原文件:
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(3));
session.delete(customer);
tx.commit();
原因分析:因为
cascade
默认值为
none
,所以当删除
customer
时,不会自动删除与其关联的
order
对象。
问题解决:添加语句
cascade
=
"delete"