读书人

Hibernate多对多配备加删除总结

发布时间: 2012-12-18 12:43:41 作者: rapoo

Hibernate多对多配置加删除总结
经历了一段时间的hibernate的学习,感觉学到的东西蛮多的,现总结经验如下(主要考虑多对多及多对多的删除,网上这方面的资料比较少):

主表配置:

<class name="com.google.musicstore.domain.CardMain" table="card">
<id name="cardid" column="cardid">
<generator type="string" column="A"
not-null="true"
/>
<property name="B" type="string" column="B"
not-null="true"
/>
<property name="C" type="string" column="C"
not-null="true"
/>
<property name="D" type="string" column="D"
not-null="true"
/>
<property name="E" type="string" column="E"
not-null="true"
/>

<set name="notes" table="card_note"
lazy="false"
inverse="false"
cascade="save-update"
>
<key column="cardid" not-null="true"/>
<many-to-many column="noteid"/>
</set>
</class>



从表:

<class name="com.google.musicstore.domain.Note" table="note">
<id name="noteid" column="noteid">
<generator type="string" column="note"
not-null="true"
/>
<list name="cards" table="CARD_NOTE" lazy="false" inverse="true" cascade="save-update"
>
<key column="noteid" />
<list-index column="id" />
<many-to-many />
</list>
</class>

以上配置当删除主表示正常,删除从表会报错.

删除从表时要先删除级联关系,然后再删除从表

public void delete(Note note) {

Session session = null;

Transaction tx = null;

try {

session = hibernateManager.getSessionFactory().getCurrentSession();

tx = session.beginTransaction();

String sql="delete from CARD_NOTE where note_recordid='"+note.getRecordid()+"'";

System.out.println(sql);

SQLQuery query = session.createSQLQuery(sql);

query.executeUpdate();

session.delete(note);

tx.commit();

} catch (Exception e) {

log.error(this, e);

if (tx != null) {

tx.rollback();

}

throw new RuntimeException(e);

}

}

读书人网 >编程

热点推荐