Hibernate复合主键映射

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

目 录:

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

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

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

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

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

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

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.

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> 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

Hibernate中使用复合主键时需要注意一些规则:

1. 使用复合主键的实体类必须实现Serializable接口。必须实现Serializable接口的原因很简单,我们查找数据的时候是根据主键查找的。打开Hibernate的帮助文档我们可以找到get与load方法的声明形式如下:

Object load(Class theClass,Serializable id)

Object get(Class theClass,Serializable id)

当我们查找复合主键类的对象时,需要传递主键值给get()或load()方法的id参数,而id参数只能接收一个实现了Serializable接口的对象。而复合主键类的主键不是一个属性可以表示的,所以只能先new出复合主键类的实例(例如:new People()),然后使用主键属性的set方法将主键值赋值给主键属性,然后将整个对象传递给get()或load()方法的id参数,实现主键值的传递,所以复合主键的实体类必须实现Serializable接口。

2. 使用复合主键的实体类必须重写equals和hashCode方法。必须重写equals和hashCode方法也很好理解。这两个方法使用于判断两个对象 (两条记录)是否相等的。为什么要判断两个对象是否相等呢?因为数据库中的任意两条记录中的主键值是不能相同的,所以我们在程序中只要确保了两个对象的主键值不同就可以防止主键约束违例的错误出现。也许这里你会奇怪为什么不使用复合主键的实体类不重写这两个方法也没有主键违例的情况出现,这是因为使用单一主键方式,主键值是Hibernate来维护的,它会确保主键不会重复,而复合主键方式,主键值是编程人员自己维护的,所以必须重写equals和hashCode方法用于判断两个对象的主键是否相同。

3. 重写的equals和hashCode方法,只与主键属性有关,普通属性不要影响这两个方法进行判断。这个原因很简单,主键才能决定一条记录,其他属性不能决定一条记录。

保存测试:

public class Client  
{  
    public static void main(String[] args)  
    {  
        Session session = HibernateUtil.getSessionFactory().openSession();  
        Transaction tx = null;  
          
        try 
        {  
            tx = session.beginTransaction();  
              
            People people = new People();  
            /*主键值由我们自己维护*/ 
            people.setId("123456");  
            people.setName("zhangsan");  
            people.setAge(40);  
              
            session.save(people);  
              
            tx.commit();  
        }  
        catch (Exception e)  
        {  
            if(tx != null)  
            {  
                tx.rollback();  
            }  
              
            e.printStackTrace();  
        }  
        finally 
        {  
            session.close();  
        }  
    }  

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.

看看数据库:

数据被正确的插入到数据库中了。

读取数据测试:

public class Client  
{  
    public static void main(String[] args)  
    {  
        Session session = HibernateUtil.getSessionFactory().openSession();  
        Transaction tx = null;  
          
        try 
        {  
            tx = session.beginTransaction();  
              
            /*查询复合主键对象,需要先构建主键*/ 
            People peoplePrimaryKey = new People();  
            peoplePrimaryKey.setId("123456");  
            peoplePrimaryKey.setName("zhangsan");  
              
            /*然后将构建的主键值传入get方法中获取对应的People对象*/ 
            People people = (People)session.get(People.class, peoplePrimaryKey);  
              
            System.out.println("people age is:"+people.getAge());  
              
            tx.commit();  
        }  
        catch (Exception e)  
        {  
            if(tx != null)  
            {  
                tx.rollback();  
            }  
              
            e.printStackTrace();  
        }  
        finally 
        {  
            session.close();  
        }  
    }  

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.

控制台输出:

people age is:40
  • 1.

可以看到数据成功的取出了。

 

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

主键类:

/*必须实现Serializable接口*/ 
public class PeoplePrimaryKey implements Serializable  
{  
    private static final long serialVersionUID = -1190986010439330142L;  
      
    /*复合主键值*/ 
    private String id;  
    private String name;  
      
    public PeoplePrimaryKey()  
    {  
          
    }  
      
    /*复合主键值的get和set方法*/ 
    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;  
    }  
 
    @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;  
        PeoplePrimaryKey other = (PeoplePrimaryKey) 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;  
    }  

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.

实体类:

public class People  
{  
    /*持有主键类的一个引用,使用该引用作为这个类的OID*/ 
    private PeoplePrimaryKey peoplePrimaryKey;  
    private int age;  
      
    public People()  
    {  
          
    }  
      
    public PeoplePrimaryKey getPeoplePrimaryKey()  
    {  
        return peoplePrimaryKey;  
    }  
 
    public void setPeoplePrimaryKey(PeoplePrimaryKey peoplePrimaryKey)  
    {  
        this.peoplePrimaryKey = peoplePrimaryKey;  
    }  
 
    public int getAge()  
    {  
        return age;  
    }  
 
    public void setAge(int age)  
    {  
        this.age = age;  
    }  

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.

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标签 --> 
        <!--  
        name - 指定了复合主键对应哪一个属性  
        class - 指定了复合主键属性的类型  
        --> 
        <composite-id name="peoplePrimaryKey" class="com.suxiaolei.hibernate.pojos.PeoplePrimaryKey"> 
            <!-- 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> 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

场景测试与方式一大同小异这里不再举例了。主键类为什么实现Serializable接口和为什么重写equals和hashCode方法上面已经解释的很清楚了。

原文链接:http://www.cnblogs.com/otomedaybreak/archive/2012/01/25/2329390.html

【编辑推荐】

  1. Hibernate继承映射
  2. Hibernate事务与并发问题处理
  3. 让Hibernate显示SQL语句的绑定参数值
  4. hibernate中MySQL自增字段的映射描述
  5. Hibernate+MySQL 中文问题的解决
责任编辑:林师授 来源: 音①晓的博客
相关推荐

2009-06-01 12:11:31

hibernatejpa复合主键

2012-03-21 11:43:41

JavaHibernate

2009-09-23 09:16:25

Hibernate复合

2012-02-02 16:13:29

HibernateJava

2009-09-23 14:23:51

Hibernate主键

2009-09-24 10:50:31

Hibernate主键

2009-09-23 17:34:18

Hibernate映射

2009-09-22 15:10:22

Hibernate映射

2012-02-03 11:17:33

HibernateJava

2009-09-25 10:00:47

Hibernate映射

2009-06-29 08:56:49

Hibernate主键生成主键

2009-09-25 13:33:43

Hibernate主键

2009-09-22 09:31:15

Hibernate主键

2009-09-24 13:49:31

Hibernate自增

2011-07-25 18:11:47

SQL Server数复合主键

2009-06-02 14:46:26

Hibernate关系映射教程

2009-06-18 14:22:06

Hibernate多对Hibernate

2009-09-25 12:59:52

Hibernate映射

2009-09-28 14:54:33

Hibernate映射

2009-09-29 15:58:22

Hibernate映射
点赞
收藏

51CTO技术栈公众号