项目进展以及Dao部分代码的完成过程-阿里云开发者社区

开发者社区> pandamonica> 正文

项目进展以及Dao部分代码的完成过程

简介: 12月20日,之前确定SpringMVC+Spring+Hibernate的方案,前面两天成功利用powerDesigner和phpmyadmin和eclipse下的hibernate tools成功的由uml生成了PO代码,修改了maven依赖中的版本使得tomcat启动时不会认为生成的PO代码有问题。
+关注继续查看

12月20日,之前确定SpringMVC+Spring+Hibernate的方案,前面两天成功利用powerDesigner和phpmyadmin和eclipse下的hibernate tools成功的由uml生成了PO代码,修改了maven依赖中的版本使得tomcat启动时不会认为生成的PO代码有问题。
接下来的工作包括:
1---调通hibernate dao的代码,换句话说利用spring-orm的技术,能够成功通过hibernate去操作之前生成的PO文件,也就是数据库的基本操作;完成Spring和Hibernate的联动。
2---在Dao的基础上写Service和controller,通过最初jsp的方式能够将数据展示在jsp页面上;
3---配置SpringMVC中有关于自定义返回值,让我们的web项目可以采用json来传递数据,从后台到前端;
4---将json传递的数据通过ExtJS显示出来。

2017年12月27日,第一步已经完成。
12月28日第二步完成(事务管理的知识差太多啊)

上述工作就是我们马上要开始的。
本博文,用来描述其中第一部分,Dao代码的形成过程。
之前分析三个其他项目的过程中确认过,Dao代码由于业务无关性,就两个文件,一个interface一个实现它的class。Dao必须实现泛型,主要调用Spring-orm中的方法。
Dao部分两个文件直接copy蒋锋的,做一些必要修改,过程如下:
_
也就是说MyHiberDao.java写完以后,后面所有业务相关的service代码都是基于这一个Dao文件就可以了。
_
创建一个新的class
_
_
_
eclipse中我们写的java文件,各种方法、属性前面的图标,代表的常用意义可以参考这个连接 这里用到的如下图:
http://blog.csdn.net/qq_27292113/article/details/54601641
_
_
下面就开始对照interface中必须实现的方法,开始一个一个的实现,毕竟是借鉴别人的代码,一方面还是要看懂,另一方面真的不想花太多时间,我们首先把一些纯java(也就是spring或者hibernate无关的)代码,列举一下,这部分肯定会用到,主要是字符处理一类的。

1---字符串大小写的处理

public class CommonUtils {
    /**
     * 判断String\List\Object[]是否为空
     * @param v
     * @param trim
     * @return
     */
    public static boolean isEmpty(Object v, boolean trim) {
        if (v == null)
            return true;
        if (v instanceof String) {
            String sv = (String) v;
            return trim ? sv.trim().length() == 0 : sv.length() == 0;
        } else if (v instanceof List<?>) {
            return ((List<?>) v).size() == 0;
        } else if (v instanceof Object[]) {
            return ((Object[]) v).length == 0;
        } else {
            return false;
        }
    }

    public static String underlineToCamelhump(String str) {
        str = str.toLowerCase();
        Matcher matcher = Pattern.compile("_[a-z]").matcher(str);
        StringBuilder builder = new StringBuilder(str);
        for (int i = 0; matcher.find(); i++) {
            builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
        }
        if (Character.isUpperCase(builder.charAt(0))) {
            builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
        }
        return builder.toString();
    }

    public static String firstCharacterUpperCase(String str) {
        if (isEmpty(str))
            return str;
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }

    public static void main(String[] args) {
    
        System.out.println(CommonUtils.firstCharacterUpperCase(CommonUtils.underlineToCamelhump("one_Two_THREE___fOUR+FiVE")));
  
        System.out.println(CommonUtils.underlineToCamelhump("one_Two_THREE___fOUR+FiVE"));
    }
}

我就不客气了,main()方法里面的参数大家都看到了,直接上图,看看console中的运行结果:
_

_
如上图DaoTest.java是一个测试的Dao文件
继续完成Dao文件,写完一部分,打算TestNG看看效果,结果报错了:

