当前位置: 代码迷 >> Web前端 >> JPA中的多对多双向联系关系实体定义与注解设置
  详细解决方案

JPA中的多对多双向联系关系实体定义与注解设置

热度:498   发布时间:2012-08-30 09:55:54.0
JPA中的多对多双向关联实体定义与注解设置
本例来至于 :itcast
第一步:
照样导入JPA实现的产品jar包
在classpath下建立META-INF persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<!-- 以transaction-type下是 事务提交类型有两种事务:第一、本地事务(在同一个数据库中完成事务)  第二、全局事务(在不同数据库中需要在同一事务中完成不同数据库的操作)-->
<persistence-unit name="person" transaction-type="RESOURCE_LOCAL">
<properties>
<!-- 使用的方言 -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<!-- 数据库驱动 -->
<property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver" />
<!-- 数据库用户名 -->
<property name="hibernate.connection.username" value="root" />
<!-- 数据库密码 -->
<property name="hibernate.connection.password" value="liyong" />
<!-- 数据库连接url -->
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/student?useUnicode=true&amp;characterEncoding=UTF-8" />
<!-- 表结构发生变化的时候更新表结构 ,表不存在是创建表-->
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>

第二步:编写Student.java Teacher。java

Student.java

/**
* 多对多JPA规范没有规定关系维护端 可以根据我们自己觉得
*
* @author Administrator
*
*/
@Entity
public class Student {

private Integer id;
private String name;
private Set<Teacher> teachers = new HashSet<Teacher>();

public Student() {
}

public Student(String name) {
this.name = name;
}

@ManyToMany(cascade = CascadeType.REFRESH)
// @JoinTable指定这个关联表如果不使用则外键表外键名使用默认值
// joinColumns指定关联表外键名(关系维护端)
// inverseJoinColumns指定关联表外键名(关系被维护端)
@JoinTable(name = "stuent_teacher", joinColumns = @JoinColumn(name = "student"), inverseJoinColumns = @JoinColumn(name = "teacher"))
public Set<Teacher> getTeachers() {
return teachers;
}

public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}

@Id
@GeneratedValue
public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

@Column(length = 12)
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

/*
* 建立关联关系 对应到关联表是建立关联外键关系
*/
public void addTeachers(Teacher teacher) {
this.teachers.add(teacher);
}

/*
* 解除关系 对应到关联表是删除关联外键关系
*
*
*/
// 下面判断这个对象是否存在根据重写hashCode()和equeals()
public void removeTeahcer(Teacher teacher) {
if (this.teachers.contains(teacher)) {
this.teachers.remove(teacher);
}
}

/*
* 判断该对象是否为同一对象使用Id来判断
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}

}

Teachar.java

@Entity
public class Teacher {

private Integer id;
private String name;
private Set<Student> students=new HashSet<Student>();

public Teacher(){}
public Teacher(String name ){
this.name=name;
}
public Teacher(String name ,Integer id){
this.name=name;
this.id=id;
}
@ManyToMany(cascade=CascadeType.REFRESH,mappedBy="teachers")
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
@Id @GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=12)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}


}

第三步: 编写单元测试


@Test
public void save()
{

EntityManagerFactory factor=Persistence.createEntityManagerFactory("person");
EntityManager entity= factor.createEntityManager();
entity.getTransaction().begin();
Student student=new Student("李勇");
//将学生持久化到数据库
entity.persist(student);
//将老师持久化到数据库
Teacher teacher=new Teacher("张老师");
entity.persist(teacher);
entity.getTransaction().commit();
entity.close();
factor.close();
}


/**
* 建立学生跟老师的关系
*/
@Test
public void BuildTS()
{

EntityManagerFactory factor=Persistence.createEntityManagerFactory("person");
EntityManager entity= factor.createEntityManager();
entity.getTransaction().begin();
Student student=entity.find(Student.class,1);
student.addTeachers(entity.getReference(Teacher.class,1));
//此时建立学生和老师的关系  --》创建关联表
entity.getTransaction().commit();
entity.close();
factor.close();
}

/**
* 删除学生跟老师的关系
*/
@Test
public void DeleteTS()
{
EntityManagerFactory factor=Persistence.createEntityManagerFactory("person");
EntityManager entity= factor.createEntityManager();
entity.getTransaction().begin();
Student student=entity.find(Student.class,1);
student.removeTeahcer(entity.getReference(Teacher.class,1));
entity.getTransaction().commit();
entity.close();
factor.close();
}
/*
* 删除老师(关系被维护端)先解除关系,然后删除对象
*/
@Test
public void deleteTeacher()
{
EntityManagerFactory factor=Persistence.createEntityManagerFactory("person");
EntityManager entity= factor.createEntityManager();
entity.getTransaction().begin();
Student student=entity.find(Student.class,1);
Teacher teacher=entity.getReference(Teacher.class,1);
student.removeTeahcer(teacher);
entity.remove(teacher);
entity.getTransaction().commit();
entity.close();
factor.close();
}
/*
* 删除学生  因为这里是Student为关系维护端所有删除学生时不用先删除关系
*/
@Test
public void deleteStudent()
{
EntityManagerFactory factor=Persistence.createEntityManagerFactory("person");
EntityManager entity= factor.createEntityManager();
entity.getTransaction().begin();
Student student=entity.find(Student.class,1);
entity.remove(student);
entity.getTransaction().commit();
entity.close();
factor.close();
}
}

第四步:测试....

源代码见附件:

  相关解决方案