Hibernate,JPA注解@SecondaryTable

使用类一级的 @SecondaryTable@SecondaryTables注解可以实现单个实体到多个表的映射. 使用 @Column或者 @JoinColumn注解中的table参数可指定某个列所属的特定表.

用例代码如下:

  • 数据库DDL语句

1,CAT表

create table CAT
(
  id          VARCHAR2(32 CHAR) not null,
  create_time TIMESTAMP(6),
  update_time TIMESTAMP(6),
  cat_name    VARCHAR2(255 CHAR),
  first_name  VARCHAR2(255 CHAR),
  last_name   VARCHAR2(255 CHAR),
  version     NUMBER(10) not null
)

2,CAT_INFO表

create table CAT_INFO
(
  address  VARCHAR2(255 CHAR),
  birthday TIMESTAMP(6),
  cat_id   VARCHAR2(32 CHAR) not null
)
  • 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="a6_SecondaryTable.Cat"/>
19         
20     </session-factory>
21 </hibernate-configuration>
  • java类

实体类 - 基类 

 1 package model;
 2 import java.io.Serializable;
 3 import java.util.Date;
 4 import javax.persistence.Column;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.Id;
 7 import javax.persistence.MappedSuperclass;
 8 import org.hibernate.annotations.GenericGenerator;
 9 /**
10  * 实体类 - 基类
11  */
12 @MappedSuperclass
13 public class BaseEntity implements Serializable {
14 
15     private static final long serialVersionUID = -6718838800112233445L;
16 
17     private String id;// ID
18     private Date create_time;// 创建日期
19     private Date update_time;// 修改日期
20     @Id
21     @Column(length = 32, nullable = true)
22     @GeneratedValue(generator = "uuid")
23     @GenericGenerator(name = "uuid", strategy = "uuid")
24     public String getId() {
25         return id;
26     }
27     public void setId(String id) {
28         this.id = id;
29     }
30     @Column(updatable = false)
31     public Date getCreate_time() {
32         return create_time;
33     }
34     public void setCreate_time(Date create_time) {
35         this.create_time = create_time;
36     }
37     public Date getUpdate_time() {
38         return update_time;
39     }
40     public void setUpdate_time(Date update_time) {
41         this.update_time = update_time;
42     }
43     @Override
44     public int hashCode() {
45         return id == null ? System.identityHashCode(this) : id.hashCode();
46     }
47     @Override
48     public boolean equals(Object obj) {
49         if (this == obj) {
50             return true;
51         }
52         if (obj == null) {
53             return false;
54         }
55         if (getClass().getPackage() != obj.getClass().getPackage()) {
56             return false;
57         }
58         final BaseEntity other = (BaseEntity) obj;
59         if (id == null) {
60             if (other.getId() != null) {
61                 return false;
62             }
63         } else if (!id.equals(other.getId())) {
64             return false;
65         }
66         return true;
67     }
68 }

实体类

 1 package a6_SecondaryTable;
 2 import java.util.Date;
 3 import javax.persistence.AttributeOverride;
 4 import javax.persistence.AttributeOverrides;
 5 import javax.persistence.Column;
 6 import javax.persistence.Embedded;
 7 import javax.persistence.Entity;
 8 import javax.persistence.PrimaryKeyJoinColumn;
 9 import javax.persistence.SecondaryTable;
10 import javax.persistence.Version;
11 import model.BaseEntity;
12 import org.hibernate.annotations.DynamicInsert;
13 import org.hibernate.annotations.DynamicUpdate;
14 
15 @Entity
16 @DynamicInsert
17 @DynamicUpdate
18 @SecondaryTable(name="CAT_INFO",pkJoinColumns=@PrimaryKeyJoinColumn(name="CAT_ID"))
19 public class Cat extends BaseEntity{
20     /**
21      * 实体类
22      */
23     private static final long serialVersionUID = -2776330321385582872L;
24 
25     private String cat_name;
26     private Name name;
27     private int version;
28     private String address;
29     private Date birthday;
30     
31     @Version
32     public int getVersion() {
33         return version;
34     }
35 
36     public void setVersion(int version) {
37         this.version = version;
38     }
39 
40     public String getCat_name() {
41         return cat_name;
42     }
43 
44     public void setCat_name(String cat_name) {
45         this.cat_name = cat_name;
46     }
47 
48     @Embedded
49     @AttributeOverrides({
50             @AttributeOverride(name = "first_name", column = @Column(name = "first_name")),
51             @AttributeOverride(name = "last_name", column = @Column(name = "last_name")) })
52     public Name getName() {
53         return name;
54     }
55 
56     public void setName(Name name) {
57         this.name = name;
58     }
59     @Column(name="ADDRESS", table="CAT_INFO")  
60     public String getAddress() {
61         return address;
62     }
63 
64     public void setAddress(String address) {
65         this.address = address;
66     }
67     @Column(name="BIRTHDAY", table="CAT_INFO")  
68     public Date getBirthday() {
69         return birthday;
70     }
71 
72     public void setBirthday(Date birthday) {
73         this.birthday = birthday;
74     }
75 }

Dao

 1 package daoUtil;
 2 import org.hibernate.HibernateException;
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.Transaction;
 6 import org.hibernate.cfg.Configuration;
 7 import org.hibernate.service.ServiceRegistry;
 8 import org.hibernate.service.ServiceRegistryBuilder;
 9 
10 public class HibernateUtil {
11 
12     private static final SessionFactory sessionFactory;
13 
14     static {
15         try {
16             Configuration cfg = new Configuration().configure();
17             ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
18                     .applySettings(cfg.getProperties()).buildServiceRegistry();
19             sessionFactory = cfg.buildSessionFactory(serviceRegistry);
20         } catch (Throwable ex) {
21             throw new ExceptionInInitializerError(ex);
22         }
23     }
24 
25     public static Session getSession() throws HibernateException {
26         return sessionFactory.openSession();
27     }
28 
29     public static Object save(Object obj){
30         Session session = HibernateUtil.getSession();
31         Transaction tx = null;
32         try {
33             tx = session.beginTransaction();
34             session.save(obj);
35             tx.commit();
36         } catch (RuntimeException e) {
37             if (tx != null) {
38                 tx.rollback();
39             }
40             throw e;
41         } finally {
42             session.close();
43         }
44         return obj;
45     }
46     
47     public static void delete(Class<?> clazz,String id){
48         Session session = HibernateUtil.getSession();
49         Transaction tx = null;
50         try {
51             tx = session.beginTransaction();
52             Object obj = session.get(clazz,id);
53             session.delete(obj);
54             tx.commit();
55         } catch (RuntimeException e) {
56             if (tx != null) {
57                 tx.rollback();
58             }
59             throw e;
60         } finally {
61             session.close();
62         }
63     }
64 }

main

 1 package a6_SecondaryTable;
 2 import daoUtil.HibernateUtil;
 3 
 4 public class Test_SecondaryTable {
 5 
 6     public static void main(String[] args) {
 7         
 8         Name name = new Name();
 9         Cat cat = new Cat();
10         cat.setCat_name("test7SecondaryTable1");
11         cat.setName(name);
12         cat.setAddress("中华人民共和国");
13         HibernateUtil.save(cat);
14         System.out.println(cat.getId());
15         
16         Cat cat1 = (Cat)HibernateUtil.getSession().get(Cat.class, cat.getId());
17         System.out.println(cat1.getId());
18     }
19 }

 

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

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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。