当前位置: 代码迷 >> J2EE >> hibernate多对一删除many有关问题
  详细解决方案

hibernate多对一删除many有关问题

热度:132   发布时间:2016-04-22 01:41:36.0
hibernate多对一删除many问题
java程序代码:

SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction ts = session.beginTransaction();

try
{
Order order = (Order) session.get(Order.class, new Long(5));
session.delete(order);
ts.commit();
} catch (Exception ex)
{
ex.printStackTrace();

if (null != ts)
{
ts.rollback();
}
} finally
{
session.close();
}


Order.hbm.xml配置文件:

<class name="com.zhangle.domain.Order" table="orders">

<id name="id" column="id" type="long">
<generator class="increment"></generator>
</id>

<property name="orderNumber" column="ordersNumber" type="string"></property>

<many-to-one name="consumer" class="com.zhangle.domain.Consumer" column="consumer_id" cascade="all"></many-to-one>

</class>

Consumer.hbm.xml配置文件:

<class name="com.zhangle.domain.Consumer" table="consumer">

<id name="id" column="id" type="long">
<generator class="increment"></generator>
</id>

<property name="username" column="username" type="string"></property>

<set name="orders" cascade="all" inverse="false">
<key column="consumer_id"></key>
<one-to-many class="com.zhangle.domain.Order"/>
</set>

</class>


我是想删除数据库orders表中id为5的记录,但是报异常了。是不是我的配置文件写错了啊! 求指教!!!!

异常信息:
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:169)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at com.zhangle.hibernate.ConsumerTest.delete(ConsumerTest.java:142)
at com.zhangle.hibernate.ConsumerTest.main(ConsumerTest.java:20)
Caused by: java.sql.BatchUpdateException: Column 'consumer_id' cannot be null
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 9 more

------解决方案--------------------
楼主的hibernate中 配置了 一对多双向关联关系

“一”的一方是:Consumer
“多”的一方是:Order

在映射配置文件中 “一”的一方 配置 inverse=“true” 放弃级联维护 ,让“多”的一方 来进行维护。

  相关解决方案