hibernate 复合主键映射

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate 复合主键映射相关的知识,希望对你有一定的参考价值。

第一次写博客,只想把工作中遇到的问题记下来。

最近做了一个二次开发的改造,改完之后被告知数据表主键根据需求需要用复合主键,因为本人菜鸟一枚,复合主键从未用过,只能靠度娘

网上给出的复合主键映射大致就两种

第一种:将复合主键对应的属性与实体其他普通属性放在一起

/*实体类.复合主键必须实现Serialzable接口*/
public class User implements Serialzable
{
private static final long serialVersionUID=1L;//版本之间的兼容,数值自己定义

private String id;
private String name;
private int age;

public User()
{

}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id=id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age=age;
}
public int hashCode()  
    {  
        final int prime = 31;  
        int result = 1;  
        result = prime * result + ((id == null) ? 0 : id.hashCode());  
        result = prime * result + ((name == null) ? 0 : name.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;  
        People other = (People) obj;  
        if (id == null)  
        {  
            if (other.id != null)  
                return false;  
        }  
       else if (!id.equals(other.id))  
            return false;  
        if (name == null)  
        {  
            if (other.name != null)  
                return false;  
        }  
        else if (!name.equals(other.name))  
            return false;  
       return true;  
    }


 }

注意:复合主键实体类需要重写hashCode()和equals()方法

User..hbm.xml;

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com">
    <class
        name="User"
        table="USER"
    >
        <meta attribute="sync-DAO">true</meta>
        <composite-id >
            <key-property name="id" column="id"   type="string"></key-property> 
            <key-property name="name" column="name" type="string"></key-property> 
        </composite-id> 


        <property name="age" column="Age" type="int" />
        
    </class>    
</hibernate-mapping>

 

第二种方式:将主键属性提取到一个主键类中,实体类只需要包涵主键类的一个引用

/*主键类*/
public class UserPK implements Serializable
{
private String name;
private String id;
public String getId()
{
return id;
}
public void setId()
{
this.id=id;
}
public String getName()
{
return name;
}
public void setName()
{
this.name=name;
}
public boolean equals (Object obj) {
        if (null == obj) return false;
        if (!(obj instanceof com.huateng.po.UserPK )) return false;
        else {
            com.huateng.po.UserPK mObj = (com.huateng.po.UserPK ) obj;
            if (null != this.getId() && null != mObj.getId()) {
                if (!this.getId().equals(mObj.getId())) {
                    return false;
                }
            }
            else {
                return false;
            }
            if (null != this.getName() && null != mObj.getName()) {
                if (!this.getName().equals(mObj.getName())) {
                    return false;
                }
            }
            else {
                return false;
            }
            return true;
        }
    }

    public int hashCode () {
        if (Integer.MIN_VALUE == this.hashCode) {
            StringBuilder sb = new StringBuilder();
            if (null != this.getId()) {
                sb.append(this.getId().hashCode());
                sb.append(":");
            }
            else {
                return super.hashCode();
            }
            if (null != this.getName()) {
                sb.append(this.getName().hashCode());
                sb.append(":");
            }
            else {
                return super.hashCode();
            }
            this.hashCode = sb.toString().hashCode();
        }
        return this.hashCode;
    }
}

/*实体类*/
public class User implements Serializable
{
private static final long serialVersionUID = 1L;
private UserPK id;
private int age;
public UserPK getId()
{
return id;
}
public UserPK setId()
{
this.id=id;
}
public int getAge() { return age; } public void setAge() { this.age=age; } }

 

User.hbm.xml 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com">
    <class
        name="User"
        table="USER"
    >
        <meta attribute="sync-DAO">true</meta>
        <composite-id name="id" class="UserPK">
            <key-property name="id" column="id"   type="string"></key-property> 
            <key-property name="name" column="name" type="string"></key-property> 
        </composite-id> 


        <property name="age" column="Age" type="int" />       
    </class>    
</hibernate-mapping>

