博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hibernate 复合主键映射
阅读量:5049 次
发布时间:2019-06-12

本文共 14510 字,大约阅读时间需要 48 分钟。

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

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

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

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

/*实体类.复合主键必须实现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;

true

 

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

/*主键类*/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 

true
以上仅仅只能当作参考,具体的还要根据实际情况修改以下送上我工作中的代码
/* @(#) * *  * * 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;    }}
主键类
true
xml

 

 

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

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

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

转载于:https://www.cnblogs.com/wangyongheng/p/5585772.html

你可能感兴趣的文章
对Feature的操作插入添加删除
查看>>
javascript String
查看>>
ecshop 系统信息在哪个页面
查看>>
【转】码云source tree 提交超过100m 为什么大文件推不上去
查看>>
Oracle数据库的增、删、改、查
查看>>
MySql执行分析
查看>>
git使用中的问题
查看>>
yaml文件 .yml
查看>>
linux字符集修改
查看>>
phpcms 添加自定义表单 留言
查看>>
mysql 优化
查看>>
读书笔记 ~ Nmap渗透测试指南
查看>>
WCF 配置文件
查看>>
动态调用WCF服务
查看>>
oracle导出/导入 expdp/impdp
查看>>
类指针
查看>>
css修改滚动条样式
查看>>
2018.11.15 Nginx服务器的使用
查看>>
Kinect人机交互开发实践
查看>>
百度编辑器UEditor ASP.NET示例Demo 分类: ASP.NET...
查看>>