十二月 21, 2017 4:50:19 下午 org.springframework.web.context.ContextLoader initWebApplicationContext
严重: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'daoTest' defined in file [D:\OxygenWork\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\RepositoryCheck\WEB-INF\classes\com\tsmi\hibernate\dao\DaoTest.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.

报错的原因百度一下:因为继承了HibernateDaoSupport 相当sessionFactory还没注入到HibernateDaoSupport中,使得这里的this.getHibernateTemplate()=null。

添加代码(一个方法)如下:

@Repository
public class DaoTest extends HibernateDaoSupport implements Dao {

    @Resource
    private SessionFactory sessionFactory;
    
    private Session session;
    
    @PostConstruct
    public void InjectedSessionFactory() {
        //给父类注入sessionFactory
        super.setSessionFactory(sessionFactory);
    }

}

最后直接上代码,基本上copy的蒋锋代码
三个文件,一个interface一个class一个test文件
1---interface

package com.tsmi.hibernate.dao;

import java.io.Serializable;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.orm.hibernate5.HibernateTemplate;

import com.tsmi.hibernate.bean.PageInfo;

public interface Dao {

    public SessionFactory getSessionFactory();

    public Session getCurrentSession();

    public Connection getConnection();

    public Session openSession();

    public Dao openDao();

    public HibernateTemplate getHibernateTemplate();

    public void flush();

    public void clear();

    public void close();

    public Transaction beginTransaction();

    public void commit();

    public void rollback();

    public <T> void refresh(T t);

    public <T> void evict(T t);

    public <T> Serializable save(T t);

    public <T> List<Serializable> bulkSave(List<T> ts);

    public int bulkUpdate(final String queryString, final Object... values);

    public <T> T update(T t);

    public <T> T update(Class<T> clazz, Map<String, Object> data);

    public <T> T update(T t, String... includeFields);

    public <T> T update(T t, boolean ignoredNull, String... includeFields);

    public <T> void delete(T c);

    public int executeUpdate(String hql, Object... params);

    public <T> T saveOrUpdate(T t);

    public <T> T saveOrUpdate(T t, String... includeFields);

    public <T> T saveOrUpdate(T t, boolean ignoredNull, String... includeFields);

    public <T, ID extends Serializable> T findById(Class<T> c, ID id);

    public <ID extends Serializable> Object findById(String entityName, ID id);

    public <T> List<T> findAll(Class<T> t);

    public <T> List<T> findByProperty(Class<T> t, Object... obj);

    public <T> T findByPropertyFirst(Class<T> t, Object... obj);

    public <T> List<T> findByProperty(Class<T> t, T obj);

    public <T> List<T> findByProperty(Class<T> t, Map<String, Object> map);

    public <T> List<T> executeQuery(String hql, Object... params);

    public <T> PageInfo<T> executeQuery(String hql, int start, int limit, Object... params);

    public int selectCount(String hql, Object... params);

    public int selectPageCount(String hql, Object... params);

    public int executeSQLUpdate(String sql, Object... params);

    public List<Map<String, Object>> executeSQLQuery(String sql, Object... params);

    public List<Map<String, Object>> executeSQLQuery(String sql, String[] fields, Object... params);

    public Map<String, Object> executeSQLQueryFirst(String sql, Object... params);

    public Map<String, Object> executeSQLQueryFirst(String sql, String[] fields, Object... params);

    public <T extends Serializable> List<T> executeSQLQuery(String sql, Class<T> c, Object... params);

    public <T extends Serializable> T executeSQLQueryFirst(String sql, Class<T> c, Object... params);

    public PageInfo<Map<String, Object>> executeSQLQueryPage(String sql, int start, int limit, Object... params);

    public PageInfo<Map<String, Object>> executeSQLQueryPage(String sql, int start, int limit, int total,
            Object... params);

    public PageInfo<Map<String, Object>> executeSQLQueryPage(String sql, String[] fields, int start, int limit,
            Object... params);

    public PageInfo<Map<String, Object>> executeSQLQueryPage(String sql, String[] fields, int start, int limit,
            int total, Object... params);

    public <T extends Serializable> PageInfo<T> executeSQLQueryPage(String sql, Class<T> c, int start, int limit,
            Object... params);

    public <T extends Serializable> PageInfo<T> executeSQLQueryPage(String sql, Class<T> c, int start, int limit,
            int total, Object... params);

    public int selectSQLCount(String sql, Object... params);

    public int selectPageSQLCount(String sql, Object... params);

    public <T> Serializable getIdentifierPropertyName(T t);

    public <T> Serializable getIdentifier(T t);

    public <T> ClassMetadata getClassMetadata(T t);
}

2---dao的实现类class

package com.tsmi.hibernate.dao;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.internal.SessionImpl;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.tsmi.hibernate.bean.PageInfo;
import com.tsmi.hibernate.utils.CommonUtils;
import com.tsmi.hibernate.utils.DataObjectUtils;

/**
 * 唯一的Dao文件
 * 对 Hibernate 和  Spring-orm 的封装
 * @author Charlie
 *
 */
@Repository
@SuppressWarnings({"unchecked","deprecation"})
public class MyHiberDao extends HibernateDaoSupport implements Dao {
    
    @Resource
    private SessionFactory sessionFactory;
    
    private Session session;
    
    /**
     * 初始化父类SessionFactory
     */
    @PostConstruct
    public void InjectedSessionFactory() {
        super.setSessionFactory(sessionFactory);
    }
    
    public MyHiberDao() {
        
    }
    
    public MyHiberDao(SessionFactory sessionFactory) {
        this.sessionFactory=sessionFactory;
        super.setSessionFactory(sessionFactory);
    }
    
    public void setSession(Session session) {
        this.session = session;    
    }
    
    /**
     * pure test method
     */
    public Session getSession() {
        return this.session;
    }
    
    /* 
     * from Hibernate
     * session's getter() method
     * Obtains the current session
     */
    public Session getCurrentSession() {
        return session == null ? sessionFactory.getCurrentSession():session;
    }

    /* 
     * from Hibernate
     * barely used
     * connection
     */
    public Connection getConnection() {
        SessionImpl session = (SessionImpl) getCurrentSession();
        return session.getJdbcCoordinator().getLogicalConnection().getPhysicalConnection();
    }

    /* 
     * from Hibernate
     * 
     * create database connection and open a session on it
     */
    public Session openSession() {
        return sessionFactory.openSession();
    }

    public Dao openDao() {
        MyHiberDao dao = new MyHiberDao();
        dao.setSessionFactory(sessionFactory);
        dao.setSession(sessionFactory.openSession());
        return dao;
    }

    /* 
     * from Hibernate
     * Force this session to flush. Must be called at the end of a unit of work, 
     * before committing the transaction and closing the session (depending on Session.setFlushMode(FlushMode), 
     * EntityTransaction.commit() calls this method).
     */
    public void flush() {
        getCurrentSession().flush();
    }
    
    /* 
     * from Hibernate
     * Completely clear the session. Evict all loaded instances and cancel all pending saves, updates and deletions. 
     * Do not close open iterators or instances of ScrollableResults.
     */
    public void clear() {
        getCurrentSession().clear();
    }

    /* 
     * from Hibernate
     * End the session by releasing the JDBC connection and cleaning up.
     */
    public void close() {
        getCurrentSession().close();
    }

    /* 
     * from Hibernate
     * session Transaction
     */
    public Transaction beginTransaction() {
        
        // Get the Transaction instance associated with this session.
        Transaction transaction = getCurrentSession().getTransaction();
        if(transaction == null||!transaction.isActive()) {
            // Begin a unit of work and return the associated Transaction object.
            transaction = getCurrentSession().beginTransaction();
        }
        return transaction;
    }

    /* 
     * from Hibernate
     */
    public void commit() {
        beginTransaction().commit();
    }

    /* 
     * from Hibernate
     */
    public void rollback() {
        beginTransaction().rollback();
    }

    

    /* 
     * from Spring-orm
     * getHibernateTemplate()--HibernateDaoSupport--Spring-orm
     * Re-read the state of the given persistent instance.
     * HibernateTemplate--session--refresh()
     * refresh() 数据库-->session
     */
    public <T> void refresh(T t) {
        getHibernateTemplate().refresh(t);
    }

    /* 
     * from Spring-orm
     * Remove the given object from the Session cache.
     * 从session中移除指定的PO
     */
    public <T> void evict(T t) {
        getHibernateTemplate().evict(t);
    }

    /* 
     * from Spring-orm
     * Persist the given transient instance.
     * 临时对象-->持久对象
     */
    public <T> Serializable save(T t) {
        //save() method is just about to persist the object,while it is not officially done
        Serializable id = getHibernateTemplate().save(t);
        //officially done
        flush();
        return id;
    }


    /* 
     * from Spring-orm
     * bulk n 大量
     * 批量save()
     */
    public <T> List<Serializable> bulkSave(List<T> ts) {
        List<Serializable> list = new ArrayList<Serializable>();
        //最好循环中,每隔20个clear一下
        for(T t:ts) {
            list.add(save(t));
        }
        flush();
        
        return list;
    }

    /* 
     * from Spring-orm
     * 
     * Update/delete all objects according to the given query, 
     * binding a number of values to "?" parameters in the query string.
     * 批量更新
     */
    public int bulkUpdate(String queryString, Object... values) {
        int count = getHibernateTemplate().bulkUpdate(queryString, values);
        flush();
        return count;
    }
    
    /* 
     * from Spring-orm
     * 获取
     * Spring-orm  HibernateTemplate.get()  Session.get()
     * get()
     * return the persistent instance of the given entity class with the given identifier
     */
    public <T, ID extends Serializable> T findById(Class<T> c, ID id) {
        return getHibernateTemplate().get(c, id);
    }

    /* 
     * from Spring-orm
     * get()
     * return the persistent instance of the given entity class with the given identifier
     */
    public <ID extends Serializable> Object findById(String entityName, ID id) {
        return getHibernateTemplate().get(entityName, id);
    }
    

    
    /* 
     * from Spring-orm
     * 游离对象-->持久对象
     */
    public <T> T update(T t) {
        return update(t,false);
    }
    
    /* 
     * String... 表示不确定参数有几个;
     * 
     */
    public <T> T update(T t, String... includeFields) {
        return update(t,true,includeFields);
    }
    
    
    /* 
     * from Spring-orm
     */
    public <T> T update(T t, boolean ignoredNull, String... includeFields) {
    
        if(ignoredNull) {
            try {
                //Serializable id = getIdentifier(t);
                //T object = (T) findById(t.getClass(),id);
                
                
            }catch(Exception e) {
                //throw new DaoException(e);
            }
            
        }else {
            
            getHibernateTemplate().update(t);
        }
    
        flush();
        return t;
        
    }


    public <T> T update(Class<T> clazz, Map<String, Object> data) {
        // TODO Auto-generated method stub
        return null;
    }

    /* 
     * from Spring-orm
     */
    public <T> void delete(T t) {
        Serializable id = getIdentifier(t);
        getHibernateTemplate().delete(findById(t.getClass(),id));
        flush();
    }

    
    
    /**
     * from Hibernate
     * private
     * HQL
     * 获取HQL的Query
     * 
     */
    private Query getQuery(String hql,Object[] params1,Map<String,Object> params2) {
        
        Query query = getCurrentSession().createQuery(hql);
        
        if(params1 !=null) {
            for(int i = 0;i<params1.length;i++) {
                query.setParameter(i, params1[i]);
            }
        }
        if(params2 !=null) {
            for(Map.Entry map : params2.entrySet()) {
                query.setParameter((String)map.getKey(),map.getValue());
            }
        }
        
        return query;
    }
    
    private int selectCount(String hql, Object[] params1, Map<String, Object> params2) {
        Query query = getQuery(hql, params1, params2);
        Object result = query.getSingleResult();
        if (result instanceof Number) {
            return ((Number) result).intValue();
        } else {
            return Integer.valueOf(result.toString());
        }
    }
    
    /* 
     * HQL
     * 获取记录数
     */
    public int selectCount(String hql, Object... params) {
        return selectCount(hql,params,null);
    }

    /* 
     * from Hibernate
     * HQL
     * 普通批量查询数据
     * Query
     */
    public <T> List<T> executeQuery(String hql, Object... params) {
        return getQuery(hql,params,null).getResultList();
    }
    
    /* 
     * from Hibernate
     * HQL
     * 分页批量查询数据
     * Query
     */
    public <T> PageInfo<T> executeQuery(String hql, int start, int limit, Object... params) {
        return executeQuery(hql,params,null,start,limit);
    }
    
    /* 
     * from Hibernate
     * private 方法 
     */
    private <T> PageInfo<T> executeQuery(String hql,Object[] params1,Map<String,Object> params2,int start,int limit){
        
        Query<T> query = getQuery(hql,params1,params2);
        ScrollableResults sr = query.scroll();
        sr.last();
        int totalRows = sr.getRowNumber();
        query.setFirstResult(start);
        query.setMaxResults(limit);
        return new PageInfo<T>(start,limit,totalRows,query.getResultList());
        
    }
    
    /*
     *  批量查询三种方式
     *  1)循环使用session的save(); 2)hqlQuery; 3)sqlQuery;
     * /
    
    /* 
     * HQL
     * 批量修改数据
     *
     * Hibernate+javax
     * HQL Query
     * Hibernate Query
     * javax executeUpdate()
     * Execute the update or delete statement
     */
    public int executeUpdate(String hql, Object... params) {
        int count = getQuery(hql,params,null).executeUpdate();
        flush();
        return count;
    }

    private int selectPageCount(String hql, Object[] params1, Map<String, Object> params2) {
        String totalsql = "select count(1) " + hql.substring(hql.indexOf(" from "));
        int orderbyIndex = totalsql.lastIndexOf(" order ");
        if (orderbyIndex != -1)
            totalsql = totalsql.substring(0, orderbyIndex);
        return selectCount(totalsql, params1, params2);
    }
    
    public int selectPageCount(String hql, Object... params) {
        return selectPageCount(hql, params, null);
    }

    
    /* 
     * from Spring-orm
     * 临时对象-->持久化对象
     * 游离对象-->持久化对象
     */
    public <T> T saveOrUpdate(T t) {
        return saveOrUpdate(t,true);
    }

    public <T> T saveOrUpdate(T t, String... includeFields) {
        return saveOrUpdate(t,true,includeFields);
    }

    public <T> T saveOrUpdate(T t, boolean ignoredNull, String... includeFields) {
        Serializable id = getIdentifier(t);
        if(CommonUtils.isEmpty(id)) {
            save(t);
        }else {
            t = update(t,ignoredNull,includeFields);
        }
        flush();
        return t;
    }

    /* 
     * Spring-orm
     * return all persistent instance of the given entity class
     * 本来PO没在session,你findAll(),全都找出来了;
     */
    public <T> List<T> findAll(Class<T> t) {
        return getHibernateTemplate().loadAll(t);
    }

    /* 
     * Hibernate
     * executeQuery()
     * 
     */
    public <T> List<T> findByProperty(Class<T> t, Object... obj) {
        if(obj != null && obj.length % 2 != 0) {
            System.out.println("error");
            return null;    
        }
        StringBuffer hql = new StringBuffer("from " + t.getName() + " ");
        if(!CommonUtils.isEmpty(obj)) {
            List<Object> params = new ArrayList<Object>();
            for(int i =0; i < obj.length; i+=2) {
                hql.append(i==0 ? " where " : " and ");
                String key = String.valueOf(obj[i]);
                Object value = obj[i + 1];
                if(value == null) {
                    hql.append(key + " is null ");
                }else {
                    hql.append(key + " = ? ");
                    params.add(obj[i + 1]);
                }
            }
            return executeQuery(hql.toString(),params.toArray());
        }
        return executeQuery(hql.toString());
    }
    
    /* 
     * Hibernate
     * executeQuery()  
     * Query getResultList()
     */
    public <T> List<T> findByProperty(Class<T> t, Map<String, Object> map) {
        StringBuffer hql = new StringBuffer("from " + t.getName() + " ");
        if(map.size() > 0)
          hql.append(" where ");
        
        List<Object> params = new ArrayList<Object>();
        for(String key : map.keySet()) {
            Object value = map.get(key);
            if(params.size() == 0) {
                hql.append(" where ");
            }
            if(value == null) {
                hql.append(key + " is null ");
            }else {
                hql.append(key + " = ? ");
                params.add(value);
            }
        }
        return executeQuery(hql.toString(),params);
    }


    public <T> List<T> findByProperty(Class<T> t, T obj) {
        StringBuffer hql = new StringBuffer("from " + t.getName() + " ");
        Field[] fields = obj.getClass().getDeclaredFields();
        List<Object> params = new ArrayList<Object>();
        for(int i = 0;i < fields.length; i++) {
            try {
                Field field = fields[i];
                field.setAccessible(true);
                Object value = fields[i].get(obj);
                if(!CommonUtils.isEmpty(value)) {
                    continue;
                }
                if(params.size() == 0) {
                    hql.append(" where ");
                }
                hql.append(field.getName() + " = ? ");
                params.add(value);
                
            }catch(Exception e) {
                e.printStackTrace();
            }    
        }
        return executeQuery(hql.toString());
    }

    /* 
     * obtain the first PO
     */
    public <T> T findByPropertyFirst(Class<T> t, Object... obj) {
        List<T> list = findByProperty(t,obj);
        return list.size() == 0 ? null : list.get(0);
    }
    
    /*
     * private方法
     * SQL批量查询
     * 
     */
    private <T> NativeQuery getSQLQuery(String sql, Class<T> c, Object[] params1, Map<String, Object> params2) {
        
        NativeQueryImpl query = (NativeQueryImpl) getCurrentSession().createNativeQuery(sql);
        Map<String,Object> param = DataObjectUtils.getSqlParameter();
        if (param != null) {
            for (String key : param.keySet()) {
                if (sql.indexOf(":" + key) != -1)
                    query.setParameter(key, param.get(key));
            }
        }
        if (c == null) {
        
        } else if (c == Map.class) {
            query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        } else {
            query.setResultTransformer(Transformers.aliasToBean(c));
        }
        query.setZeroBasedParametersIndex(true);
        if (params1 != null) {
            for (int i = 0; i < params1.length; i++) {
                query.setParameter(i, params1[i]);
            }
        }
        if (params2 != null) {
            for (Map.Entry map : params2.entrySet()) {
                query.setParameter((String) map.getKey(), map.getValue());
            }
        }
        return query;
    }
    
    /* (non-Javadoc)
     * @see com.tsmi.hibernate.dao.Dao#executeSQLQuery(java.lang.String, java.lang.Object[])
     */
    public List<Map<String, Object>> executeSQLQuery(String sql, Object... params) {
        NativeQuery query = getSQLQuery(sql, Map.class, params, null);
        return query.getResultList();
    }

    public List<Map<String, Object>> executeSQLQuery(String sql, String[] fields, Object... params) {
        NativeQuery query = getSQLQuery(sql, null, params, null);
        return arrayToMap(fields, query.getResultList());
    }
    
    public <T extends Serializable> List<T> executeSQLQuery(String sql, Class<T> c, Object... params) {
        NativeQuery query = getSQLQuery(sql, Map.class, params, null);
        return convertMapToList(c, query.getResultList());
    }

    private List<Map<String, Object>> arrayToMap(String[] fields, List<Object[]> resultList) {
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < resultList.size(); i++) {
            Object obj = resultList.get(i);
            Map<String, Object> dataMap = new HashMap<String, Object>();
            if (obj instanceof Object[]) {
                Object[] datas = (Object[]) obj;
                for (int j = 0; j < fields.length; j++) {
                    dataMap.put(fields[j], j < datas.length ? datas[j] : null);
                }
            } else {
                dataMap.put(fields[0], obj);
            }
            dataList.add(dataMap);
        }
        return dataList;
    }

    public int executeSQLUpdate(String sql, Object... params) {
        int count = getSQLQuery(sql, Map.class, params, null).executeUpdate();
        flush();
        return count;
    }

    public Map<String, Object> executeSQLQueryFirst(String sql, Object... params) {
        List<Map<String, Object>> list = executeSQLQuery(sql, params);
        return list.size() == 0 ? null : list.get(0);
    }

    public Map<String, Object> executeSQLQueryFirst(String sql, String[] fields, Object... params) {
        NativeQuery query = getSQLQuery(sql, null, params, null);
        List<Map<String, Object>> list = arrayToMap(fields, query.getResultList());
        return list.size() == 0 ? null : list.get(0);
    }

    public <T extends Serializable> T executeSQLQueryFirst(String sql, Class<T> c, Object... params) {
        List<T> list = executeSQLQuery(sql, c, params);
        return list.size() == 0 ? null : list.get(0);
    }
    
    public static <T> T convertMapToBean(Class<T> type, Map<String, Object> map)
            throws IntrospectionException, IllegalAccessException, InstantiationException, InvocationTargetException {
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        T obj = type.newInstance();

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (String key : map.keySet()) {
            String beanfieldlike = key.replaceAll("_", "").toLowerCase();
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                if (propertyName.toLowerCase().equals(beanfieldlike)) {
                    Object value = map.get(key);
                    Object[] args = new Object[1];
                    args[0] = value;
                    if (descriptor.getPropertyType() == Boolean.class) {
                        if (value != null && value.getClass() != Boolean.class) {
                            Boolean b = Boolean.valueOf(value.toString());
                            if (value instanceof Number)
                                b = Integer.parseInt(value.toString()) != 0;
                            args[0] = b;
                        }
                    }
                    if (descriptor.getPropertyType() == BigInteger.class) {
                        if (value != null && value.getClass() != BigInteger.class) {
                            BigInteger b = new BigInteger(value.toString());
                            args[0] = b;
                        }
                    }
                    if (descriptor.getPropertyType() == Integer.class) {
                        if (value != null) {
                            Integer b = Integer.parseInt(value.toString());
                            args[0] = b;
                        }
                    }
                    descriptor.getWriteMethod().invoke(obj, args);
                }
            }
        }
        return obj;
    }
    
    public static <T> List<T> convertMapToList(Class<T> type, List<Map<String, Object>> maps) {
        List<T> result = new ArrayList<T>();
        for (Map<String, Object> map : maps) {
            try {
                result.add(convertMapToBean(type, map));
            } catch (IllegalAccessException | InstantiationException | InvocationTargetException| IntrospectionException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    
    
    /**
     * 这个方法调用了selectPageSQLCount,而那个方法是有问题的
     * total参数非0情况下,可以正常使用
     * @param sql
     * @param c
     * @param fields
     * @param params1
     * @param params2
     * @param start
     * @param limit
     * @param total
     * @return
     */
    private <T> PageInfo<T> executeSQLQueryPage(String sql, Class<T> c, String[] fields, Object[] params1,
            Map<String, Object> params2, int start, int limit, int total) {
        Query<T> query = getSQLQuery(sql, c, params1, params2);
        int totalRows = total == 0 ? selectPageSQLCount(sql, params1, params2) : total;
        query.setFirstResult(start);
        query.setMaxResults(limit);
        List resultList = query.getResultList();
        PageInfo info = new PageInfo<T>(start, limit, totalRows, null);
        if (c == null && !CommonUtils.isEmpty(fields)) {
            info.setData(arrayToMap(fields, resultList));
        } else {
            info.setData(resultList);
        }
        return info;
    }
    

    public PageInfo<Map<String, Object>> executeSQLQueryPage(String sql, int start, int limit, Object... params) {
        // 未实现
        return null;
    }

    public PageInfo<Map<String, Object>> executeSQLQueryPage(String sql, int start, int limit, int total,
            Object... params) {
        // 未实现
        return null;
    }

    /*
     * 四个executeSQLQueryPage(),都是调用private的executeSQLQueryPage()方法
     * */
    
    //total=0
    public PageInfo<Map<String, Object>> executeSQLQueryPage(String sql, String[] fields, int start, int limit,
            Object... params) {
        return executeSQLQueryPage(sql, null, fields, params, null, start, limit, 0);
    }

    //total!=0
    public PageInfo<Map<String, Object>> executeSQLQueryPage(String sql, String[] fields, int start, int limit,
            int total, Object... params) {

        return executeSQLQueryPage(sql, null, fields, params, null, start, limit, total);
    }

    //total=0
    public <T extends Serializable> PageInfo<T> executeSQLQueryPage(String sql, Class<T> c, int start, int limit,
            Object... params) {
        return executeSQLQueryPage(sql, c, null, params, null, start, limit, 0);
    }

    //total!=0
    public <T extends Serializable> PageInfo<T> executeSQLQueryPage(String sql, Class<T> c, int start, int limit,
            int total, Object... params) {
        return executeSQLQueryPage(sql, c, null, params, null, start, limit, total);
    }
    
    
    private int selectSQLCount(String sql, Object[] params1, Map<String, Object> params2) {
        Query query = getCurrentSession().createNativeQuery(sql);

        Map<String, Object> param = DataObjectUtils.getSqlParameter();
        if (param != null) {
            for (String key : param.keySet()) {
                if (sql.indexOf(":" + key) != -1)
                    query.setParameter(key, param.get(key));
            }
        }
        if (params1 != null) {
            for (int i = 0; i < params1.length; i++) {
                query.setParameter(i, params1[i]);
            }
        }
        if (params2 != null) {
            for (Map.Entry map : params2.entrySet()) {
                query.setParameter((String) map.getKey(), map.getValue());
            }
        }
        Object result = query.getSingleResult();
        if (result instanceof Number) {
            return ((Number) result).intValue();
        } else {
            return Integer.valueOf(result.toString());
        }
    }


    /* 
     * 调用private方法
     */
    public int selectSQLCount(String sql, Object... params) {
        return selectSQLCount(sql, params, null);
    }

    /* 
     * WARNING!!!
     * this method's function body is wrong;
     * The reason that author did not debug this method is that this method is never used;
     * 
     */
    public int selectPageSQLCount(String sql, Object... params) {
        return selectPageSQLCount(sql, params, null);
    }

    public <T> Serializable getIdentifierPropertyName(T t) {
        ClassMetadata cm = getClassMetadata(t);
        return cm.getIdentifierPropertyName();
    }

    /* 
     * get the identifier of an instance
     */
    public <T> Serializable getIdentifier(T t) {
        SessionImpl session = (SessionImpl)getCurrentSession();
        EntityPersister ep = session.getEntityPersister(t.getClass().getName(), t);
        return ep.getIdentifier(t, session);
    }

    public <T> ClassMetadata getClassMetadata(T t) {
        SessionImpl session = (SessionImpl) getCurrentSession();
        Class c = t instanceof Class ? (Class<? extends Object>) t : t.getClass();
        EntityPersister ep = session.getEntityPersister(c.getName(), t);
        return ep.getClassMetadata();
    }
    
    /**
     * test
     */
    public String testF() {
        
        return "testF()";
    }

}

3---testNG测试类

package com.tsmi.hibernate.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.internal.SessionImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.testng.annotations.Test;

import com.tsmi.hibernate.bean.PageInfo;
import com.tsmi.hibernate.entity.Mara;
import com.tsmi.hibernate.entity.UserDep;

@ContextConfiguration("classpath*:/mysqlHibernateContext.xml")
public class MyHiberDaoTest extends AbstractTransactionalTestNGSpringContextTests{
    
    private MyHiberDao mhd;
    
    public MyHiberDao getMhd() {
        return mhd;
    }

    @Autowired
    public void setMhd(MyHiberDao mhd) {
        this.mhd = mhd;
    }
    
    
  @Rollback(false)
  @Test
  public void f() {
      
      //just test a String
      System.out.println("------first------");
      //test a empty function which return a String
      System.out.println(mhd.testF());
      //test basic connection info
      try {
          System.out.println("数据库已知的用户"+mhd.getConnection().getMetaData().getUserName());
          System.out.println("数据库的系统函数的逗号分隔列表: "+ mhd.getConnection().getMetaData().getSystemFunctions());      
          System.out.println("数据库的时间和日期函数的逗号分隔列表: "+ mhd.getConnection().getMetaData().getTimeDateFunctions());      
          System.out.println("数据库的字符串函数的逗号分隔列表:  "+ mhd.getConnection().getMetaData().getStringFunctions());      
          System.out.println("数据库供应商用于 'schema' 的首选术语: "+ mhd.getConnection().getMetaData().getSchemaTerm());      
          System.out.println("数据库URL:  " + mhd.getConnection().getMetaData().getURL());      
          System.out.println("是否允许只读:" + mhd.getConnection().getMetaData().isReadOnly());      
          System.out.println("数据库的产品名称:" + mhd.getConnection().getMetaData().getDatabaseProductName());      
          System.out.println("数据库的版本:" + mhd.getConnection().getMetaData().getDatabaseProductVersion());      
          System.out.println("驱动程序的名称:" + mhd.getConnection().getMetaData().getDriverName());      
          System.out.println("驱动程序的版本:" + mhd.getConnection().getMetaData().getDriverVersion());
    
      }catch(SQLException e) {
          e.printStackTrace();
      }
      
      //test Hibernate's Hibernate.session 
      //SessionImpl session = (SessionImpl) mhd.getCurrentSession();
//      //Check if the session is still open.
//      System.out.println("session.isOpen()  "+session.isOpen());
//      System.out.println("session.isAutoCloseSessionEnabled()  "+session.isAutoCloseSessionEnabled());
//      //Will entities and proxies that are loaded into this session be made read-only by default? To determine the read-only/modifiable setting for a particular entity or proxy:
//      System.out.println("session.isDefaultReadOnly()  "+session.isDefaultReadOnly());
//      //Does this session contain any changes which must be synchronized with the database? In other words, would any DML operations be executed if we flushed this session?
//      System.out.println("session.isDirty()  "+session.isDirty());
  
      /*
       * Hibernate 本质是对JDBC的封装
       * Hiberante 的基本接口
       * Configuration  配置Hibernate
       * SessionFactory 初始化Hibernate
       * Session 
       * Transaction    事务
       * Query          查询
       * 
       * Configuration--SessionFactory--Session--Transaction--Query
       * 
       * 
       * 
       * Session session = factory.openSession();
       * Transaction tx;
       * try{
       *    tx = session.beginTransaction();
       *    
       *    

       *    tx.commit();
       * }catch(RuntimeException e){
       *    if(tx!=null) tx.rollback();
       *    throw e;
       * }finally{
       *    session.close();
       * }
       * 
       * */
      
/*     
      //测试flush()方法,保存临时对象
      UserDep ud2 = new UserDep();
      ud2.setKostl("2100");
      ud2.setEname("总务课");
      ud2.setLevel("1");
      mhd.flush();
      mhd.close();
      //result : fail

      */
      
/*     
      //测试save(),保存临时对象
      UserDep ud2 = new UserDep();
      ud2.setKostl("2109");
      ud2.setEname("技术的课");
      ud2.setLevel("1");
      mhd.save(ud2);
      mhd.close();
      //result : bingo
      
*/
      
/*     
     
      * 下面共同测试了findById()和clear()和flush()方法
      * 哎,什么也没测出来,放弃了
      * 
      UserDep ud3 = mhd.findById(UserDep.class, "1501");
      System.out.println(ud3.getEname());
      //mhd.evict(ud3);
      mhd.clear();
      mhd.flush();
      // mhd.refresh(ud3);
      System.out.println("after clear()   "+ud3.getEname());
*/
      
/*      
      //测试 update()/evict()/flush()
      UserDep ud4 = mhd.findById(UserDep.class, "2109");
      //remove ud4 from session
      mhd.evict(ud4);
      ud4.setEname("P板检测");
      //now ud4 is a detached object
      
      //update() method can turn a detached object into a persistent object
      mhd.update(ud4);
      //flush() method can only deal with persistent object;
      //mhd.flush();
      System.out.println(ud4.getEname());
     //result : update bingo / flush() fail
      
      */
      
/*      
      //测试delete()
      UserDep ud5 = mhd.findById(UserDep.class, "2109");
      mhd.delete(ud5);
      // result : bingo
*/
      
      /* getQuery()是MyHiberDao中的private的自定义方法
       * getQuery()执行HQL类Query的查询
       */
     
/*
        // 测试hql查询(不带参数)
        String hql = "from UserDep";
        List<UserDep> rls = mhd.executeQuery(hql, new Object[] {});
        System.out.println(rls.size());
        for (int i = 1; i < rls.size(); i++) {

            System.out.println(" 成本中心:" + rls.get(i).getKostl());
            System.out.println(" 部门名称: " + rls.get(i).getEname());

        }
        rls.clear();
*/
      
/*
        String hql2 = "from Mara as c where c.ename=?";
        String sTemp = "端子";
        List<Mara> rls2 = mhd.executeQuery(hql2, new Object[] { sTemp });

        System.out.println(rls2.size());
        for (int i = 0; i < rls2.size(); i++) {
            System.out.println(" 物料编号: " + rls2.get(i).getMatnr());
            System.out.println(" 物料名称: " + rls2.get(i).getEname());
        }
        rls2.clear();
 */
      
/*
        // 测试返回值类型为PageInfo 的executeQuery(),分页显示
        String hql2 = "from Mara as c where c.ename=?";
        String sTemp = "端子";
        
        PageInfo<Mara> pm1 = mhd.executeQuery(hql2, 10, 20, new Object[] { sTemp });
        List<Mara> lm1 = pm1.getData();
        System.out.println(lm1.size());
        for (int i = 0; i < lm1.size(); i++) {
            System.out.println(" 物料编号: " + lm1.get(i).getMatnr());
            System.out.println(" 物料名称: " + lm1.get(i).getEname());
        }
        lm1.clear();
*/
      
/*      
         //测试executeUpdate() 带有参数更新
         //String hql2 =  "update UserDep c set c.ename =? , c.level=? where c.level=?"; 
         String hql2 =  "update UserDep c set c.ename =?  where c.level=?"; 
         mhd.executeUpdate(hql2, new Object[] {"火箭军","1"});
         
*/
      
/*        
      //测试findAll()
         
      String hql2 = "from Mara as c where c.ename=?";
      String sTemp = "端子";
      List<Mara> rls2 =  mhd.executeQuery(hql2, new Object[] {sTemp});
      //清空session
      mhd.clear();
      //findAll()
      List<Mara> rls3 = mhd.findAll(Mara.class);
      
      System.out.println(rls3.size());
      for (int i = 0;i < rls3.size();i++) {
          System.out.println(" 物料编号: "+rls3.get(i).getMatnr());
          System.out.println(" 物料名称: "+rls3.get(i).getEname());
      }
      System.out.println(rls3.size());
      mhd.clear();
      mhd.close();
      //result : get all the data from db
*/
      
      
/*      
      //测试findByProperty()
      
      List<Mara> rls3 = mhd.findByProperty(Mara.class, new Object[] {"ename","端子","matnr","VH-T"});
      for (int i = 0;i < rls3.size();i++) {
          System.out.println(" 物料编号: "+rls3.get(i).getMatnr());
          System.out.println(" 物料名称: "+rls3.get(i).getEname());
      }
      System.out.println(rls3.size());
      
*/
      
/*      
      //测试selectCount()
      String hql2 = "select count(1) from Mara as c where c.ename=?";
      String sTemp = "端子";
      System.out.println(mhd.selectCount(hql2, new Object[] {sTemp}));
*/  
  }

}

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
【Elastic Engineering】Elasticsearch 中的一些重要概念: cluster, node, index, document, shards 及 replica
Elasticsearch 中的一些重要概念: cluster, node, index, document, shards 及 replica
2 0
【Elastic Engineering】Elasticsearch 中的一些重要概念: cluster, node, index, document, shards 及 replica
Elasticsearch 中的一些重要概念: cluster, node, index, document, shards 及 replica
6 0
【Elastic Engineering】Elasticsearch 简介
Elasticsearch 是一个非常强大的搜索引擎。
4 0
安卓平板体验Java开发,还能白嫖一年阿里无影云!真香
阿里无影云早有耳闻,前两天看朋友发体验照片,可能是程序员天生爱折腾的特性又发挥作用了,自己也没能忍住,赶快下载体验了一把,没想到“很香”。我体验了浏览器端、Windows 客户端和安卓平板端,下面就来聊聊使用的过程和使用体验。内含一年免费无影云的白嫖方法,千万别错过哦~
22 0
阿里巴巴数据库分库分表的实践(5)
阿里巴巴数据库分库分表的实践(5)
4 0
飞天加速计划-服务器使用经历
自我介绍,阿里云服务器使用体验,总结收获,个人作品链接。
14 0
用阿里云飞天计划提供的CES服务器为高中生活搭建“故事簿”网页
一名刚踏入大学的大一本科生利用阿里云提供的CES服务器为高中“故事簿”搭建网页
15 0
使用阿里云ECS搭建个人网站
学习在ECS上如何搭建个人网站
23 0
阿里云飞天加速计划
阿里云服务器是一个非常好的学习平台,我们定会用来提升自身的专业能力。
11 0
+关注
159
文章
3
问答
文章排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载