以上仅仅只能当作参考,具体的还要根据实际情况修改以下送上我工作中的代码
技术分享
/* @(#)
 *
 * 
 *
 * Modify Information:
 * =============================================================================
 *   Author         Date           Description
 *   ------------ ---------- ---------------------------------------------------
 *   徐志诚                         2016-5-18         first release
 *
 *
 * Copyright Notice:
 * =============================================================================
 *       Copyright 2016 Huateng Software, Inc. All rights reserved.
 *
 *       This software is the confidential and proprietary information of
 *       Shanghai HUATENG Software Co., Ltd. ("Confidential Information").
 *       You shall not disclose such Confidential Information and shall use it
 *       only in accordance with the terms of the license agreement you entered
 *       into with Huateng.
 *
 * Warning:
 * =============================================================================
 *
 */
package com.huateng.po;

import java.io.Serializable;

/**
 * Title:
 * 
 * Description:
 * 
 * Copyright: Copyright (c) 2016-5-18
 * 
 * Company: Shanghai Huateng Software Systems Co., Ltd.
 * 
 *
 * 
 * @version 1.0
 */
//@SuppressWarnings("serial")
public class Tblvatrule implements Serializable{
    
    private static final long serialVersionUID = 1L;
    
    public static String REF ="Tblvatrule";
    public static String PROP_ORACLE_GL="oraclegl";
    public static String PROP_GL_DESC="gldesc";
    public static String PROP_DC_FLAG="dcflag";
    public static String PROP_TAX_RATE="taxrate";
    public static String PROP_TAN_NUM="tannum";
    public static String PROP_EFF_DATE="effdate";
    public static String PROP_status="status";
    public static String PROP_MODIFY_TLR="modifytlr";
    public static String PROP_MODIFY_TIME="modifytime";
    public static String PROP_AUTH_TLR="authtlr";
    public static String PROP_AUTH_TIME="authtime";
    public static String PROP_TAX_GL="taxgl";
    public static String PROP_TAX_CODE="taxcode";
    public static String PROP_ID="id";
    public Tblvatrule(){
        
    }
    public Tblvatrule(com.huateng.po.TblvatruleTmpPK id,java.lang.String oraclegl,java.lang.String dcflag){
        this.setId(id);
        this.setOraclegl(oraclegl);
        this.setDcflag(dcflag);
        initialize();
    }
    
