顯示具有 Hibernate 標籤的文章。 顯示所有文章
顯示具有 Hibernate 標籤的文章。 顯示所有文章

2013年2月1日 星期五

The Lost Part of Multi-tenancy in Hibernate

在Hibernate官方網站Chapter 16. Multi-tenancy中提到三種實現multi-tenancy的方法,分別是:
  1. Separate database
  2. Separate schema
  3. Partitioned (discriminator) data
前兩項在Hibernate 4已經有支援,但是最後一項discriminator很遺憾官方有說明如下:
Correlates to the partitioned (discriminator) approach. It is an error to attempt to open a session without a tenant identifier using this strategy. This strategy is not yet implemented in Hibernate as of 4.0 and 4.1. Its support is planned for 5.0.
所以在Hibernate 4之前我們得自己實現這樣的approach,深入思考一下,如果可以依照登入的使用者取得tenant ID,然後這個使用者產生的所有資料都自動填入tenant ID,而讀取資料的任何query都自動加上tenant ID這個condition,那麼不就完成了我們所想要的multi-tenancy機制嗎?所以我們將三種技術結合就可以達成這個目的:
  1. Spring Security
  2. Hibernate Filter
  3. Hibernate Interceptor
可以參考:
目前我們已經在部分系統中成功地實現這樣的概念。

Update Specific Columns Automatically by Hibernate Interceptor

如果我們想要在某些時機點固定更新某些欄位,但是又不想讓這種邏輯被寫死在DAO裡面,就可以利用Hibernate Interceptor這個功能完成這件事情。

舉例來說,如果我們想要記錄每筆資料是誰在什麼時間產生,又是誰在什麼時間做了修改,如果在每個DAO中去處理這件事情就需要花相當的力氣,而Hibernate Interceptor會是個不錯的選擇。

以下我們就實作這樣的例子,程式分為三大部分:
  1. 一組攔截generic property的Hibernate Interceptor API
  2. 記錄誰在什麼時間更新資料的API
  3. 設定與程式套用範例
Part I
EmbeddablePropertyInterceptor
package com.gss.gmo.cao.hibernate.interceptor;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;

import lombok.EqualsAndHashCode;
import lombok.SneakyThrows;
import lombok.ToString;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.util.ReflectionUtils;

/**
 * @author linus_chien
 *
 * @param <Embeddable>
 */
@EqualsAndHashCode(of = "embeddableClass", callSuper = false)
@ToString(of = "embeddableClass")
public abstract class EmbeddablePropertyInterceptor<Embeddable> extends EmptyInterceptor {

    private static final long serialVersionUID = 1L;

    private Class<Embeddable> embeddableClass;

    @SuppressWarnings("unchecked")
    public EmbeddablePropertyInterceptor() {
        java.lang.reflect.Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        embeddableClass = (Class<Embeddable>) pt.getActualTypeArguments()[0];
    }

    /**
     * @return new Embeddable instance.
     */
    @SneakyThrows
    private Embeddable newInstance() {
        return embeddableClass.newInstance();
    }

    @SuppressWarnings("unchecked")
    private Embeddable findEmbeddableProperty(Object entity, Object[] state, String[] propertyNames) {
        for (int i = 0; i < propertyNames.length; i++) {
            String propertyName = propertyNames[i];
            Field auditInfoField = ReflectionUtils.findField(entity.getClass(), propertyName, embeddableClass);
            if (auditInfoField != null) {
                if (state[i] == null) {
                    state[i] = newInstance();
                }
                return (Embeddable) state[i];
            }
        }
        return null;
    }

    @Override
    public final boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        Embeddable embeddable = findEmbeddableProperty(entity, state, propertyNames);
        if (embeddable != null) {
            takeCreateEvent(embeddable);
            return true;
        } else {
            return false;
        }
    }

    protected abstract void takeCreateEvent(Embeddable embeddable);

    @Override
    public final boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
        Embeddable embeddable = findEmbeddableProperty(entity, currentState, propertyNames);
        if (embeddable != null) {
            takeModifiedEvent(embeddable);
            return true;
        } else {
            return false;
        }
    }

    protected abstract void takeModifiedEvent(Embeddable embeddable);

}
EmbeddablePropertyInterceptorChainProxy
package com.gss.gmo.cao.hibernate.interceptor;

