hibernate联合主键的三种注解做法

时间:2021-09-18 13:50:30

1.给组件类加上@Embeddable注解,给实体类的主键属性加上@Id

如组件类如下写:

package vo;

import java.io.Serializable;

import javax.persistence.Embeddable;
@Embeddable
public class StudentPK implements Serializable{
 private int sid;
 private String sname;
 public int getSid() {
  return sid;
 }
 public void setSid(int sid) {
  this.sid = sid;
 }
 
 public String getSname() {
  return sname;
 }
 public void setSname(String sname) {
  this.sname = sname;
 }
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + sid;
  result = prime * result + ((sname == null) ? 0 : sname.hashCode());
  return result;
 }
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  StudentPK other = (StudentPK) obj;
  if (sid != other.sid)
   return false;
  if (sname == null) {
   if (other.sname != null)
    return false;
  } else if (!sname.equals(other.sname))
   return false;
  return true;
 }
 
 
}
而实体类如下写

package vo;

import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;


@Entity
public class Student {

 private StudentPK pk;
 private int age;
 
 
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 @Id
 public StudentPK getPk() {
  return pk;
 }
 public void setPk(StudentPK pk) {
  this.pk = pk;
 }
 
}

2.第二种注解写法:直接在实体类的主键属性上加@EmbededId即可

3.第三种写法:实体类还需要加上主键属性sid,sname,只不过在这两个属性上都加上@Id,在实体类上边加上@IdClass(value=StudentPK.class)