hibernate复合主键的使用 2008-02-14 Java
当需要使用多个字段作为主键时,就需要使用复合主键。复合主键要求编写一个复合主键类(Composite Primary Key Class)。
复合主键类需要满足以下要求:
·复合主键类必须是public和无参数的构造函数
·复合主键类的每个属性变量必须有getter/setter,否则必须是public或者protected
·复合主键类必须实现java.io.serializable
·复合主键类必须实现equals()和hashcode()方法
·复合主键类中的主键属性变量的名字必须和对应的Entity中主键属性变量的名字相同
·一旦主键值设定后,不能修改主键属性变量的值
1. 复合主键类的代码:
package com.mycompany.hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
@Embeddable
public class ProductPK implements Serializable {
private static final long serialVersionUID = -1;
private String code;
private String name;
public ProductPK() {
}
public ProductPK(final String code, final String name) {
this.code = code;
this.name = name;
}
/**
* @return code
*/
@Column(name = “CODE”)
public String getCode() {
return code;
}
/**
* @return name
*/
@Column(name = “NAME”)
public String getName() {
return name;
}
/**
* @param code
*/
public void setCode(final String code) {
this.code = code;
}
/**
* @param name
*/
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(final Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
}
2. 使用该复合主键的实体类代码:
package com.mycompany.hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = “PRODUCT”)
public class Product implements Serializable {
private static final long serialVersionUID = -1;
private ProductPK primaryKey;
private String createdDate;
@Transient
public String getCode() {
return primaryKey.getCode();
}
@Transient
public String getName() {
return primaryKey.getName();
}
@EmbeddedId
public ProductPK getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(final ProductPK primaryKey) {
this.primaryKey = primaryKey;
}
@Column(name = “CREATED_DATE”)
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(final String createdDate) {
this.createdDate = createdDate;
}
}
3. 查询语句
DetachedCriteria criteria = DetachedCriteria.forClass(Product.class);
criteria.add(Restrictions.eq(”primaryKey.code”,”111″));
List results = getHibernateTemplate().findByCriteria(criteria);
标签: hibernate






