标签:
一.前言
在我们的日常开发中,有时候会用到数据库进行设计的时候,采用了复合主键来来保证唯一性,下面介绍一下采用hibernate的@EmbeddedId嵌入式主键。
二.说明
设计一个学生类,包含了三个字段
create tbale student( stu_no char(11) not null, stu_name varchar2(30) not null, stu_class varchar2(20) )
stu_no : 学号、 stu_name : 姓名 、 stu_class : 班级
把stu_no、stu_name作为复合主键
三.studetn 学生类复合主键
package com.shine.account.composite.holdportfolio.po; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; /** * 类说明:studetn 学生类复合主键. * * NOTE : 符合条件: * 1.必须实现Serializable * 2.必须有默认的 public无参数的构造方法、必须覆盖 equals和 hashCode 方法,这些要求与使用复合主键的要求相同 * 3.将嵌入式主键类使用 @Embeddable 标注,表示这个是一个嵌入式类。 * */ @Embeddable @SuppressWarnings("serial") public class StudentId implements Serializable{ /**学号*/ private String stuNo; /**姓名*/ private String stuName; public StudentId() { super(); } @Column(name = "STU_NO", nullable = false, precision = 11) public String getStuNo() { return stuNo; } public void setStuNo(String stuNo) { this.stuNo = stuNo; } @Column(name = "STU_NAME", nullable = false) public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } @Override public boolean equals(Object other) { if(this == other) return true; if(other == null) return false; if(!(other instanceof StudentId)) return false; StudentId otherStudentId = (StudentId) other; return this.getStuNo() == otherStudentId.stuNo && this.getStuName() == otherStudentId.stuNo; } @Override public int hashCode() { return this.stuNo.hashCode() + this.stuName.hashCode(); } }
四.po对象(采用java的注解的方式,来注解po)
package com.shine.account.composite.holdportfolio.po; import java.io.Serializable; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; /** * 类说明:学习实体类. */ @Entity @Table(name = "STUDENT") @SuppressWarnings("serial") public class Student implements Serializable{ /**复合主键类*/ private StudentId studentId; /**学生对应班级*/ private String stuClass; /** * @EmbeddedId 复合主键id * @AttributeOverrides 属性映射 */ @EmbeddedId @AttributeOverrides({ @AttributeOverride(name = "stuNo", column = @Column(name = "STU_NO", nullable = false, precision = 11)), @AttributeOverride(name = "stuName", column = @Column(name = "STU_NAME", nullable = false)) }) public StudentId getStudentId() { return studentId; } public void setStudentId(StudentId studentId) { this.studentId = studentId; } @Column(name = "STU_CLASS", nullable = false) public String getStuClass() { return stuClass; } public void setStuClass(String stuClass) { this.stuClass = stuClass; } }
标签:
原文地址:http://www.cnblogs.com/hongwz/p/5598962.html