import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;

import lombok.extern.apachecommons.CommonsLog;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

@CommonsLog
public class EmbeddablePropertyInterceptorChainProxy extends EmptyInterceptor {

    private static final long serialVersionUID = 5566719359520070978L;

    private Set<EmbeddablePropertyInterceptor<?>> interceptorChain = new LinkedHashSet<EmbeddablePropertyInterceptor<?>>();

    public void setInterceptorChain(Set<EmbeddablePropertyInterceptor<?>> interceptorChain) {
        this.interceptorChain.addAll(interceptorChain);
    }

    public void addInterceptorChain(EmbeddablePropertyInterceptor<?> interceptor) {
        interceptorChain.add(interceptor);
    }

    @Override
    public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
        boolean isStateChanged = false;
        for (EmbeddablePropertyInterceptor<?> interceptor : interceptorChain) {
            log.debug("invoke onFlushDirty of " + interceptor.toString());

            if (interceptor.onFlushDirty(entity, id, currentState, previousState, propertyNames, types)) {
                isStateChanged = true;
            }
        }
        return isStateChanged;
    }

    @Override
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        boolean isStateChanged = false;
        for (EmbeddablePropertyInterceptor<?> interceptor : interceptorChain) {
            log.debug("invoke onSave of " + interceptor.toString());

            if (interceptor.onSave(entity, id, state, propertyNames, types)) {
                isStateChanged = true;
            }
        }
        return isStateChanged;
    }

}
小結:
在EmbeddablePropertyInterceptor裡面我們留了兩個abstract method,讓developer各自實作。
EmbeddablePropertyInterceptorChainProxy是為了可以攔截不同的property,但限制是type不能重複。

Part II
AuditInterceptor
package com.gss.gmo.cao.hibernate.audit;

import java.util.Date;

import org.springframework.beans.factory.annotation.Required;

import com.gss.gmo.cao.hibernate.interceptor.EmbeddablePropertyInterceptor;

/**
 * Auto-set values of createUserId, createDate, lastModifiedUserId and
 * lastModifiedDate.
 *
 * @author linus_chien
 *
 */
public class AuditInterceptor extends EmbeddablePropertyInterceptor<AuditInfo> {

    private static final long serialVersionUID = 1L;

    /**
     * Provide audit user id.
     */
    private AuditUserIdAware auditUserIdAware;

    @Required
    public void setAuditUserIdAware(AuditUserIdAware auditUserIdAware) {
        this.auditUserIdAware = auditUserIdAware;
    }

    @Override
    protected void takeCreateEvent(AuditInfo auditInfo) {
        auditInfo.setCreateUserId(auditUserIdAware.getAuditUserId());
        auditInfo.setCreateUserName(auditUserIdAware.getAuditUserName());
        auditInfo.setCreateUserEnglishName(auditUserIdAware.getAuditUserEnglishName());
        auditInfo.setCreateDate(new Date());
    }

    @Override
    protected void takeModifiedEvent(AuditInfo auditInfo) {
        auditInfo.setLastModifiedUserId(auditUserIdAware.getAuditUserId());
        auditInfo.setLastModifiedUserName(auditUserIdAware.getAuditUserName());
        auditInfo.setLastModifiedUserEnglishName(auditUserIdAware.getAuditUserEnglishName());
        auditInfo.setLastModifiedDate(new Date());
    }

}
AuditUserIdAware
package com.gss.gmo.cao.hibernate.audit;

import java.io.Serializable;

/**
 * @author linus_chien
 *
 */
public interface AuditUserIdAware extends Serializable {

    /**
     * @return user id for auditing.
     */
    String getAuditUserId();

    /**
     * @return user name for auditing.
     */
    String getAuditUserName();

    /**
     * @return user English name for auditing.
     */
    String getAuditUserEnglishName();

}
AuditInfo
package com.gss.gmo.cao.hibernate.audit;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Embeddable;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @author linus_chien
 *
 */
