Hibernate配置组合主键(笔记)

5 篇文章 0 订阅
1 篇文章 0 订阅

当表中一个主键不能唯一标识一条记录的时候,就需要使用联合主键了,下面是使用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;

    }

   

}

我的情况是Hibernate实现对象多对多时,要在中间表增加字段。我就创建了中间表的类。但Hibernate自动建表时,将中间表里的两个多对多关联字段自动创建成了组合主键,想改为单主键注解配置另外的id字段为主键也没有效果。保存数据的时候id字段就会存为空,hibernate查询的时候,因为id字段为空,数据自然也就查询不到。找半天,借鉴了这篇例子,在Entity里配置了组合主键,终于成功了!!!

做一个记录,避免同一个坑跳两次。


转自:http://blog.sina.com.cn/s/blog_4b5bc01101010uwt.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值