欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate基础之六:联合主键@EmbeddedId

程序员文章站 2022-04-24 22:30:05
...


一:联合主键类

联合主键就是靠多个属性一起来决定主键
所以要新建主键类,其中要实现
1.Serializable //主键需要传递
2.equals(Object o) //靠主键区分pk,所以必须

3.hashCode()//根据pk的哈希码去查找,所以必须

public class TeacherPK implements Serializable
{
	private int id;
	private String name;//根据这两项属性联合生成主键
	
	public boolean equals(Object o) //靠主键区分pk,所以必须
	{
		if(o instanceof  TeacherPK)
		{
			TeacherPK pk = (TeacherPK)o;//强转
			if(this.id == pk.getId() && this.name.equals(pk.getName()))
			{
				return true;//id和name都分别相等,才是同一主键
			}
		}
		return false;//其余所有情况都返回false
	}

	public int hashCode()//根据pk的哈希码去查找,所以必须
	{
		return this.name.hashCode();	
	}

	
	
	//setter&getter



二:Annotation标注

1.TeacherPK上写@Embeddable
聚合的getPk()上写@Id

2.getPk()上写@EmbeddedId

3.实体上@IdClass(value=TeacherPK.class)
name和id上都要写@Id

@Entity
@Table(name="t_Teacher")
public class Teacher {
	
	private TeacherPK pk;//聚合联合主键

	private int age;
	private Date birthday;
	private String secret;
	private Grade grade;

	//setter&getter
	@EmbeddedId //联合主键的getPK()方法上写 EmbeddedId
	public TeacherPK getPk() {
		return pk;
	}



三:JUnit测试

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        
        
        TeacherPK pk = new TeacherPK();//组装联合主键
        pk.setId(250);
        pk.setName("张三");
		
        Teacher t = new Teacher();
        t.setPk(pk); //set联合主键
		t.setAge(0);
		t.setBirthday(new Date());
		t.setGrade(Grade.A);
		
        session.save(t);

        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();
      

执行后主键就是:primary key (id, name)

DEBUG SchemaUpdate:226 - create table t_Teacher (id number(10,0) not null, name varchar2(255 char) not null, age number(10,0) not null, birthday date, grade varchar2(255 char), primary key (id, name))