    protected void initialize () {}        
    private com.huateng.po.TblvatruleTmpPK id;

/**
     * @return the id
     */
    public com.huateng.po.TblvatruleTmpPK getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(com.huateng.po.TblvatruleTmpPK id) {
        this.id = id;
    }
private java.lang.String oraclegl;       //账号
private java.lang.String gldesc;         //账户描述
private java.lang.String dcflag;         //借贷标识
private java.lang.String taxrate;        //税率
private java.lang.String txnnum;         //交易码
private java.lang.String effdate;        //生效日期
private java.lang.String status;         //状态
private java.lang.String modifytlr;      //录入操作员
private java.lang.String modifytime;     //录入时间
private java.lang.String authtlr;        //审核操作员
private java.lang.String authtime;       //审核时间
private java.lang.String taxgl;          //增值税账号
private java.lang.String taxcode;        //增值税代码
private int hashCode = Integer.MIN_VALUE;
/**
 * @return the taxgl
 */
public java.lang.String getTaxgl() {
    return taxgl;
}
/**
 * @param taxgl the taxgl to set
 */
public void setTaxgl(java.lang.String taxgl) {
    this.taxgl = taxgl;
}
/**
 * @return the taxcode
 */
public java.lang.String getTaxcode() {
    return taxcode;
}
/**
 * @param taxcode the taxcode to set
 */
public void setTaxcode(java.lang.String taxcode) {
    this.taxcode = taxcode;
}
/**
 * @return the oraclegl
 */
public java.lang.String getOraclegl() {
    return oraclegl;
}
/**
 * @param oraclegl the oraclegl to set
 */
public void setOraclegl(java.lang.String oraclegl) {
    this.oraclegl = oraclegl;
}
/**
 * @return the gldesc
 */
public java.lang.String getGldesc() {
    return gldesc;
}
/**
 * @param gldesc the gldesc to set
 */
public void setGldesc(java.lang.String gldesc) {
    this.gldesc = gldesc;
}
/**
 * @return the dcflag
 */
public java.lang.String getDcflag() {
    return dcflag;
}
/**
 * @param dcflag the dcflag to set
 */
public void setDcflag(java.lang.String dcflag) {
    this.dcflag = dcflag;
}
/**
 * @return the taxrate
 */
public java.lang.String getTaxrate() {
    return taxrate;
}
/**
 * @param taxrate the taxrate to set
 */
public void setTaxrate(java.lang.String taxrate) {
    this.taxrate = taxrate;
}
/**
 * @return the txnnum
 */
public java.lang.String getTxnnum() {
    return txnnum;
}
/**
 * @param txnnum the txnnum to set
 */
public void setTxnnum(java.lang.String txnnum) {
    this.txnnum = txnnum;
}
/**
 * @return the effdate
 */
public java.lang.String getEffdate() {
    return effdate;
}
/**
 * @param effdate the effdate to set
 */
public void setEffdate(java.lang.String effdate) {
    this.effdate = effdate;
}
/**
 * @return the status
 */
public java.lang.String getStatus() {
    return status;
}
/**
 * @param status the status to set
 */
public void setStatus(java.lang.String status) {
    this.status = status;
}
/**
 * @return the modifytlr
 */
public java.lang.String getModifytlr() {
    return modifytlr;
}
/**
 * @param modifytlr the modifytlr to set
 */
public void setModifytlr(java.lang.String modifytlr) {
    this.modifytlr = modifytlr;
}
/**
 * @return the modifytimel
 */
public java.lang.String getModifytime() {
    return modifytime;
}
/**
 * @param modifytimel the modifytimel to set
 */
public void setModifytime(java.lang.String modifytime) {
    this.modifytime = modifytime;
}
/**
 * @return the authtlr
 */
public java.lang.String getAuthtlr() {
    return authtlr;
}
/**
 * @param authtlr the authtlr to set
 */
public void setAuthtlr(java.lang.String authtlr) {
    this.authtlr = authtlr;
}
/**
 * @return the authtime
 */
public java.lang.String getAuthtime() {
    return authtime;
}
/**
 * @param authtime the authtime to set
 */
public void setAuthtime(java.lang.String authtime) {
    this.authtime = authtime;
}
public boolean equals (Object obj) {
    if (null == obj) return false;
    if (!(obj instanceof com.huateng.po.Tblvatrule)) return false;
    else {
        com.huateng.po.Tblvatrule tvrt = (com.huateng.po.Tblvatrule) obj;
        if (null == this.getId() || null == tvrt.getId()) return false;
        else return (this.getId().equals(tvrt.getId()));
    }
}

public int hashCode () {
    if (Integer.MIN_VALUE == this.hashCode) {
        if (null == this.getId()) return super.hashCode();
        else {
            java.lang.String hashStr = this.getClass().getName() + ":" + this.getId().hashCode();
            this.hashCode = hashStr.hashCode();
        }
    }
    return this.hashCode;
}

public java.lang.String toString () {
    return super.toString();
}
}
实体类

技术分享
/* @(#)
 *
 * Project:OCBCServer
 *
 * Modify Information:
 * =============================================================================
 *   Author         Date           Description
 *   ------------ ---------- ---------------------------------------------------
 *   徐志诚                         2016-6-12         first release
 *
 *
 * Copyright Notice:
 * =============================================================================
 *       Copyright 2016 Huateng Software, Inc. All rights reserved.
 *
 *       This software is the confidential and proprietary information of
 *       Shanghai HUATENG Software Co., Ltd. ("Confidential Information").
 *       You shall not disclose such Confidential Information and shall use it
 *       only in accordance with the terms of the license agreement you entered
 *       into with Huateng.
 *
 * Warning:
 * =============================================================================
 *
 */
package com.huateng.po;

import java.io.Serializable;

/**
 * Title:
 * 
 * Description:
 * 
 * Copyright: Copyright (c) 2016-6-12
 * 
 * Company: Shanghai Huateng Software Systems Co., Ltd.
 * 
 * @author 徐志诚
 * 
 * @version 1.0
 */
