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

相关推荐