@Getter
@Setter
@ToString
@Embeddable
public class AuditInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * column length.
     */
    private static final int LENGTH = 50;

    /**
     * create user id.
     */
    @Column(name = "CREATE_USER_ID", length = LENGTH)
    private String createUserId;

    /**
     * create user name.
     */
    @Column(name = "CREATE_USER_NAME", length = LENGTH)
    private String createUserName;

    /**
     * create user English name.
     */
    @Column(name = "CREATE_USER_ENGLISH_NAME", length = LENGTH)
    private String createUserEnglishName;

    /**
     * create date.
     */
    @Column(name = "CREATE_DATE")
    private Date createDate;

    /**
     * last modified user id.
     */
    @Column(name = "LAST_MODIFIED_USER_ID", length = LENGTH)
    private String lastModifiedUserId;

    /**
     * last modified user name.
     */
    @Column(name = "LAST_MODIFIED_USER_NAME", length = LENGTH)
    private String lastModifiedUserName;

    /**
     * last modified English name.
     */
    @Column(name = "LAST_MODIFIED_USER_ENGLISH_NAME", length = LENGTH)
    private String lastModifiedUserEnglishName;

    /**
     * last modified date.
     */
    @Column(name = "LAST_MODIFIED_DATE")
    private Date lastModifiedDate;

}
小結:
讓Hibernate Interceptor幫我們攔截AuditInfo;AuditUserIdAware是為了loose coupling,不讓取得使用者資訊的程式碼出現在AuditInterceptor裡面。

Part III
Person
package com.gss.gmo.cao.hibernate.impl;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;

import org.hibernate.annotations.Filter;
import org.hibernate.annotations.Type;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import com.gss.gmo.cao.base.BaseDto;
import com.gss.gmo.cao.hibernate.audit.AuditInfo;

/**
 * @author linus_chien
 *
 */
@Getter
@Setter
@EqualsAndHashCode(callSuper = false, of = { "id" })
@ToString
@Entity
@Filter(name = "personFilter", condition = "name like :name and address is null")
public class Person extends BaseDto {

    private static final long serialVersionUID = 1L;

    @Id
    private String id;

    @Column
    private String name;

    @Column
    private String address;

    @Embedded
    private AuditInfo auditInfo;

    @Type(type = "listType")
    private List<String> emails;

}
LoginUserIdProvider
package com.gss.gmo.cao.hibernate.impl;

import com.gss.gmo.cao.hibernate.audit.AuditUserIdAware;

public class LoginUserIdProvider implements AuditUserIdAware {

    private static final long serialVersionUID = -5133132384619280103L;

    @Override
    public String getAuditUserId() {
        return "linus_chien";
    }

    @Override
    public String getAuditUserName() {
        return "Cheng-Ming Chien";
    }

    @Override
    public String getAuditUserEnglishName() {
        return "Linus";
    }

}
SpringConfig
package com.gss.gmo.cao.hibernate.impl;

import org.hibernate.Interceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.gss.gmo.cao.hibernate.audit.AuditInterceptor;
import com.gss.gmo.cao.hibernate.interceptor.EmbeddablePropertyInterceptorChainProxy;

@Configuration
public class SpringConfig {

    @Bean
    public Interceptor embeddablePropertyInterceptorChainProxy() {
        EmbeddablePropertyInterceptorChainProxy interceptor = new EmbeddablePropertyInterceptorChainProxy();
        AuditInterceptor auditInterceptor = new AuditInterceptor();
        auditInterceptor.setAuditUserIdAware(new LoginUserIdProvider());
        interceptor.addInterceptorChain(auditInterceptor);
        return interceptor;
    }

}
Spring XML
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.format_sql">true</prop>
        </props>
    </property>
    <property name="packagesToScan" value="com.gss.gmo.cao.hibernate.impl" />
    <property name="annotatedPackages" value="com.gss.gmo.cao.hibernate.impl" />
    <property name="entityInterceptor" ref="embeddablePropertyInterceptorChainProxy" />
</bean>
小結:
LoginUserIdProvider裡面可以和Spring Security整合,取得目前登入的使用者資訊。

2013年1月24日 星期四

Enable Hibernate Filter Dynamically

Hibernate Filter功能的主要目的是預先設定好filter definition和filter condition,然後在操作Hibernate session時決定要不要enable filter並提供要傳入condition的變數,將一些公用的condition抽離到filter中,Hibernate會在符合filter設定的任何查詢上都補上定義好的condition。

