Java tutorial
/** * Copyright (c) 2005-2009 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: SimpleHibernateDao.java 762 2009-12-27 14:46:36Z calvinxiu $ */ package com.thinkmore.framework.orm.hibernate; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.Date; import java.util.List; import java.util.Map; import org.hibernate.Criteria; import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.metadata.ClassMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate4.SessionFactoryUtils; import org.springframework.util.Assert; import com.thinkmore.framework.utils.ReflectionUtils; /** * ?HibernateAPIDAO. * * ?Service,?DAO?. * ?Spring2.5Petlinc?,?HibernateTemplate,HibernateAPI. * * @param <T> DAO? * @param <PK> * * @author calvin */ @SuppressWarnings("unchecked") public class SimpleHibernateDao<T, PK extends Serializable> { protected Logger logger = LoggerFactory.getLogger(getClass()); protected SessionFactory sessionFactory; protected Class<T> entityClass; /** * Dao?. * ??Class. * eg. * public class UserDao extends SimpleHibernateDao<User, Long> */ public SimpleHibernateDao() { this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass()); } /** * ?Dao, ServiceSimpleHibernateDao. * Class. * eg. * SimpleHibernateDao<User, Long> userDao = new SimpleHibernateDao<User, Long>(sessionFactory, User.class); */ public SimpleHibernateDao(final SessionFactory sessionFactory, final Class<T> entityClass) { this.sessionFactory = sessionFactory; this.entityClass = entityClass; } /** * ?sessionFactory. */ public SessionFactory getSessionFactory() { return sessionFactory; } /** * @AutowiredSessionFactory,SesionFactoryOverride. */ @Autowired public void setSessionFactory(final SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * ??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); } /** * id?. */ public T get(final PK id) { Assert.notNull(id, "id?"); return (T) getSession().load(entityClass, id); } /** * ?. */ public List<T> getAll() { return find(); } /** * ?,??. */ public List<T> getAll(String orderBy, boolean isAsc) { Criteria c = createCriteria(); if (isAsc) { c.addOrder(Order.asc(orderBy)); } else { c.addOrder(Order.desc(orderBy)); } return c.list(); } /** * ,??. */ public List<T> findBy(final String propertyName, final Object value) { Assert.hasText(propertyName, "propertyName?"); Criterion criterion = Restrictions.eq(propertyName, value); return find(criterion); } /** * ,??. */ public T findUniqueBy(final String propertyName, final Object value) { Assert.hasText(propertyName, "propertyName?"); Criterion criterion = Restrictions.eq(propertyName, value); return (T) createCriteria(criterion).uniqueResult(); } /** * id?. */ public List<T> findByIds(List<PK> ids) { return find(Restrictions.in(getIdName(), ids)); } /** * HQL. * * @param values ????,?. */ public <X> List<X> find(final String hql, final Object... values) { return createQuery(hql, values).list(); } /** * 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 Object... values) { return (X) createQuery(hql, values).uniqueResult(); } /** * HQL. * * @param values ???,??. */ public <X> X findUnique(final String hql, final Map<String, ?> values) { return (X) createQuery(hql, values).uniqueResult(); } /** * HQL?/?. */ public int batchExecute(final String hql, final Object... values) { return createQuery(hql, values).executeUpdate(); } /** * HQL?/?. * @return . */ public int batchExecute(final String hql, final Map<String, ?> values) { return createQuery(hql, values).executeUpdate(); } /** * ?HQL?Query. * * ?find()T,?T. * * @param values ????,?. */ public Query createQuery(final String queryString, final Object... values) { Assert.hasText(queryString, "queryString?"); Query query = getSession().createQuery(queryString); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query; } /** * ?HQL?Query. * * @param values ???,??. */ public Query createQuery(final String queryString, final Map<String, ?> values) { Assert.hasText(queryString, "queryString?"); Query query = getSession().createQuery(queryString); if (values != null) { query.setProperties(values); } return query; } /** * Criteria. * * @param criterions ???Criterion. */ public List<T> find(final Criterion... criterions) { return createCriteria(criterions).list(); } /** * Criteria. * * @param criterions ???Criterion. */ public T findUnique(final Criterion... criterions) { return (T) createCriteria(criterions).uniqueResult(); } /** * ?Criterion?Criteria. * * ?find()T,?T. * * @param criterions ???Criterion. */ public Criteria createCriteria(final Criterion... criterions) { Criteria criteria = getSession().createCriteria(entityClass); for (Criterion c : criterions) { criteria.add(c); } return criteria; } /** * ?. * load()Proxy, View???. * ??entity,????. * ??,?,: * Hibernate.initialize(user.getRoles())?User??. * Hibernate.initialize(user.getDescription())?UserDescription. */ public void initEntity(T entity) { Hibernate.initialize(entity); } /** * @see #initEntity(Object) */ public void initEntity(List<T> entityList) { for (T entity : entityList) { Hibernate.initialize(entity); } } /** * Querydistinct transformer. */ public Query distinct(Query query) { query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return query; } /** * Criteriadistinct transformer. */ public Criteria distinct(Criteria criteria) { criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return criteria; } /** * ???. */ public String getIdName() { ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass); return meta.getIdentifierPropertyName(); } /** * ? * @param list sql? */ public void executeBatch(final List<String> list) { Connection conn = null; Statement st = null; try { conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection(); conn.setAutoCommit(false); // ?? st = conn.createStatement(); for (int i = 1, j = list.size(); i < j; i++) { String sql = list.get(i); st.addBatch(sql); if (i % 240 == 0) {//?240?sql??? st.executeBatch(); conn.commit(); st.clearBatch(); } else if (i % j == 0) {//?? st.executeBatch(); conn.commit(); st.clearBatch(); } } } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { closeAll(st, conn); } } /** * ? * @param list sql? */ public void executeBatchByPrepare(String sql, final List<String> list) { Connection conn = null; PreparedStatement st = null; try { conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection(); conn.setAutoCommit(false); // ?? st = conn.prepareStatement(sql); for (int i = 1, j = list.size(); i < j; i++) { Object objs = list.get(i - 1); if (objs instanceof List) { List<Object> values = (List<Object>) objs; for (int h = 1, k = values.size(); h <= k; k++) { Object value = values.get(k - 1); setParameters(st, k, value); } } else { setParameters(st, i, objs); } st.addBatch(sql); if (i % 240 == 0) {//?240?sql??? st.executeBatch(); conn.commit(); st.clearBatch(); } else if (i % j == 0) {//?? st.executeBatch(); conn.commit(); st.clearBatch(); } } } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { closeAll(st, conn); } } public void setParameters(PreparedStatement ps, int j, Object value) throws SQLException { if (value != null) { if (value instanceof java.lang.Integer) { ps.setInt(j, (Integer) value); } else if (value instanceof java.lang.Long) { ps.setLong(j, (Long) value); } else if (value instanceof java.util.Date) { ps.setTimestamp(j, new java.sql.Timestamp(((Date) value).getTime())); } else if (value instanceof java.sql.Date) { ps.setDate(j, new java.sql.Date(((Date) value).getTime())); } else if (value instanceof java.lang.String) { ps.setString(j, value.toString()); } else if (value instanceof java.lang.Double) { ps.setDouble(j, (Double) value); } else if (value instanceof java.lang.Byte) { ps.setByte(j, (Byte) value); } else if (value instanceof java.lang.Character) { ps.setString(j, value.toString()); } else if (value instanceof java.lang.Float) { ps.setFloat(j, (Float) value); } else if (value instanceof java.lang.Boolean) { ps.setBoolean(j, (Boolean) value); } else if (value instanceof java.lang.Short) { ps.setShort(j, (Short) value); } else { ps.setObject(j, value); } } else { ps.setNull(j, Types.NULL); } } private void closeAll(Statement st, Connection conn) { if (st != null) { try { st.close(); } catch (SQLException e2) { e2.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e2) { e2.printStackTrace(); } } } }