com.xyz.framework.data.impl.JpaDao.java Source code

Java tutorial

Introduction

Here is the source code for com.xyz.framework.data.impl.JpaDao.java

Source

/**
 * Copyright (c) 2005-2009 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: HibernateDao.java,v 1.2 2009/09/25 06:08:05 test Exp $
 */
package com.xyz.framework.data.impl;

import java.io.Serializable;
import java.util.List;

import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import com.xyz.framework.data.DataUtil;
import com.xyz.framework.data.IDataObject;
import com.xyz.util.Page;
import com.xyz.util.PropertyFilter;
import com.xyz.util.ReflectionUtil;
import com.xyz.util.PropertyFilter.MatchType;

/**
 * ?Jdo DAO.
 * 
 * ,?. ?Service,?DAO?,?.
 * 
 * @param <T>
 *            DAO?
 * @param <PK>
 *            
 * 
 * @author calvin
 */
public class JpaDao<T, PK extends Serializable> extends SimpleJpaDao<T, PK> implements IDataObject<T, PK> {
    /**
     * Dao?. ??Class. eg. public class UserDao extends
     * HibernateDao<User, Long>{ }
     */
    public JpaDao() {
        super();
    }

    /**
     * 
     * 
     * @param entityClass
     */

    public JpaDao(final Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    //  //

    /**
     * ?.
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Page<T> getAll(final Page<T> page) {
        return findPage(page, "");
    }

    /**
     * jdoQL.
     * 
     * @param page
     *            ?.??orderBy?.
     * @param jdoQl
     *            hql?.
     * @param values
     *            ????,?.
     * 
     * @return , ??.
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Page<T> findPage(final Page<T> page, final String jpaQl) {
        Assert.notNull(page, "page?");
        String sql = getBaseSql();
        if (jpaQl != null && jpaQl.trim().length() > 0)
            sql += " where " + jpaQl;
        sql = dealOrder(sql, page);
        Query query = entityManager.createQuery(sql);
        if (page.isAutoCount()) {
            int totalCount = countJpaQlResult(jpaQl);
            page.setTotalCount(totalCount);
        }
        query.setFirstResult(page.getStart());
        query.setMaxResults(page.getLimit());
        List<T> lt = query.getResultList();
        page.setResult(lt);
        return page;
    }

    /**
     * .
     * 
     * @param page
     *            ?.??orderBy?.
     * @param jdoQl
     *            hql?.
     * @param values
     *            ????,?.
     * 
     * @return , ??.
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Page<T> findPage(final Page<T> page) {
        Assert.notNull(page, "page?");
        String sql = getBaseSql();
        sql = dealOrder(sql, page);
        Query query = entityManager.createQuery(sql);
        if (page.isAutoCount()) {
            int totalCount = countJpaQlResult("");
            page.setTotalCount(totalCount);
        }
        query.setFirstResult(page.getStart());
        query.setMaxResults(page.getLimit());
        List<T> lt = query.getResultList();
        page.setResult(lt);
        return page;
    }

    /**
     * ,??.
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Page<T> findBy(final Page page, final String propertyName, final Object value) {
        Assert.hasText(propertyName, "propertyName?");
        Assert.notNull(value, "value?");
        final String filter = buildPropertyFilterCriterion(propertyName, value, MatchType.EQ);
        String sql = getBaseSql() + " where " + filter;
        sql = dealOrder(sql, page);
        Query query = entityManager.createQuery(sql);
        if (page.isAutoCount()) {
            int totalCount = countJpaQlResult(filter);
            page.setTotalCount(totalCount);
        }
        query.setFirstResult(page.getStart());
        query.setMaxResults(page.getLimit());
        List<T> lt = query.getResultList();
        page.setResult(lt);
        return page;
    }

    /**
     * countHql.
     * 
     * ???jpaQl?,??jpaQl?count?.
     */
    public int countJpaQlResult(final String jpaQl) {

        String sql = " select count(1) from " + entityClass.getName() + " e ";
        if (jpaQl != null && jpaQl.trim().length() > 0)
            sql += " where " + jpaQl;
        String countQl = sql;
        int oi = sql.indexOf("order");
        if (oi > 0)
            countQl = sql.substring(0, oi);

        if (countQl.trim().length() > 0) {
            Query query = entityManager.createQuery(countQl);
            return (Integer) query.getSingleResult();
        } else {
            return 0;
        }
    }

    // ? //

    /**
     * ,????.
     * 
     * @param matchType
     *            ??,????PropertyFilterMatcheType enum.
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<T> findBy(final String propertyName, final Object value, final MatchType matchType) {
        String criterion = buildPropertyFilterCriterion(propertyName, value, matchType);
        return find(criterion);
    }

    /**
     * ?.
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<T> find(List<PropertyFilter> filters) {
        String criterions = buildPropertyFilterCriterions(filters);
        return find(criterions);
    }

    /**
     * ?.
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters) {

        String criterions = buildPropertyFilterCriterions(filters);
        return findPage(page, criterions);
    }

    /**
     * ?Criterion,.
     */
    public String buildPropertyFilterCriterions(final List<PropertyFilter> filters) {
        String fs = "";
        for (PropertyFilter filter : filters) {
            if (!filter.isMultiProperty()) { // ??.
                fs += buildPropertyFilterCriterion(filter.getPropertyName(), filter.getValue(),
                        filter.getMatchType());
            } else {// ??, && ?.
                for (String param : filter.getPropertyNames()) {
                    String criterion = buildPropertyFilterCriterion(param, filter.getValue(),
                            filter.getMatchType());
                    fs += criterion + " and ";
                }
            }
            fs += " and ";
        }
        int i = fs.lastIndexOf("and");
        if (i > 0)
            fs = fs.substring(0, i);
        return fs;
    }

    /**
     * ??Criterion,.
     */
    public String buildPropertyFilterCriterion(String propertyName, Object value, final MatchType matchType) {
        Assert.hasText(propertyName, "propertyName?");
        String criterion = null;
        try {
            // entity property.
            /*Object realValue = ReflectionUtil.convertValue(value, entityClass,
                  propertyName);*/
            // ???
            if (value instanceof String) {
                String str = (String) value;
                value = DataUtil.toSqlStr(str);
            }

            // ?MatchTypecriterion
            if (MatchType.EQ.equals(matchType)) {
                criterion = propertyName + " = " + value;
            }
            if (MatchType.LIKE.equals(matchType)) {
                criterion = propertyName + " like '%" + value + "%'";
            }
            if (MatchType.LE.equals(matchType)) {
                criterion = propertyName + " <= " + value;
            }
            if (MatchType.LT.equals(matchType)) {
                criterion = propertyName + " < " + value;
            }
            if (MatchType.GE.equals(matchType)) {
                criterion = propertyName + " >= " + value;
            }
            if (MatchType.GT.equals(matchType)) {
                criterion = propertyName + " > " + value;
            }
        } catch (Exception e) {
            throw ReflectionUtil.convertToUncheckedException(e);
        }
        return criterion;
    }

    /**
     * ??
     * @param page
     * @return
     */
    private String dealOrder(String jpaQl, Page<T> page) {
        if (page.isOrderBySetted()) {
            jpaQl += " order by " + page.getOrderBy();
        }
        return jpaQl;
    }

    /**
     * ??.
     * 
     * ,(value)?(orgValue)?.
     */
    public boolean isPropertyUnique(final String propertyName, final Object newValue, final Object oldValue) {
        if (newValue == null || newValue.equals(oldValue))
            return true;
        Object object = findUniqueBy(propertyName, newValue);
        return (object == null);
    }

}