Hibernate 注解方式设置联合主键

2018-08-18  本文已影响24人  春泥村雨

使用 Annotation 设置联合主键有三种方式:

1. 方法一

实体类:

@Entity 
@Table(name="Test01")  
public class Test01 implements Serializable{  
   private static final long serialVersionUID = 3524215936351012384L;  
   private String address ;  
   private int age ;  
   private String email ;  
   private String phone ;  
   @Id
   private TestKey01 testKey ;
}

主键类:

@Embeddable  
public class Testkey01  implements Serializable{
private static final long serialVersionUID = -3304319243957837925L;  
private long id ;  
private String name ;  
 
public long getId() {  
    return id;  
}  

public void setId(long id) {  
    this.id = id;  
}  

public String getName() {  
    return name;  
}  

public void setName(String name) {  
    this.name = name;  
}  

@Override  
public boolean equals(Object o) {  
    if(o instanceof Testkey0101){  
        Testkey01 key = (TestKey01)o ;  
        if(this.id == key.getId() && this.name.equals(key.getName())){  
            return true ;  
        }  
    }  
    return false ;  
}  
  
@Override  
public int hashCode() {  
    return this.name.hashCode();  
}
}

2. 方法二

@Entity
@Table(name="Test02")
public class Test02 {
    private String address;
    private int age;
    private String email;
    private String phone;
    
    @EmbeddedId
    private TestKey02 testKey ;
}

注:Testkey02为普通 Java 类即可。

3. 方法三

@Entity  
@Table(name="Test03")  
@IdClass(TestKey03.class)  
public class Test03 {  
    @Id
    private long id ;
    @Id  
    private String name ; 
}

Testkey03为普通Java类即可。

注:

参考链接:
https://www.cnblogs.com/lcngu/p/5854864.html
https://blog.csdn.net/zj420964597/article/details/77918357

上一篇 下一篇

猜你喜欢

热点阅读