com.lakeside.data.sqldb.BaseDao.java Source code

Java tutorial

Introduction

Here is the source code for com.lakeside.data.sqldb.BaseDao.java

Source

/**
 * Copyright (c) 2005-2009 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: SimpleHibernateDao.java 1139 2010-07-31 15:25:32Z calvinxiu $
 */
package com.lakeside.data.sqldb;

import com.lakeside.core.utils.Assert;
import com.lakeside.core.utils.ReflectionUtils;
import org.hibernate.*;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import javax.sql.DataSource;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ?HibernateAPIDAO.
 * 
 * ?Service,?DAO?.
 * ?Spring2.5Petlinc?,?HibernateTemplate,HibernateAPI.
 * 
 * @param <T> DAO?
 * @param <PK> 
 * 
 * @author calvin
 */
@SuppressWarnings("unchecked")
public class BaseDao<T, PK extends Serializable> {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected SessionFactory sessionFactory;

    protected Class<T> entityClass;

    protected NamedParameterJdbcTemplate jdbcTemplate;

    private DataSource dataSource;

    public static final HashMap<String, Object> EMPTY_PARAMETER = null;

    /**
     * Dao?.
     * ??Class.
     * eg.
     * public class UserDao extends BaseDao<User, Long>
     */
    public BaseDao() {
        this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());

    }

    /**
     * ?Dao, ServiceBaseDao.
     * Class.
     * eg.
     * BaseDao<User, Long> userDao = new BaseDao<User, Long>(sessionFactory, User.class);
     */
    public BaseDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
        this.sessionFactory = sessionFactory;
        this.entityClass = entityClass;
    }

    /**
     * ?sessionFactory.
     */
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * @AutowiredSessionFactory, SesionFactoryOverride.
     */
    @Autowired
    public void setDataSource(final DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * @AutowiredSessionFactory, SesionFactoryOverride.
     */
    @Autowired
    public void setSessionFactory(final SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Autowired
    public void setJdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * ??Session.
     */
    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * ?.
     */
    public void save(final T entity) {
        Assert.notNull(entity, "entity?");
        getSession().saveOrUpdate(entity);
        logger.debug("save entity: {}", entity);
    }

    /**
     * .
     * 
     * @param entity session?idtransient.
     */
    public void delete(final T entity) {
        Assert.notNull(entity, "entity?");
        getSession().delete(entity);
        logger.debug("delete entity: {}", entity);
    }

    /**
     * id.
     */
    public void delete(final PK id) {
        Assert.notNull(id, "id?");
        delete(get(id));
        logger.debug("delete entity {},id is {}", entityClass.getSimpleName(), id);
    }

    /**
     * ?.
     * load()Proxy, View???.
     * ??entity,????.
     * ??,?,:
     * Hibernate.initialize(user.getRoles())?User??.
     * Hibernate.initialize(user.getDescription())?UserDescription.
     */
    public void initProxyProperty(Object proxyProperty) {
        Hibernate.initialize(proxyProperty);
    }

    /**
     * Flush?Session.
     */
    public void flush() {
        getSession().flush();
    }

    /**
     * id?.
     */
    public T get(final PK id) {
        Assert.notNull(id, "id?");
        return (T) getSession().get(entityClass, id);
    }

    /**
     *   ?.
     */
    public List<T> getAll() {
        return find();
    }

    /**
     * ?
     * @param entity
     * @return
     */
    public T merge(final T entity) {
        Assert.notNull(entity, "entity?");
        Session session = getSession();
        String idName = getIdName();
        PropertyDescriptor idp = BeanUtils.getPropertyDescriptor(entityClass, idName);
        PK idvalue = null;
        try {
            idvalue = (PK) idp.getReadMethod().invoke(entity);
        } catch (Exception e) {
            throw new FatalBeanException("Could not copy properties from source to target", e);
        }
        T dest = null;
        if (idvalue != null) {
            dest = (T) session.get(entityClass, idvalue);
        }
        if (dest != null) {
            // merge the properties
            PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(entityClass);
            for (PropertyDescriptor p : descriptors) {
                if (p.getWriteMethod() != null) {
                    try {
                        Method readMethod = p.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(entity);
                        if (value == null) {
                            continue;
                        }
                        Method writeMethod = p.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(dest, value);
                    } catch (Throwable ex) {
                        throw new FatalBeanException("Could not copy properties from source to target", ex);
                    }
                }
            }
        } else {
            // destination object is empty, save the entity object parameted
            dest = entity;
        }
        session.saveOrUpdate(dest);
        logger.debug("merge entity: {}", entity);
        return dest;
    }

    /**
     * Criteria.
     * 
     * @param criterions ???Criterion.
     */
    public List<T> find(final Criterion... criterions) {
        return createCriteria(criterions).list();
    }

    /**
     * ?Criterion?Criteria.
     * 
     * ?find()T,?T.
     * 
     * @param criterions ???Criterion.
     */
    protected Criteria createCriteria(final Criterion... criterions) {
        Criteria criteria = getSession().createCriteria(entityClass);
        for (Criterion c : criterions) {
            criteria.add(c);
        }
        return criteria;
    }

    /**
     * HQL.
     * 
     * @param values ???,??.
     */
    public <X> List<X> find(final String hql, final Map<String, ?> values) {
        return createQuery(hql, values).list();
    }

    /**
     * HQL.
     * 
     * @param values ???,??.
     */
    public <X> X findUnique(final String hql, final Map<String, ?> values) {
        return (X) createQuery(hql, values).uniqueResult();
    }

    /**
     * ,??.
     * 
     */
    public T findUniqueBy(final String propertyName, final Object value) {
        Assert.hasText(propertyName, "propertyName?");
        Criterion criterion = Restrictions.eq(propertyName, value);
        return (T) createCriteria(criterion).uniqueResult();
    }

    /**
     * HQL?/?.
     * @return .
     */
    public int batchExecute(final String hql, final Map<String, ?> values) {
        Assert.hasText(hql, "hql?");
        return createQuery(hql, values).executeUpdate();
    }

    /**
     * ?HQL?Query.
     * 
     * @param values ???,??.
     */
    public Query createQuery(final String hql, final Map<String, ?> values) {
        Assert.hasText(hql, "hql?");
        Query query = getSession().createQuery(hql);
        if (values != null) {
            query.setProperties(values);
        }
        return query;
    }

    /**
     * ???.
     */
    public String getIdName() {
        ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
        return meta.getIdentifierPropertyName();
    }

    /**
     * jdbcTemplatecount
     * @param sql sql?
     * @param paramMap ???,??.
     * @return 1?
     */
    public int jfindInt(final String sql, final Map<String, ?> paramMap) {
        return jdbcTemplate.queryForInt(sql, paramMap);
    }

    /**
     * jdbcTemplate?
     * @param <X>?
     * @param paramMap ???,??.
     * @param elementType ??
     * @return 
     */
    public <X> List<X> jfind(final String sql, final Map<String, ?> paramMap, final Class<X> elementType) {
        return jdbcTemplate.query(sql, paramMap, new BeanPropertyRowMapper<X>(elementType));
    }

    /**
     * jdbcTemplate
     * @param paramMap ???,??.
     * @return 
     */
    public List<Map<String, Object>> jfind(final String sql, final Map<String, ?> paramMap) {
        return jdbcTemplate.queryForList(sql, paramMap);
    }

    /**
     * jdbcTemplate
     * @param paramMap ???,??.
     * @return Mapnull
     */
    public Map<String, Object> jfindUnique(final String sql, final Map<String, ?> paramMap) {
        List<Map<String, Object>> result = jfind(sql, paramMap);
        if (result == null || result.size() == 0) {
            return null;
        }
        return result.get(0);
    }

    /**
     * jdbcTemplate?
     * @param paramMap ?
     * @param requiredType ?
     * @return
     */
    public <X> X jfindUnique(final String sql, final Map<String, ?> paramMap, Class<X> requiredType) {
        List<X> result = jfind(sql, paramMap, requiredType);
        if (result == null || result.size() == 0) {
            return null;
        }
        return result.get(0);
    }

    public long insertWithGeneratedKey(final String sql, final Map<String, ?> paramMap) {

        MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource(paramMap);
        KeyHolder keyHolder = new GeneratedKeyHolder();
        int row = this.jdbcTemplate.update(sql, mapSqlParameterSource, keyHolder);
        if (row > 0)
            return keyHolder.getKey().longValue(); //line 72
        return -1;
    }

    public Transaction begainTransaction() {
        Session currentSession = this.sessionFactory.openSession();
        Transaction tran = currentSession.beginTransaction();
        tran.begin();
        return tran;
    }

    protected Map<String, Object> newParameters() {
        return new HashMap<String, Object>();
    }
}