码迷,mamicode.com
首页 > 其他好文 > 详细

hinernate复合主键操作方法

时间:2015-03-02 12:57:14      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

目录:

1. 实现方式一:将复合主键对应的属性与实体其他普通属性放在一起

2. 实现方式二:将主键属性提取到一个主键类中,实体类只需包含主键类的一个引用

 

  在日常开发中会遇到这样一种情况,数据库中的某张表需要多个字段列才能唯一确定一行记录,这时表需要使用复合主键。面对这样的情况Hibernate为我们提供了两种方式来解决复合主键问题。

 

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

例如实体类People中"id"和"name"属性对应复合主键:

People.java:

/*实体类,使用复合主键必须实现Serializable接口*/
public class People implements Serializable
{
    private static final long serialVersionUID = -4888836126783955019L;
    
    private String id;
    private String name;
    private int age;
    
    public People()
    {
        
    }

    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;
    }

    @Override
    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;
    }
}

People.hbm.xml:

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

<hibernate-mapping>
    <class name="com.suxiaolei.hibernate.pojos.People" table="people">
        <!-- 复合主键使用composite-id标签 -->
        <composite-id>
            <!-- key-property标签表示哪一些属性对应复合主键 -->
            <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="integer"></property>
    </class>
</hibernate-mapping>

 

hinernate复合主键操作方法

标签:

原文地址:http://www.cnblogs.com/a-5895373/p/4308442.html

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