但這樣還不夠好,原因是這樣的使用方式會讓DAO裡面充滿enable filter的程式碼,developer必須了解這些filter的規範才能正確使用,如果我們會依照使用者的身份決定condition的值,那麼與security有關的API就會汙染DAO,為此,我們利用Spring AOP的功能來完成enable filter dynamically的機制,讓interceptor來決定目前被攔截的DAO是否需要enable filter並傳入condition變數。

以下的程式碼分為兩大部分,interceptor and test case。

Interceptor:
EnableFilterInterceptor
package com.gss.gmo.cao.hibernate.filter;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

import lombok.SneakyThrows;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.hibernate.Filter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.util.ReflectionUtils;

import com.gss.gmo.cao.hibernate.HibernateGenericDao;
import com.gss.gmo.cao.hibernate.HibernateGenericPagingDao;

/**
 * @author linus_chien
 *
 */
public class EnableFilterInterceptor implements MethodInterceptor {

    /**
     * Provide filter name and parameters to enable.
     */
    private EnableFilterInfoAware enableFilterInfoAware;

    /**
     * @param enableFilterInfoAware
     */
    @Required
    public void setEnableFilterInfoAware(EnableFilterInfoAware enableFilterInfoAware) {
        this.enableFilterInfoAware = enableFilterInfoAware;
    }

    @Override
    @SneakyThrows
    public Object invoke(MethodInvocation invocation) {
        Object target = invocation.getThis();
        if (target instanceof HibernateGenericDao || target instanceof HibernateGenericPagingDao) {
            SessionFactory sessionFactory = getSessionFactory(target);
            Session session = sessionFactory.getCurrentSession();
            @SuppressWarnings("unchecked")
            Set<String> filterNames = sessionFactory.getDefinedFilterNames();
            Map<String, Map<String, Object>> filterInfo = enableFilterInfoAware.getEnableFilterInfo();
            for (String filterName : filterNames) {
                if (filterInfo.containsKey(filterName)) {
                    Filter filter = session.getEnabledFilter(filterName);
                    if (filter == null) {
                        filter = session.enableFilter(filterName);
                        Map<String, Object> parameters = filterInfo.get(filterName);
                        for (String parameterName : parameters.keySet()) {
                            Object parameterValue = parameters.get(parameterName);
                            filter.setParameter(parameterName, parameterValue);
                        }
                        filter.validate();
                    }
                }
            }
        }

        Object result = invocation.proceed();
        return result;
    }

    /**
     * @param target
     * @return SessionFactory
     */
    private SessionFactory getSessionFactory(Object target) {
        Field sessionFactoryField = ReflectionUtils.findField(target.getClass(), "sessionFactory", SessionFactory.class);
        ReflectionUtils.makeAccessible(sessionFactoryField);
        return (SessionFactory) ReflectionUtils.getField(sessionFactoryField, target);
    }

}
EnableFilterInfoAware
package com.gss.gmo.cao.hibernate.filter;

import java.util.Map;

/**
 * @author linus_chien
 *
 */
public interface EnableFilterInfoAware {

    /**
     * Key: filter name, Value: parameters (Key: parameter name, Value: value).
     *
     * @return
     */
    Map<String, Map<String, Object>> getEnableFilterInfo();

}
EnableFilterInfoAware的用意事實上就是Strategy Pattern的一種應用,再一次將怎麼enable filter這件事交給strategy object負責。

Test Case包含四小部分:
  1. Filter Definition:package-info.java
  2. Filter:Person
  3. Implement Strategy:EnableFilterInfoProvider
  4. Setup AOP:Spring XML
package-info.java
/**
 * @author linus_chien
 *
 */
@FilterDef(name = "personFilter", parameters = { @ParamDef(name = "name", type = "string"), @ParamDef(name = "address", type = "string") })
@TypeDef(name = "listType", typeClass = ListJsonType.class)
package com.gss.gmo.cao.hibernate.impl;

import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
import org.hibernate.annotations.TypeDef;
Person
package com.gss.gmo.cao.hibernate.impl;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;

import org.hibernate.annotations.Filter;
import org.hibernate.annotations.Type;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import com.gss.gmo.cao.base.BaseDto;
import com.gss.gmo.cao.hibernate.audit.AuditInfo;

