Hibernate 多对多 删除操作(many-to-many)
Hibernate多对多的例子不少,但仔细一看,大多数都是保存的,删除谈的少,但问题还不少,因此有必须简单测试一下,以下我们来个简单的多对多关系建立
老师Teacher 与 课程Course 是一个多对多的关系,Pojo与XMl配置如下。
Pojo
/**
* Course Entity
* see table: tbl_course
*/
package com.leo.domain;
import java.util.HashSet;
import java.util.Set;
/**
* @author superleo
*
*/
public class Course {
private String id;
private String name;
private Set<Teacher> teachers = new HashSet<Teacher>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Teacher> getTeachers() {
return teachers;
}
public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}
}
/**
* Teacher Entity
* see table: tbl_teacher
*/
package com.leo.domain;
import java.util.HashSet;
import java.util.Set;
/**
* @author superleo
*
*/
public class Teacher {
private String id;
private String name;
private Set<Course> courses = new HashSet<Course>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}
Hibernate配置文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.leo.domain.Course" table="tbl_course"
batch-size="100" dynamic-insert="true" dynamic-update="true">
<id name="id" column="id">
<generator class="uuid" />
</id>
<property name="name" column="name" type="string" />
<set access="property" lazy="true" inverse="false"
cascade="save-update" name="teachers" batch-size="10" fetch="select"
table="tbl_teacher_course">
<key column="fk_course_id" />
<many-to-many class="com.leo.domain.Teacher"
column="fk_teacher_id" />
</set>
</class>
</hibernate-mapping>
Xml代码:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.leo.domain.Teacher" table="tbl_teacher"
batch-size="100" dynamic-insert="true" dynamic-update="true">
<id name="id" column="id">
<generator class="uuid" />
</id>
<property name="name" column="name" type="string" />
<set access="property" lazy="true" inverse="true"
cascade="save-update" name="courses" batch-size="10" fetch="select"
table="tbl_teacher_course">
<key column="fk_teacher_id" />
<many-to-many class="com.leo.domain.Course"
column="fk_course_id" />
</set>
</class>
</hibernate-mapping>