hibernate ——联合主键
Posted 沙中世界
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate ——联合主键相关的知识,希望对你有一定的参考价值。
接上一篇博客:http://www.cnblogs.com/tengpan-cn/p/5551323.html
主键类不需要写任何注解,表对象类使用@IdClass注解
在表对象类前面加@IdClass(value=主键类名.class)然后,表对象类中也不必包含主键类,直接分成各个属性即可。在多个属性前加@ID
添加主键类,注意必须实现Serializable接口
package com.pt.hibernate; import java.io.Serializable; public class UnionId implements Serializable{ public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } public int getId() { return id; } public void setId(int id) { this.id = id; } String schoolName; int id; }
package com.pt.hibernate; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; @Entity @IdClass(value=UnionId.class) public class Student { String schoolName; int id; String stuName; public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } @Id public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } @Id public int getId() { return id; } public void setId(int id) { this.id = id; } }
生成表的语句:
create table Student ( id integer not null, schoolName varchar(255) not null, stuName varchar(255), primary key (id, schoolName) ) ENGINE=InnoDB
以上是关于hibernate ——联合主键的主要内容,如果未能解决你的问题,请参考以下文章