/**
 * @author linus_chien
 *
 */
@Getter
@Setter
@EqualsAndHashCode(callSuper = false, of = { "id" })
@ToString
@Entity
@Filter(name = "personFilter", condition = "name like :name and address is null")
public class Person extends BaseDto {

    private static final long serialVersionUID = 1L;

    @Id
    private String id;

    @Column
    private String name;

    @Column
    private String address;

    @Embedded
    private AuditInfo auditInfo;

    @Type(type = "listType")
    private List<String> emails;

}
EnableFilterInfoProvider
package com.gss.gmo.cao.hibernate.impl;

import java.util.HashMap;
import java.util.Map;

import com.gss.gmo.cao.hibernate.filter.EnableFilterInfoAware;

public class EnableFilterInfoProvider implements EnableFilterInfoAware {

    @Override
    public Map<String, Map<String, Object>> getEnableFilterInfo() {
        Map<String, Map<String, Object>> enableFilterInfo = new HashMap<String, Map<String, Object>>();
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("name", "%Linus%");
        parameter.put("address", "abc");
        enableFilterInfo.put("personFilter", parameter);
        return enableFilterInfo;
    }

}
Spring XML
<aop:config>
    <aop:pointcut id="daoPointcut" expression="execution(* com.gss.gmo.cao.hibernate.*Dao.*(..))" />
    <aop:advisor advice-ref="daoAdvice" pointcut-ref="daoPointcut" />
</aop:config>

<bean id="daoAdvice" class="com.gss.gmo.cao.hibernate.filter.EnableFilterInterceptor">
    <property name="enableFilterInfoAware">
        <bean class="com.gss.gmo.cao.hibernate.impl.EnableFilterInfoProvider" />
    </property>
</bean>
這樣只要是被攔截到的DAO就會enable filter,然後只要查詢Person就會補上額外的condition,而相同的filter definition套在每個entity都能有不同的condition。想像一下,如果今天要做到個人只能看個人的資料,而主管可以看到部門內所有人的資料,利用這個方式就不需要在DAO裡面implement這樣的邏輯,而是交給Hibernate Filter和Strategy處理了。

最後我們看一下Hibernate實際下的SQL statement:
Show SQL
Hibernate:
    select
        count(*) as y0_
    from
        Person this_
    where
        this_.name like ? 
        and this_.address is null
        and (
            this_.name=?
        )

2013年1月21日 星期一

Hibernate Generic Paging DAO

在頁面上處理lazy loading分頁資料不外乎要計算:
  1. 總筆數
  2. 依每頁顯示筆數計算總頁數
  3. 計算要顯示頁數第一筆資料的offset
如果我們仔細分析,會發現事實上取得資料總筆數和撈取某一頁所需的資料,這兩者的SQL statement在where condition應是一模一樣的,根據這一點我們可以design出paging專用的DAO。

以下會包含兩大部分,一是generic paging DAO的設計,二是test case。

Generic Paging DAO:
  1. GenericPagingDao<Entity extends BaseDto, Condition>
  2. AbstractGenericPagingDaoImpl<Entity extends BaseDto, Condition>
  3. HibernateGenericPagingDao<Entity extends BaseDto, Condition>
  4. AbstractHibernateGenericPagingDaoImpl<Entity extends BaseDto, Condition>
  5. BaseDto
GenericPagingDao<Entity extends BaseDto, Condition>
package com.gss.gmo.cao.data;

import java.util.List;

import com.gss.gmo.cao.base.BaseDto;

/**
 * @author linus_chien
 *
 * @param <Entity>
 * @param <Condition>
 */
public interface GenericPagingDao<Entity extends BaseDto, Condition> {

    Class<Entity> getEntityClass();

    List<Entity> findPagingResults(Condition condition, int firstResult, int maxResults);

    <ResultClass> List<ResultClass> findPagingTransformResults(Condition condition, int firstResult, int maxResults, Class<ResultClass> resultClass);

    long getRowCount(Condition condition);

}
AbstractGenericPagingDaoImpl<Entity extends BaseDto, Condition>
package com.gss.gmo.cao.data.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.gss.gmo.cao.base.BaseDto;
import com.gss.gmo.cao.data.GenericPagingDao;

