码迷,mamicode.com
首页 > Web开发 > 详细

hibernate配置联合主键

时间:2015-06-26 12:26:57      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

配置联合主键有多种方式,这里仅记录我使用的一种。

直接上代码

使用@IdClass,红色标注。

package com.szy.operation.stat.model.agent.school;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;

import com.szy.common.model.IEntity;


@Entity
@Table(name = "test_test_test")
@IdClass(AgentDaySchoolPrimaryKey.class)
public class StatAgentDaySchoolAggregate implements IEntity<Long>{

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "stat_date")
    private String statDate;
    
    @Id
    @Column(name = "agent_id")
    private Integer agentId;
    
    @Column(name = "agent_name")
    private String agentName;public String getStatDate() {
        return statDate;
    }

    public void setStatDate(String statDate) {
        this.statDate = statDate;
    }

    public Integer getAgentId() {
        return agentId;
    }

    public void setAgentId(Integer agentId) {
        this.agentId = agentId;
    }

    public String getAgentName() {
        return agentName;
    }

    public void setAgentName(String agentName) {
        this.agentName = agentName;
    }

    @Override
    public Long getId() {
        return null;
    }
    
    
}

同时主键类如下,重写equal()和hashCode().

package com.szy.operation.stat.model.agent.school;

import java.io.Serializable;

import javax.persistence.Column;


public class AgentDaySchoolPrimaryKey implements Serializable{

    private static final long serialVersionUID = 1L;
    
    @Column(name = "stat_date")
    private String statDate;
    
    @Column(name = "agent_id")
    private Integer agentId;

    public String getStatDate() {
        return statDate;
    }

    public void setStatDate(String statDate) {
        this.statDate = statDate;
    }

    public Integer getAgentId() {
        return agentId;
    }

    public void setAgentId(Integer agentId) {
        this.agentId = agentId;
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof AgentDaySchoolPrimaryKey){  
            AgentDaySchoolPrimaryKey key = (AgentDaySchoolPrimaryKey)obj ;  
            if(this.statDate.equals(key.getStatDate()) && this.agentId.equals(key.getAgentId())){  
                return true ;  
            }  
        }  
        return false ;
    }

    @Override
    public int hashCode() {
        int result = 17;  
          result = 7 * result + (getAgentId() == null ? 0 : this.getAgentId().hashCode());  
          result = 7 * result + (getStatDate() == null ? 0 : this.getStatDate().hashCode());  
        return result;
    }
}

这样就完成了。

记录遇到的问题以供参考。

hibernate配置联合主键

标签:

原文地址:http://www.cnblogs.com/wkhc/p/4601929.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!