我想使用一个类来映射三个表,据我所知,javax.persistance提供了@SecondaryTable注释,可以将两个表映射到一个类
使用@SecondaryTables映射多个表。
您可以使用类级批注将单个实体 Bean 映射到多个表。要表示某列位于特定表中,请使用 的 table 参数 。@SecondaryTables
@Column
@JoinColumn
例如,有 3 个实体,即: 、 & :Name
Address
Student
Name
实体将如下所示:
@Entity
@Table(name="name")
public class Name implements Serializable {
@Id
@Column(name="id")
private int id;
@Column(name="name")
private String name;
public Name(){}
public Name(int id,String name){
this.id=id;
this.name=name;
}
//getters and setters
}
Address
实体将如下所示:
@Entity
@Table(name="address")
public class Address implements Serializable {
@Id
@Column(name="id")
private int id;
@Column(name="address")
private String address;
public Address(){}
public Address(int id, String address) {
super();
this.id = id;
this.address = address;
}
//getters and setters
}
Student
实体将如下所示:
@Entity
@Table(name="student")
@SecondaryTables({
@SecondaryTable(name="name", pkJoinColumns={
@PrimaryKeyJoinColumn(name="id", referencedColumnName="student_id") }),
@SecondaryTable(name="address", pkJoinColumns={
@PrimaryKeyJoinColumn(name="id", referencedColumnName="student_id") })
})
public class Student implements Serializable {
@Id
@Column(name="student_id")
private int studentId;
@Column(table="name")
private String name;
@Column(table="address")
private String address;
public Student(){}
public Student(int studentId){
this.studentId=studentId;
}
//getters and setters
}
商店喜欢:
Student s= new Student(1);
session.save(s);
Name n=new Name(s.getStudentId(),"Bilal Hasan");
session.save(n);
Address address = new Address(s.getStudentId(), "India");
session.save(address);
Student ob = (Student)session.get(Student.class, s.getStudentId());
System.out.println(ob.getStudentId());
System.out.println(ob.getName());
System.out.println(ob.getAddress());
输出:
1
Bilal Hasan
India