/**
 * @author linus_chien
 *
 * @param <Entity>
 * @param <Condition>
 */
public abstract class AbstractGenericPagingDaoImpl<Entity extends BaseDto, Condition> implements GenericPagingDao<Entity, Condition> {

    /**
     * Class of entity.
     */
    private final Class<Entity> entityClass;

    /**
     * Init entityClass by generic type.
     */
    @SuppressWarnings("unchecked")
    public AbstractGenericPagingDaoImpl() {
        Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        entityClass = (Class<Entity>) pt.getActualTypeArguments()[0];
    }

    @Override
    public final Class<Entity> getEntityClass() {
        return entityClass;
    }

}
HibernateGenericPagingDao<Entity extends BaseDto, Condition>
package com.gss.gmo.cao.hibernate;

import org.hibernate.SessionFactory;

import com.gss.gmo.cao.base.BaseDto;
import com.gss.gmo.cao.data.GenericPagingDao;

/**
 * @author linus_chien
 *
 * @param <Entity>
 * @param <Condition>
 */
public interface HibernateGenericPagingDao<Entity extends BaseDto, Condition> extends GenericPagingDao<Entity, Condition> {

    /**
     * @param sessionFactory
     */
    void setSessionFactory(SessionFactory sessionFactory);

}
AbstractHibernateGenericPagingDaoImpl<Entity extends BaseDto, Condition>
package com.gss.gmo.cao.hibernate.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;

import com.gss.gmo.cao.base.BaseDto;
import com.gss.gmo.cao.data.impl.AbstractGenericPagingDaoImpl;
import com.gss.gmo.cao.hibernate.HibernateGenericPagingDao;

/**
 * @author linus_chien
 *
 * @param <Entity>
 * @param <Condition>
 */
public abstract class AbstractHibernateGenericPagingDaoImpl<Entity extends BaseDto, Condition> extends AbstractGenericPagingDaoImpl<Entity, Condition>
        implements HibernateGenericPagingDao<Entity, Condition> {

    /**
     * SessionFactory instance.
     */
    private SessionFactory sessionFactory;

    @Autowired
    @Required
    @Override
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * @return Current session.
     */
    protected Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public List<Entity> findPagingResults(final Condition condition, final int firstResult, final int maxResults) {
        return findPagingTransformResults(condition, firstResult, maxResults, getEntityClass());
    }

    @SuppressWarnings("unchecked")
    @Override
    public <ResultClass> List<ResultClass> findPagingTransformResults(Condition condition, int firstResult, int maxResults, Class<ResultClass> resultClass) {
        Criteria criteria = getCurrentSession().createCriteria(getEntityClass(), getEntityClass().getSimpleName().toLowerCase());
        initCriteria(condition, criteria);
        exclusiveForPagingResults(condition, criteria);
        criteria.setFirstResult(firstResult);
        criteria.setMaxResults(maxResults);
        if (getEntityClass() != resultClass) {
            criteria.setResultTransformer(new AliasToBeanResultTransformer(resultClass));
        }
        return criteria.list();
    }

    @Override
    public long getRowCount(final Condition condition) {
        Criteria criteria = getCurrentSession().createCriteria(getEntityClass());
        initCriteria(condition, criteria);
        criteria.setProjection(Projections.rowCount());
        return (Long) criteria.uniqueResult();
    }

    /**
     * Setup criteria by generic Condition type.
     *
     * @param condition
     * @param criteria
     */
    protected abstract void initCriteria(Condition condition, Criteria criteria);

    /**
     * Execute this method only for findPagingResults. Do nothing by default.
     *
     * @param condition
     * @param criteria
     */
    protected void exclusiveForPagingResults(Condition condition, Criteria criteria) {
    }

}
BaseDto
package com.gss.gmo.cao.base;

import java.io.Serializable;

/**
 * Force DTO to implement equals(), hashCode(), toString().
 *
 * @author linus_chien
 *
 */
public abstract class BaseDto implements Serializable {

    private static final long serialVersionUID = 1L;

    @Override
    public abstract int hashCode();

    @Override
    public abstract boolean equals(Object obj);

