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

Hibernate,JPA注解@EmbeddedId

时间:2015-03-31 22:00:37      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:

定义组合主键的几种语法:

  • 将组件类注解为@Embeddable,并将组件的属性注解为@Id
  • 将组件的属性注解为@EmbeddedId
  • 将类注解为@IdClass,并将该实体中所有属于主键的属性都注解为@Id

组合主键使用一个可嵌入的类作为主键表示,因此你需要使用@Id 和@Embeddable两个注解. 还有一种方式是使用@EmbeddedId注解.注意所依赖的类必须实现 serializable以及实现equals()/hashCode()方法.

用例代码如下:

  • 数据库DDL语句
1 create table DOG
2 (
3   dog_name    VARCHAR2(255 CHAR) not null,
4   id_no       VARCHAR2(255 CHAR) not null,
5   mobile      VARCHAR2(255 CHAR),
6   create_time TIMESTAMP(6),
7   update_time TIMESTAMP(6)
8 )
  • hibernate.cfg.xml
 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <!DOCTYPE hibernate-configuration
 3  PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
 4  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <!-- 数据库驱动配置 -->
 8         <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
 9         <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
10         <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
11         <property name="connection.username">wxuatuser</property>
12         <property name="connection.password">xlh</property>
13         <property name="show_sql">true</property>
14         <!-- 自动执行DDL属性是update,不是true -->
15         <property name="hbm2ddl.auto">update</property>
16         <!-- hibernate实体类 -->
17         
18         <mapping class="a5_EmbeddedId.Dog"/>
19         
20     </session-factory>
21 </hibernate-configuration>
  • java类

实体类 - 基类 

package model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.hibernate.annotations.GenericGenerator;
/**
 * 实体类 - 基类
 */
@MappedSuperclass
public class BaseEntity implements Serializable {

    private static final long serialVersionUID = -6718838800112233445L;

    private String id;// ID
    private Date create_time;// 创建日期
    private Date update_time;// 修改日期
    @Id
    @Column(length = 32, nullable = true)
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid")
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @Column(updatable = false)
    public Date getCreate_time() {
        return create_time;
    }
    public void setCreate_time(Date create_time) {
        this.create_time = create_time;
    }
    public Date getUpdate_time() {
        return update_time;
    }
    public void setUpdate_time(Date update_time) {
        this.update_time = update_time;
    }
    @Override
    public int hashCode() {
        return id == null ? System.identityHashCode(this) : id.hashCode();
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass().getPackage() != obj.getClass().getPackage()) {
            return false;
        }
        final BaseEntity other = (BaseEntity) obj;
        if (id == null) {
            if (other.getId() != null) {
                return false;
            }
        } else if (!id.equals(other.getId())) {
            return false;
        }
        return true;
    }
}

实体类

 1 package a5_EmbeddedId;
 2 import javax.persistence.AttributeOverride;
 3 import javax.persistence.AttributeOverrides;
 4 import javax.persistence.Column;
 5 import javax.persistence.EmbeddedId;
 6 import javax.persistence.Entity;
 7 import javax.persistence.Id;
 8 import org.hibernate.annotations.DynamicInsert;
 9 import org.hibernate.annotations.DynamicUpdate;
10 
11 @Entity
12 @DynamicInsert
13 @DynamicUpdate
14 public class Dog{
15     /**
16      * 实体类
17      */
18     private static final long serialVersionUID = -2776330321385582872L;
19     @Id
20     private DogPK pk;
21     
22     private String mobile;
23 
24     @EmbeddedId
25     @AttributeOverrides( {
26         @AttributeOverride(name = "dog_name", column = @Column(name = "dog_name")),
27         @AttributeOverride(name = "id_no", column = @Column(name = "id_no")) })
28     public DogPK getPk() {
29         return pk;
30     }
31     public void setPk(DogPK pk) {
32         this.pk = pk;
33     }
34     public String getMobile() {
35         return mobile;
36     }
37     public void setMobile(String mobile) {
38         this.mobile = mobile;
39     }
40 }

组件类

 1 package a5_EmbeddedId;
 2 import java.io.Serializable;
 3 import javax.persistence.Embeddable;
 4 
 5 @Embeddable
 6 public class DogPK implements Serializable {
 7 
 8     /**
 9      * 嵌入式组建
10      * 作为嵌入式主键类,要满足以下几点要求。 
11      * 1.必须实现Serializable接口
12      * 必须有默认的public无参数的构造方法、必须覆盖equals 和hashCode方法,这些要求与使用复合主键的要求相同。 
13      * 但发现没这么干也能跑,目前还未深入了解为什么
14      */
15     private static final long serialVersionUID = -581520734909530534L;
16     
17     private String dog_name;
18     private String id_no;
19     
20     public String getDog_name() {
21         return dog_name;
22     }
23 
24     public void setDog_name(String dog_name) {
25         this.dog_name = dog_name;
26     }
27 
28     public String getId_no() {
29         return id_no;
30     }
31 
32     public void setId_no(String id_no) {
33         this.id_no = id_no;
34     }
35 }

Dao

package daoUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            Configuration cfg = new Configuration().configure();
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                    .applySettings(cfg.getProperties()).buildServiceRegistry();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return sessionFactory.openSession();
    }

    public static Object save(Object obj){
        Session session = HibernateUtil.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.save(obj);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } finally {
            session.close();
        }
        return obj;
    }
    
    public static void delete(Class<?> clazz,String id){
        Session session = HibernateUtil.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Object obj = session.get(clazz,id);
            session.delete(obj);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } finally {
            session.close();
        }
    }
}

main

 1 package a5_EmbeddedId;
 2 import daoUtil.HibernateUtil;
 3 
 4 public class Test_EmbeddedId {
 5 
 6     public static void main(String[] args) {
 7         
 8         Dog dog = new Dog();
 9         DogPK pk = new DogPK();
10         pk.setDog_name("wangcai");
11         pk.setId_no("5");
12         dog.setPk(pk);
13         dog.setMobile("13012345678");
14         
15         HibernateUtil.save(dog);
16         
17         dog = (Dog)HibernateUtil.getSession().get(Dog.class, dog.getPk());
18         System.out.println(dog.getPk().getId_no());
19     }
20 }

 

环境:JDK1.6,MAVEN,tomcat,eclipse

源码地址:http://files.cnblogs.com/files/xiluhua/hibernate%40EmbeddedId.rar

 

Hibernate,JPA注解@EmbeddedId

标签:

原文地址:http://www.cnblogs.com/xiluhua/p/4382062.html

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