@Embeddable

JPA嵌入式對象(又名組件)
在實體中可以定義一個嵌入式組件(embedded component), 甚至覆蓋該實體中原有的列映射. 組件類必須在類一級定義@Embeddable註解. 在特定的實體的關聯屬性上使用@Embedded和@AttributeOverride註解可以覆蓋該屬性對應的嵌入式對象的列映射。

用例代碼如下:

數據庫DDL語句

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
)

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration
 PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 數據庫驅動配置 -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
        <property name="connection.username">wxuatuser</property>
        <property name="connection.password">xlh</property>
        <property name="show_sql">true</property>
        <!-- 自動執行DDL屬性是update,不是true -->
        <property name="hbm2ddl.auto">update</property>
        <!-- hibernate實體類 -->
        
        <mapping class="a4_Embeddable.Cat"/>
        
    </session-factory>
</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;
    }
}

實體類

package a4_Embeddable;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Version;
import model.BaseEntity;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

@Entity
@DynamicInsert
@DynamicUpdate
public class Cat extends BaseEntity{
    /**
     * 實體類
     */
    private static final long serialVersionUID = -2776330321385582872L;
    
    private String cat_name;
    private Name name;
    private int version;
    
    @Version
    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }
    
    public String getCat_name() {
        return cat_name;
    }

    public void setCat_name(String cat_name) {
        this.cat_name = cat_name;
    }
    
    @Embedded
    @AttributeOverrides( {
        @AttributeOverride(name = "first_name", column = @Column(name = "first_name")),
        @AttributeOverride(name = "last_name", column = @Column(name = "last_name")) })
    public Name getName() {
        return name;
    }

    public void setName(Name name) {
        this.name = name;
    }
}

組件類

package a4_Embeddable;
import java.io.Serializable;
import javax.persistence.Embeddable;

@Embeddable
public class Name implements Serializable {
    /**
     * 嵌入式組建
     */
    private static final long serialVersionUID = -2776330321385582872L;
    
    private String first_name;
    private String last_name;
    public String getFirst_name() {
        return first_name;
    }
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
    public String getLast_name() {
        return last_name;
    }
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
}

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

package a4_Embeddable;
import daoUtil.HibernateUtil;

public class Test_Embeddable {

    public static void main(String[] args) {
        
        Name name = new Name();
        name.setFirst_name("first");
        name.setLast_name("last");
        
        Cat cat = new Cat();
        cat.setCat_name("Tom");
        cat.setName(name);
        
        HibernateUtil.save(cat);
        
        cat = (Cat)HibernateUtil.getSession().get(Cat.class, cat.getId());
        System.out.println(cat.getName().getFirst_name());
    }
}

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

源碼地址:http://files.cnblogs.com/files/xiluhua/hibernate%40Embeddable.rar

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章