JPA注解实现联合主键

Posted 倚天剑雨

tags:

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

当表中一个主键不能唯一标识一条记录的时候,就需要使用联合主键了,下面是使用JPA注解实现联合主键的代码

1 首先需要建立一个复合主键类,用来存放需要生产联合主键的属性,该类需要实现序列化。

package com.ericsson.adp.entity.cons;

import java.io.Serializable;

public class ConsumerGroupMapPK implements Serializable{

   private String msisdn;//电话号码

   private Long tagGroupId;//(10)标签组id

   public String getMsisdn() {

      return msisdn;

    }

   public void setMsisdn(String msisdn) {

      this.msisdn = msisdn;

    }

   public Long getTagGroupId() {

      return tagGroupId;

    }

   public void setTagGroupId(Long tagGroupId) {

      this.tagGroupId = tagGroupId;

    }

}

 

然后再写一个类,该类对应数据库中的表,在该类中需要使用@IdClass(ConsumerGroupMapPK.class)引入上面写的复合主键类

同时在需要做成联合主键的属性上面加上@Id标明该属性是主键就好了

package com.ericsson.adp.entity.cons;

 

import javax.persistence.EmbeddedId;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.IdClass;

import javax.persistence.Table;

 

import org.hibernate.annotations.Cache;

import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity

@IdClass(ConsumerGroupMapPK.class)

@Table(name="T_CONS_CONSUMER_GROUP_MAP")

@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)

public class ConsumerGroupMap{

    @Id

   private String msisdn;//电话号码

    @Id

   private Long tagGroupId;//(10)标签组id

   

   public ConsumerGroupMap() {

      super();

       // TODO Auto-generated constructor stub

    }

   public ConsumerGroupMap(String msisdn, Long tagGroupId) {

      super();

      this.msisdn = msisdn;

      this.tagGroupId = tagGroupId;

    }

   

   public String getMsisdn() {

      return msisdn;

    }

   public void setMsisdn(String msisdn) {

      this.msisdn = msisdn;

    }

   public Long getTagGroupId() {

      return tagGroupId;

    }

   public void setTagGroupId(Long tagGroupId) {

      this.tagGroupId = tagGroupId;

    }

   

}

以上是关于JPA注解实现联合主键的主要内容,如果未能解决你的问题,请参考以下文章

hibernate ——联合主键

hibernate 联合主键一对多用注解怎么设置?

hibernate联合主键 注解方式

Hibernate中用到联合主键的使用方法,为何要序列化,为何要重写hashcode 和 equals 方法

Hibernate—— 联合主键 一对一关联关系映射(xml和注解) 和 领域驱动设计

Hibernate注解映射联合主键的三种主要方式