    @Override
    public abstract String toString();

}
Test Case:
  1. Person
  2. PersonPagingDao
  3. PersonPagingDaoImpl
  4. AbstractHibernateGenericPagingDaoImplTest
  5. AbstractHibernateGenericPagingDaoImplTest-context.xml
Person
package com.gss.gmo.cao.hibernate.impl;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;

import org.hibernate.annotations.Filter;
import org.hibernate.annotations.Type;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import com.gss.gmo.cao.base.BaseDto;
import com.gss.gmo.cao.hibernate.audit.AuditInfo;

/**
 * @author linus_chien
 *
 */
@Getter
@Setter
@EqualsAndHashCode(callSuper = false, of = { "id" })
@ToString
@Entity
@Filter(name = "personFilter", condition = "name like :name and address is null")
public class Person extends BaseDto {

    private static final long serialVersionUID = 1L;

    @Id
    private String id;

    @Column
    private String name;

    @Column
    private String address;

    @Embedded
    private AuditInfo auditInfo;

    @Type(type = "listType")
    private List<String> emails;

}
PersonPagingDao
package com.gss.gmo.cao.hibernate;

import com.gss.gmo.cao.hibernate.impl.Person;

public interface PersonPagingDao extends HibernateGenericPagingDao<Person, String> {

}
PersonPagingDaoImpl
package com.gss.gmo.cao.hibernate.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.gss.gmo.cao.hibernate.PersonPagingDao;

@Component
public class PersonPagingDaoImpl extends AbstractHibernateGenericPagingDaoImpl<Person, String> implements PersonPagingDao {

    @Override
    protected void initCriteria(String condition, Criteria criteria) {
        criteria.add(Restrictions.eq("name", condition));
    }

    @Override
    protected void exclusiveForPagingResults(String condition, Criteria criteria) {
        criteria.addOrder(Order.desc("name"));
    }

}
AbstractHibernateGenericPagingDaoImplTest
package com.gss.gmo.cao.hibernate.impl;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.gss.gmo.cao.hibernate.PersonDao;
import com.gss.gmo.cao.hibernate.PersonPagingDao;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration(defaultRollback = false)
@Transactional
public class AbstractHibernateGenericPagingDaoImplTest {

    @Autowired
    private PersonDao personDao;

    @Autowired
    private PersonPagingDao personPagingDao;

    @Test
    public void testFindPagingResults() {
        Person person = new Person();
        person.setId("A");
        person.setName("Linus");
        personDao.save(person);

        person = new Person();
        person.setId("B");
        person.setName("Linus");
        personDao.save(person);

        person = new Person();
        person.setId("C");
        person.setName("Linus");
        personDao.save(person);

        List<Person> persons = personPagingDao.findPagingResults("Linus", 1, 2);
        assertEquals(2, persons.size());

        persons = personPagingDao.findPagingResults("A", 1, 2);
        assertEquals(0, persons.size());
    }

    @Test
    public void testGetRowCount() {
        assertEquals(3, personPagingDao.getRowCount("Linus"));
        assertEquals(0, personPagingDao.getRowCount("A"));
    }

    @Test
    public void testFindPagingTransformResults() {
        List<PersonWrapper> personWrappers = personPagingDao.findPagingTransformResults("Linus", 1, 2, PersonWrapper.class);
        assertEquals(2, personWrappers.size());
        for (PersonWrapper personWrapper : personWrappers) {
            assertEquals("Linus", personWrapper.getPerson().getName());
        }
    }

}
AbstractHibernateGenericPagingDaoImplTest-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.gss.gmo.cao.hibernate.impl" />
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Datasource -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver">
        </property>
        <property name="url" value="jdbc:hsqldb:mem:ExampleTest">
        </property>
        <property name="username" value="sa">
        </property>
        <property name="password" value="">
        </property>
    </bean>

    <!-- Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan" value="com.gss.gmo.cao.hibernate.impl" />
        <property name="annotatedPackages" value="com.gss.gmo.cao.hibernate.impl" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>
Test case裡面的PersonDao只是一般CRUD的DAO,這裡就不浪費版面多做贅述。

2013年1月18日 星期五

Customize Hibernate JSON UserType & Apply Package Level Annotation

