您的位置:首页 > 其它

Hibernate注解映射联合主键的三种主要方式(转载)

2017-04-20 20:14 99 查看
Hibernate注解映射联合主键的三种主要方式(转载)

转自:http://blog.csdn.net/robinpipi/article/details/7655388

联合主键用hibernate注解映射方式主要有三种:
第一、将联合主键的字段单独放在一个类中,该类需要实现Java.io.Serializable接口并重写equals和hascode,再将该类注解为@Embeddable,最后在主类中(该类不包含联合主键类中的字段)保存该联合主键类的一个引用,并生成set和get方法,并将该引用注解为@Id

第二、将联合主键的字段单独放在一个类中,该类需要实现java.io.Serializable接口并重写equals和hascode,最后在主类中(该类不包含联合主键类中的字段)保存该联合主键类的一个引用,并生成set和get方法,并将该引用注解为@EmbeddedId

第三、将联合主键的字段单独放在一个类中,该类需要实现java.io.Serializable接口并要重写equals和hashcode.最后在主类中(该类包含联合主键类中的字段)将联合主键字段都注解为@Id,并在该类上方将上这样的注解:@IdClass(联合主键类.class)

转自:http://blog.sina.com.cn/s/blog_8297f0d00101012c.html

使用方式:

1、model类:

@Entity

@Table(name="JLEE01")

public class Jlee01 implements Serializable{

private static final long serialVersionUID = 3524215936351012384L;

private String address ;

private int age ;

private String email ;

private String phone ;

@Id

private JleeKey01 jleeKey ;

主键类:JleeKey01.java

@Embeddable

public class JleeKey01 implements Serializable{

private static final long serialVersionUID = -3304319243957837925L;

private long id ;

private String name ;

/**

* @return the id

*/

public long getId() {

return id;

}

/**

* @param id the id to set

*/

public void setId(long id) {

this.id = id;

}

/**

* @return the name

*/

public String getName() {

return name;

}

/**

* @param name the name to set

*/

public void setName(String name) {

this.name = name;

}

@Override

public boolean equals(Object o) {

if(o instanceof JleeKey01){

JleeKey01 key = (JleeKey01)o ;

if(this.id == key.getId() && this.name.equals(key.getName())){

return true ;

}

}

return false ;

}

@Override

public int hashCode() {

return this.name.hashCode();

}

}

2、model类:

@Entity

@Table(name="JLEE02")

public class Jlee02 {

private String address ;

private int age ;

private String email ;

private String phone ;

@EmbeddedId

private JleeKey02 jleeKey ;

主键类:JleeKey02.java

普通java类即可。

3、model类:

@Entity

@Table(name="JLEE03")

@IdClass(JleeKey03.class)

public class Jlee03 {

@Id

private long id ;

@Id

private String name ;

主键类:JleeKey03.java

普通java类。

主键类都需要实现重写equals和hascode方法,至于是否需要实现implements Serializable接口,测试了下,貌似可以不需要。

转自:http://laodaobazi.iteye.com/blog/903236

前端如果用easyui的 话,

需要这样写:

{field:'joinKey.statistic_id',title:'编号',width:80,sortable:true,align:'center',
formatter:function(value,rowData,rowIndex){

return rowData.joinKey.statistic_id;

}},

{field:'joinKey.month',title:'时间(单位月)',width:200,sortable:true,align:'center',
formatter:function(value,rowData,rowIndex){

return rowData.joinKey.month;

}}

joinKey为主键类,statistic_id、month为联合主键的字段。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: