http://www.itzhai.com/hibernate-one-to-many-association-mapping-configuration-and-the-cascade-delete-problem.html首先舉一個簡單的一對多雙向關聯的配置:
一的一端:QuestionType類
package com.exam.entity;
import java.util.Set;
public class QuestionType {
private String typeName;
private char typeUniqueness;
private Set quesion;
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public char getTypeUniqueness() {
return typeUniqueness;
}
public void setTypeUniqueness(char typeUniqueness) {
this.typeUniqueness = typeUniqueness;
}
public Set getQuesion() {
return quesion;
}
public void setQuesion(Set quesion) {
this.quesion = quesion;
}
}
配置文件:
<hibernate-mapping package="com.exam.entity">
<class name="QuestionType" table="exam_question_type">
<id name="typeName" column="type_name"></id>
<property name="typeUniqueness" column="type_uniqueness"/>
<set name="quesion" inverse="true" cascade="delete">
<key column="question_type_name"/>
<one-to-many class="Question"/>
</set>
</class>
</hibernate-mapping>
多的一端:Question類
package com.exam.entity;
import java.util.Date;
public class Question {
private int questionNo;
private QuestionType questionType;
private String questionsTitle;
public int getQuestionNo() {
return questionNo;
}
public void setQuestionNo(int questionNo) {
this.questionNo = questionNo;
}
public QuestionType getQuestionType() {
return questionType;
}
public void setQuestionType(QuestionType questionType) {
this.questionType = questionType;
}
public String getQuestionsTitle() {
return questionsTitle;
}
public void setQuestionsTitle(String questionsTitle) {
this.questionsTitle = questionsTitle;
}
}
配置文件:
<hibernate-mapping package="com.exam.entity">
<class name="Question" table="exam_question">
<id name="questionNo" column="question_no" >
<generator class="increment" />
</id>
<many-to-one name="questionType" column="question_type_name"/>
<property name="questionsTitle" column="questions_title" length="200" />
</class>
</hibernate-mapping>
首先說明一下一些常用的屬性:
<many-to-one>元素包含以下屬性:
name:設定映射的持久化類的屬性名
column:設定和持久化類的屬性對應的表的外鍵
class:設定持久化類的屬性的類型
cascade:設定是否級聯
lazy:設定是否延遲加載
<set>元素包含以下屬性:
name:設定映射的持久化類的屬性名
cascade:設置是否級聯
inverse:設定反向控制,如果為true則一的一端不維護外鍵
<key>:設定與所關聯的持久化類對應的表的外鍵。
one-to-many:設定所關聯的持久化類
如果要對一對多關聯映射進行級聯刪除,可以按照上面的舉例進行配置:
首先看到一的一端:
<set name="quesion" inverse="true" cascade="delete">
<key column="question_type_name"/>
<one-to-many class="Question"/>
</set>
這里設置inverse表示一的一端不維護外鍵,設置cascade=”delete”表示刪除一的一端時對關聯到得多的所有的對象也一起刪除
再看到多的一端:
<many-to-one name="questionType" column="question_type_name"/>
這里的column表示外鍵的名,需要和一的一端設置的key標簽里的column保持一致,表示維護同一個鍵值。
可以按照如下的代碼執行刪除操作:
session.beginTransaction();
QuestionType questionType = (QuestionType) session.load(QuestionType.class, "判斷題");
session.delete(questionType);
session.getTransaction().commit();
這里使用load查上來的對象是持久狀態的(Persistent),只有是Persistent狀態的對象才可以使用session.delete()操作進行級聯刪除,由new創建的對象屬于Transient狀態,不能進行session.delete()操作。