hibernate 一个类映射多个表
使用 @SecondaryTables 注解实现一个类映射多个表
比如现有三个实体: 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 }
Test:
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
shareimprove this answer
edited Mar 27 '14 at 13:13
answered Mar 27 '14 at 13:06
Rembo
2,29911230
相关推荐
solarspot 2020-07-28
houmenghu 2020-11-17
我心似明月 2020-11-09
oraclemch 2020-11-06
ltd00 2020-09-12
康慧欣 2020-09-10
waveclouds 2020-09-04
蓝色深海 2020-09-15
jincheng 2020-09-01
思君夜未眠 2020-08-25
取个好名字真难 2020-08-06
歆萌 2020-08-03
阳光之吻 2020-08-03
婷婷小屋 2020-07-28
MLXY 2020-07-26
dxbjfu0 2020-07-26
songbinxu 2020-07-19
83520298 2020-07-06