這裡我們展示如何自訂一個generic UserType,功能是將entity的任意物件轉換成JSON之後以String的方式儲存到database中,然後提供一個sample供參考,而這個sample會以package level的方式設定。
GenericJsonStringType<T>
package com.gss.gmo.cao.hibernate.usertype;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;

import org.apache.commons.lang3.ObjectUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.gss.gmo.cao.gson.ISODateTimeAdapter;

public abstract class GenericJsonStringType<T> implements UserType {

    private static final int[] SQL_TYPES = { Types.LONGVARCHAR };

    private final Type userType;

    private final Gson gson;

    public GenericJsonStringType() {
        Type type = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) type;
        userType = pt.getActualTypeArguments()[0];
        gson = new GsonBuilder().registerTypeAdapter(Date.class, new ISODateTimeAdapter()).create();
    }

    @Override
    public int[] sqlTypes() {
        return SQL_TYPES;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public Class returnedClass() {
        if (userType instanceof Class) {
            return (Class) userType;
        } else {
            return (Class) ((ParameterizedType) userType).getRawType();
        }
    }

    @Override
    public boolean equals(Object x, Object y) throws HibernateException {
        return ObjectUtils.equals(x, y);
    }

    @Override
    public int hashCode(Object x) throws HibernateException {
        return x.hashCode();
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
        String jsonString = rs.getString(names[0]);
        return gson.fromJson(jsonString, userType);
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
        st.setString(index, gson.toJson(value, userType));
    }

    @Override
    public Object deepCopy(Object value) throws HibernateException {
        return gson.fromJson(gson.toJson(value, userType), userType);
    }

    @Override
    public boolean isMutable() {
        return true;
    }

    @Override
    public Serializable disassemble(Object value) throws HibernateException {
        return gson.toJson(value, userType);
    }

    @Override
    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return gson.fromJson((String) cached, userType);
    }

    @Override
    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return original;
    }

}
Sample有四個部分:
  1. Setup org.springframework.orm.hibernate4.LocalSessionFactoryBean
  2. Setup org.hibernate.annotations.TypeDef in package-info.java
  3. Extend GenericJsonStringType<T>
  4. Mapping UserType field in entity
Setup org.springframework.orm.hibernate4.LocalSessionFactoryBean
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.format_sql">true</prop>
        </props>
    </property>
    <property name="packagesToScan" value="com.gss.gmo.cao.hibernate.impl" />
    <property name="annotatedPackages" value="com.gss.gmo.cao.hibernate.impl" />
</bean>
Setup org.hibernate.annotations.TypeDef in package-info.java
@TypeDef(name = "listType", typeClass = ListJsonType.class)
package com.gss.gmo.cao.hibernate.impl;

import org.hibernate.annotations.TypeDef;
Extend GenericJsonStringType<T>
package com.gss.gmo.cao.hibernate.impl;

import java.util.List;
import com.gss.gmo.cao.hibernate.usertype.GenericJsonStringType;

public class ListJsonType extends GenericJsonStringType<List<String>> {
}
Mapping UserType field in entity
package com.gss.gmo.cao.hibernate.impl;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import org.hibernate.annotations.Type;

import com.gss.gmo.cao.base.BaseDto;
import com.gss.gmo.cao.hibernate.audit.AuditInfo;

/**
 * @author linus_chien
 *
 */
@Getter
@Setter
@EqualsAndHashCode(callSuper = false, of = { "id" })
@ToString
@Entity
public class Person extends BaseDto {

    private static final long serialVersionUID = 1L;

    @Id
    private String id;

    @Column
    private String name;

    @Column
    private String address;

    @Embedded
    private AuditInfo auditInfo;

    @Type(type = "listType")
    private List<String> emails;

}

2013年1月8日 星期二

Hibernate hbm2ddl API

Hibernate提供了hbm2ddl的設定可以在啟動時create table schema,那麼這個API在哪呢?
答案是:org.hibernate.tool.hbm2ddl.SchemaExport
以下是將script打印在console上,而不真的執行sql的程式範例。
代碼:
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ActiveProfiles("test")
public class ExportCreateScript {
    @Autowired
    private AnnotationSessionFactoryBean sessionFactory;

    @Test
    public void test() {
        SchemaExport export = new SchemaExport(sessionFactory.getConfiguration());
        export.setDelimiter(";");
        export.create(true, false);
    }
}