@SuppressWarnings("serial")
public class TblvatrulePK implements Serializable{
    protected int hashCode = Integer.MIN_VALUE;
    private java.lang.String oraclegl;     //账号
    private java.lang.String dcflag;       //借贷标识
    public TblvatrulePK(){
        
    }
    public TblvatrulePK(java.lang.String oraclegl,java.lang.String dcflag){
        this.setOraclegl(oraclegl);
        this.setDcflag(dcflag);
    }
    /**
     * @return the oraclegl
     */
    public java.lang.String getOraclegl() {
        return oraclegl;
    }
    /**
     * @param oraclegl the oraclegl to set
     */
    public void setOraclegl(java.lang.String oraclegl) {
        this.oraclegl = oraclegl;
    }
    /**
     * @return the dcflag
     */
    public java.lang.String getDcflag() {
        return dcflag;
    }
    /**
     * @param dcflag the dcflag to set
     */
    public void setDcflag(java.lang.String dcflag) {
        this.dcflag = dcflag;
    }
    public boolean equals (Object obj) {
        if (null == obj) return false;
        if (!(obj instanceof com.huateng.po.TblvatrulePK)) return false;
        else {
            com.huateng.po.TblvatrulePK mObj = (com.huateng.po.TblvatrulePK) obj;
            if (null != this.getOraclegl() && null != mObj.getOraclegl()) {
                if (!this.getOraclegl().equals(mObj.getOraclegl())) {
                    return false;
                }
            }
            else {
                return false;
            }
            if (null != this.getDcflag() && null != mObj.getDcflag()) {
                if (!this.getDcflag().equals(mObj.getDcflag())) {
                    return false;
                }
            }
            else {
                return false;
            }
            return true;
        }
    }

    public int hashCode () {
        if (Integer.MIN_VALUE == this.hashCode) {
            StringBuilder sb = new StringBuilder();
            if (null != this.getOraclegl()) {
                sb.append(this.getOraclegl().hashCode());
                sb.append(":");
            }
            else {
                return super.hashCode();
            }
            if (null != this.getDcflag()) {
                sb.append(this.getDcflag().hashCode());
                sb.append(":");
            }
            else {
                return super.hashCode();
            }
            this.hashCode = sb.toString().hashCode();
        }
        return this.hashCode;
    }
}
主键类
技术分享
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com.huateng.po">
    <class
        name="Tblvatrule"
        table="TBL_VAT_RULE"
    >
        <meta attribute="sync-DAO">true</meta>
        <composite-id name="id" class="TblvatruleTmpPK">
            <key-property name="oraclegl" column="ORACLE_GL" type="string"></key-property> 
            <key-property name="dcflag" column="DC_FLAG" type="string"></key-property> 
        </composite-id> 


        <property name="gldesc" column="GL_DESC" type="string" />
        <property name="taxgl"  column="TAX_GL"  type="string" />
        <property name="taxcode" column="TAX_CODE" type="string" />
        <property name="taxrate" column="TAX_RATE" type="string" />
        <property name="txnnum" column="TXN_NUM" type="string" />
        <property name="effdate" column="EFF_DATE" type="string" />
        <property name="status" column="STATUS" type="string" />
        <property name="modifytlr" column="MODIFY_TLR" type="string" />
        <property name="modifytime" column="MODIFY_TIME" type="string" />
        <property name="authtlr" column="AUTH_TLR" type="string" />
        <property name="authtime" column="AUTH_TIME"  type="string" />
        
    </class>    
</hibernate-mapping>
xml

 




 总结:复合主键是一个指一个主键是有一个以上字段组成,

当一个主键字段无法确保其唯一性时,需要其他字段一起形成唯一性,

优点是唯一性得到保证,缺点是影响查询和修改的效率。

以上是关于hibernate 复合主键映射的主要内容,如果未能解决你的问题,请参考以下文章

Hibernate:复合主键 - 外键:如何在两个表之间映射各个字段

Hibernate复合主键映射

Hibernate复合主键映射

hibernate复合主键

主键映射

具有复合键的一对多注释映射