第一种:@EmbeddedID

package org.hibernate.first.model;


import java.io.Serializable;


public class TeacherPK implements Serializable{  //必须实现Serializable接口  序列号

private int id;

private String name;

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;

}

@Override    //重写 equals()和hashCode()方法

public boolean equals(Object o){

if (o instanceof TeacherPK) {

TeacherPK pk = (TeacherPK)o;

if (this.id == pk.getId() && this.name.equals(pk.getName())) {

return true;

}

}

return false;

}

@Override

public int hashCode(){

return this.name.hashCode();

}

}


操作Model类:


@Entity  


public class Teacher {


private String title;

private TeacherPK tPk;

@EmbeddedId

public TeacherPK gettPk() {

return tPk;

}

public void settPk(TeacherPK tPk) {

this.tPk = tPk;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

}


Junit4测试类:

public class TestTeacher {


@Test

public void testTeacher(){

Teacher t = new Teacher();

TeacherPK tPK = new TeacherPK();

tPK.setId(1);

tPK.setName("jim");

t.settPk(tPK);

t.setTitle("教授");

Configuration cfg = new AnnotationConfiguration();

SessionFactory sessionFactory = cfg.configure().buildSessionFactory();

Session session = sessionFactory.openSession();

session.beginTransaction();

session.save(t);

session.getTransaction().commit();

session.close();

sessionFactory.close();

}


}

测试成功图片:

155630533.jpg


另外两种方式:

1.@ID + @IDClass的方式:

在类的地方加IDClass

@IdClass(TeacherPK.class)

public class Teacher {

..................

}

然后在想设为主键的地方加@ID就可以了


2.Embeddable + @ID 的方式:

在PK类的地方加:@Embeddable,然后在model类的地方生命PK类setter和getter的方法进去,在get方法那里加上ID就可以了。