日期:2014-05-18 浏览次数:20648 次
Paper类:
package com.donald.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
@Entity
public class Paper {
private Integer id;
private String name;
private Set<Subject> subjects = new HashSet<Subject>();
@GeneratedValue
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name="pater_subject",
joinColumns={@JoinColumn(name="paperId")},
inverseJoinColumns={@JoinColumn(name="subjectId")}
)
public Set<Subject> getSubjects() {
return subjects;
}
public void setSubjects(Set<Subject> subjects) {
this.subjects = subjects;
}
}
Subject类:
package com.donald.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
@Entity
public class Subject {
private Integer id;
private String name;
private Set<Paper> papers = new HashSet<Paper>();
@GeneratedValue
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(mappedBy="subjects")
public Set<Paper> getPapers() {
return papers;
}
public void setPapers(Set<Paper> papers) {
this.papers = papers;
}
}
测试代码:
Session session = factory.openSession();
Paper p = (Paper)session.get(Paper.class, 1);
System.out.println(p.getSubjects());