java多对多双向关联

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhang1996922/article/details/82593046

package hibernate002test.copy;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

public class Student {
private int id;
private String name;
private Set<Teacher> teacher = new HashSet<Teacher>();

@ManyToMany(mappedBy = "student")
public Set<Teacher> getTeacher() {
    return teacher;
}

public void setTeacher(Set<Teacher> teacher) {
    this.teacher = teacher;
}

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

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

public String getName() {
    return name;
}

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

}
package hibernate002test.copy;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

public class Teacher {
private int id;
private String name;
private Set<Student> students = new HashSet<Student>();

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

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

public String getName() {
    return name;
}

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

@ManyToMany
@JoinTable(name = "s_t", joinColumns = { @JoinColumn(name = "teacher_id") }, inverseJoinColumns = {
        @JoinColumn(name = "student_id") })
public Set<Student> getStudents() {
    return students;
}

public void setStudents(Set<Student> students) {
    this.students = students;
}

}
测试类
package datatest;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
/**
* 在一对一双向关联时要使用例如:@OneToOne(mappedBy=”wife”)
* @author Lenovo
*
*/
public class Test {

@org.junit.Test
public void test() {
   new SchemaExport(new AnnotationConfiguration().configure()).create(false,true);
}

}

猜你喜欢

转载自blog.csdn.net/zhang1996922/article/details/82593046
今日推荐