第一步:配置web.xml文件,添加对spring和spring mvc的支持
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description>指定配置文件路径</description> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.do</url-pattern> <!-- 所有以*.do结尾的request都会被拦截 --> </servlet-mapping>
第二步:在spring的配置文件中配置数据源和对hibernate的支持
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop classpath:/org/springframework/aop/config/spring-aop-3.2.xsd http://www.springframework.org/schema/beans classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd http://www.springframework.org/schema/context classpath:/org/springframework/context/config/spring-context-3.0.xsd http://www.springframework.org/schema/mvc classpath:/org/springframework/web/servlet/config/spring-mvc-3.2.xsd http://www.springframework.org/schema/tx classpath:/org/springframework/transaction/config/spring-tx-3.0.xsd "> <!-- ===================================== 视图配置 ===================================== --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> <!-- ===================================== 注解驱动的配置 ===================================== --> <!-- <mvc:annotation-driven /> --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json; charset=UTF-8</value> <value>application/x-www-form-urlencoded; charset=UTF-8</value> </list> </property> </bean> --> </mvc:message-converters> </mvc:annotation-driven> <context:component-scan base-package="com.login" /> <!-- 读取资源文件 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${jdbc.driverClassName}</value> </property> <property name="password"> <value>${jdbc.password}</value> </property> <property name="username"> <value>${jdbc.username}</value> </property> <property name="url"> <value>${jdbc.url}</value> </property> </bean> <!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${jdbc.driverClassName}</value> </property> <property name="jdbcUrl"> <value>${jdbc.url}</value> </property> <property name="user"> <value>${jdbc.username}</value> </property> <property name="password"> <value>${jdbc.password}</value> </property> <property name="minPoolSize"> <value>2</value> </property> <property name="maxPoolSize"> <value>5</value> </property> <property name="maxIdleTime"> <value>20000</value> </property> <property name="acquireIncrement"> <value>2</value> </property> <property name="maxStatements"> <value>0</value> </property> <property name="initialPoolSize"> <value>2</value> </property> <property name="idleConnectionTestPeriod"> <value>8000</value> </property> <property name="acquireRetryAttempts"> <value>30</value> </property> <property name="breakAfterAcquireFailure"> <value>true</value> </property> <property name="testConnectionOnCheckout"> <value>false</value> </property> </bean> --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource" /> </property> <property name="mappingDirectoryLocations"> <list> <value>classpath:com/login/entities</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref local="dataSource"></ref> </property> </bean> </beans>
主要支持注解
第三步:创建jdbc.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull jdbc.username=root jdbc.password=253503125
第四步:创建IBaseDao
public interface IBaseDao { /** * 保存 * @param entity --实体对象 * @throws HibernateException */ public void save(final Object entity) throws HibernateException; /** * 更新 * @param entity --实体对象 * @throws HibernateException */ public void update(final Object entity) throws HibernateException; /** * 保存或更新 * @param entity --实体对象 * @throws HibernateException */ public void saveOrUpdate(final Object entity) throws HibernateException; /** * 根据主键ID删除 * @param id --主键ID * @param entityClass --实体类 * @throws HibernateException */ public void delById(final Serializable id, final Class entityClass) throws HibernateException; /** * 删除 * @param entity --实体对象 * @throws HibernateException */ public void del(final Object entity) throws HibernateException; /** * 根据主键ID查找 * @param id --主键ID * @param entityClass --实体类 * @return Object * @throws HibernateException */ public Object findById(final Serializable id, final Class entityClass) throws HibernateException; /** * 根据属性查找 * @param propertyName --属性名称 * @param value --查询值 * @param EntityClass --实体类 * @return Object * @throws HibernateException */ public Object findByProperty(final String propertyName, final Object value, final Class EntityClass) throws HibernateException; /** * 查询列表 * @param entityClass --实体类 * @return List * @throws HibernateException */ public List findList(final Class entityClass) throws HibernateException; /** * 查询列表 * @param entityClass --实体类 * @param order --排序(不设定排序则为null) * @return List * @throws HibernateException */ public List findList(final Class entityClass, final Order order) throws HibernateException; /** * 查询列表 * @param entityClass --实体类 * @param order --排序(不设定排序则为null) * @param curPage --查询页码 * @return List * @throws HibernateException */ public List findList(final Class entityClass, final Order order, final int curPage) throws HibernateException; /** * 查询列表(模糊查询) * @param param --查询实体对象(带查询参数) * @param order --排序(不设定排序则为null) * @param curPage --查询页码 * @return List * @throws HibernateException */ public List findList(final Object param, final Order order, final int curPage) throws HibernateException; /** * 根据HQL查询列表 * @param hqlStr --HQL * @return List * @throws HibernateException */ public List findListByHql(final String hqlStr) throws HibernateException; /** * 根据HQL查询列表 * @param hqlStr --HQL * @param args --参数 * @return List * @throws HibernateException */ public List findListByHql(final String hqlStr, final Object[] args) throws HibernateException; /** * 根据HQL查询列表 * @param hqlStr --HQL * @param curPage --查询页码 * @return List * @throws HibernateException */ public List findListByHql(final String hqlStr, final int curPage) throws HibernateException; /** * 根据HQL查询唯一一条记录 * @param hqlStr --HQL * @return Object * @throws HibernateException */ public Object findUniqueByHql(final String hqlStr) throws HibernateException; /** * 根据HQL查询唯一一条记录 * @param hqlStr --HQL * @param args --参数 * @return Object * @throws HibernateException */ public Object findUniqueByHql(final String hqlStr, final Object[] args) throws HibernateException; /** * 获取Hibernate的Session * @return Session */ public Session getHibernateSession(); public void flush(); public void clear(); /** * 执行SQL,返回执行影响行数 * @param sqlStr --SQL * @return int * @throws DataAccessException */ public int executeSql(final String sqlStr) throws DataAccessException; /** * 执行SQL,返回执行影响行数 * @param sqlStr --SQL * @param args --参数 * @return int * @throws DataAccessException */ public int executeSql(final String sqlStr, final Object[] args) throws DataAccessException; /** * 执行SQL查询,返回统计值 * @param sqlStr --SQL * @return int * @throws DataAccessException */ public int queryForInt(final String sqlStr) throws DataAccessException; /** * 执行SQL查询,返回统计值 * @param sqlStr --SQL * @param args --参数 * @return int * @throws DataAccessException */ public int queryForInt(final String sqlStr, final Object[] args) throws DataAccessException; /** * 批量操作(插入、更新、删除) * @param sqlStr --SQL * @param batchPstmt --BatchPreparedStatementSetter对象 * @return int * @throws DataAccessException */ public int batchExecuteBySql(final String sqlStr, final BatchPreparedStatementSetter batchPstmt) throws DataAccessException; public JdbcTemplate getJdbcTemplate(); public void setJdbcTemplate(JdbcTemplate jdbcTemplate); /** * 设置每页显示的记录数 * @param pageSize */ public void setPageSize(int pageSize); }
第五步:创建BaseDao实现IBaseDao
package com.login.dao.impl; import java.io.Serializable; import java.sql.SQLException; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.annotation.Resource; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.login.dao.IBaseDao; import com.login.util.Tools; public class BaseDao extends HibernateDaoSupport implements IBaseDao { /** * 保存 * @param entity --实体对象 * @throws HibernateException */ public void save(final Object entity) throws HibernateException { getHibernateTemplate().save(entity); } /** * 更新 * @param entity --实体对象 * @throws HibernateException */ public void update(final Object entity) throws HibernateException { getHibernateTemplate().update(entity); } /** * 保存或更新 * @param entity --实体对象 * @throws HibernateException */ public void saveOrUpdate(final Object entity) throws HibernateException { getHibernateTemplate().saveOrUpdate(entity); } /** * 根据主键ID删除 * @param id --主键ID * @param entityClass --实体类 * @throws HibernateException */ public void delById(final Serializable id, final Class entityClass) throws HibernateException { Object entity = null; if(id.getClass().getSimpleName().equals("Integer")) { entity = findById(Integer.valueOf(id.toString()), entityClass); }else { entity = findById(id, entityClass); } if(entity != null) del(entity); } /** * 删除 * @param entity --实体对象 * @throws HibernateException */ public void del(final Object entity) throws HibernateException { getHibernateTemplate().delete(entity); } /** * 根据主键ID查找 * @param id --主键ID * @param entityClass --实体类 * @return Object * @throws HibernateException */ @SuppressWarnings("unchecked") public Object findById(final Serializable id, final Class entityClass) throws HibernateException { Object entity = null; if(id.getClass().getSimpleName().equals("Integer")) { entity = getHibernateTemplate().get(entityClass, Integer.valueOf(id.toString())); }else { entity = getHibernateTemplate().get(entityClass, id); } return entity; } /** * 根据属性查找 * @param propertyName --属性名称 * @param value --查询值 * @param EntityClass --实体类 * @return Object * @throws HibernateException */ public Object findByProperty(final String propertyName, final Object value, final Class entityClass) throws HibernateException { Object entity = null; List list = getHibernateTemplate().executeFind( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { List results = session.createCriteria(entityClass) .add(Restrictions.eq(propertyName, value)) .list(); return results; } } ); if(!list.isEmpty() && list.size() > 0) { entity = list.get(0); } return entity; } /** * 查询列表 * @param entityClass --实体类 * @return List * @throws HibernateException */ public List findList(final Class entityClass) throws HibernateException { List list = null; list = getHibernateTemplate().executeFind( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { List results = null; Criteria criteria = session.createCriteria(entityClass); results = criteria.list(); return results; } } ); return list; } /** * 查询列表 * @param entityClass --实体类 * @param order --排序(不设定排序则为null) * @return List * @throws HibernateException */ public List findList( final Class entityClass, final Order order ) throws HibernateException { List list = null; list = getHibernateTemplate().executeFind( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { List results = null; Criteria criteria = session.createCriteria(entityClass); if(order != null) { criteria.addOrder(order); } results = criteria.list(); return results; } } ); return list; } /** * 分页查询列表 * @param entityClass --实体类 * @param order --排序(不设定排序则为null) * @param curPage --查询页码 * @return List * @throws HibernateException */ public List findList( final Class entityClass, final Order order, final int curPage ) throws HibernateException { List list = null; list = getHibernateTemplate().executeFind( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { List results = null; Criteria criteria = session.createCriteria(entityClass); if(order != null) { criteria.addOrder(order); } criteria.setMaxResults(pageSize); criteria.setFirstResult((curPage-1)*pageSize); results = criteria.list(); return results; } } ); return list; } /** * 查询列表(模糊查询) * @param param --查询实体对象(带查询参数) * @param order --排序(不设定排序则为null) * @param curPage --查询页码 * @return List * @throws HibernateException */ public List findList( final Object param, final Order order, final int curPage ) throws HibernateException { List list = null; list = getHibernateTemplate().executeFind( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { List results = null; Criteria criteria = session.createCriteria(param.getClass()); Collection methodInfo = Tools.getMethodInfo(param); Iterator itr = methodInfo.iterator(); while(itr.hasNext()) { Object[] fv = (Object[])itr.next(); //System.out.println("字段名:" + fv[1].toString() + " -- 返回值:" + fv[2].toString() + " -- 返回类型:" + fv[0].toString()); if(fv[2] != null && !fv[2].equals("")) { if(fv[0].toString().indexOf("String") > 0) { //如果返回值类型为字符串类型 criteria.add(Restrictions.like(fv[1].toString(), fv[2].toString(), MatchMode.ANYWHERE)); }else { //如果返回值类型为数字类型 if(Integer.valueOf(fv[2].toString()) != 0) { criteria.add(Restrictions.eq(fv[1].toString(), fv[2])); } } } } if(order != null) { criteria.addOrder(order); } criteria.setMaxResults(pageSize); criteria.setFirstResult((curPage-1)*pageSize); results = criteria.list(); return results; } } ); return list; } /** * 根据HQL查询列表 * @param hqlStr --HQL * @return List * @throws HibernateException */ public List findListByHql( final String hqlStr ) throws HibernateException { return getHibernateTemplate().find(hqlStr); } /** * 根据HQL查询列表 * @param hqlStr --HQL * @param args --参数 * @return List * @throws HibernateException */ public List findListByHql( final String hqlStr, final Object[] args ) throws HibernateException { return getHibernateTemplate().find(hqlStr, args); } /** * 根据HQL查询列表 * @param hqlStr --HQL * @param curPage --查询页码 * @return List * @throws HibernateException */ public List findListByHql( final String hqlStr, final int curPage ) throws HibernateException { List list = null; list = getHibernateTemplate().executeFind( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { List results = null; Query query = session.createQuery(hqlStr); query.setMaxResults(pageSize); query.setFirstResult((curPage-1)*pageSize); results = query.list(); return results; } } ); return list; } /** * 根据HQL查询唯一一条记录 * @param hqlStr --HQL * @return Object * @throws HibernateException */ public Object findUniqueByHql( final String hqlStr ) throws HibernateException { Object entity = null; List list = null; list = getHibernateTemplate().find(hqlStr); if(!list.isEmpty() && list.size() > 0) { entity = list.get(0); } return entity; } /** * 根据HQL查询唯一一条记录 * @param hqlStr --HQL * @param args --参数 * @return Object * @throws HibernateException */ public Object findUniqueByHql( final String hqlStr, final Object[] args ) throws HibernateException { Object entity = null; List list = null; list = getHibernateTemplate().find(hqlStr, args); if(!list.isEmpty() && list.size() > 0) { entity = list.get(0); } return entity; } /** * 获取Hibernate的Session * @return Session */ public Session getHibernateSession() { return this.getSession(); } public void flush() { getHibernateTemplate().flush(); } public void clear() { getHibernateTemplate().clear(); } //JDBC************************************************************************************* /** * 执行SQL,返回执行影响行数 * @param sqlStr --SQL * @return int * @throws DataAccessException */ public int executeSql( final String sqlStr ) throws DataAccessException { //println("执行SQL:" + sqlStr); int resultSum = jdbcTemplate.update(sqlStr); //println("影响行数:" + resultSum); return resultSum; } /** * 执行SQL,返回执行影响行数 * @param sqlStr --SQL * @param args --参数 * @return int * @throws DataAccessException */ public int executeSql( final String sqlStr, final Object[] args ) throws DataAccessException { //println("执行SQL:" + sqlStr); int resultSum = jdbcTemplate.update(sqlStr, args); //println("影响行数:" + resultSum); return resultSum; } /** * 执行SQL查询,返回统计值 * @param sqlStr --SQL * @return int * @throws DataAccessException */ public int queryForInt( final String sqlStr ) throws DataAccessException { //println("执行SQL:" + sqlStr); int iValue = jdbcTemplate.queryForInt(sqlStr); //println("统计值:" + iValue); return iValue; } /** * 执行SQL查询,返回统计值 * @param sqlStr --SQL * @param args --参数 * @return int * @throws DataAccessException */ public int queryForInt( final String sqlStr, final Object[] args ) throws DataAccessException { int iValue = jdbcTemplate.queryForInt(sqlStr, args); return iValue; } /** * 批量操作(插入、更新、删除) * @param sqlStr --SQL * @param batchPstmt --BatchPreparedStatementSetter对象 * @return int * @throws DataAccessException */ public int batchExecuteBySql( final String sqlStr, final BatchPreparedStatementSetter batchPstmt ) throws DataAccessException { int[] sum = jdbcTemplate.batchUpdate(sqlStr, batchPstmt); return sum.length; } //JDBC 模版******************************************************************************************** @Autowired private JdbcTemplate jdbcTemplate; public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } //查询需要分页的数据列表时用到***************************************************************************************** /** * 查询列表时,默认每页显示的记录数 */ private int pageSize = 10; /** * 设置每页显示的记录数 * @param pageSize */ public void setPageSize(int pageSize) { this.pageSize = pageSize; } @Resource public void setSessionFactory0(SessionFactory sessionFactory){ System.out.println("---__---"); super.setSessionFactory(sessionFactory); } }
然后在书写自己需要的dao时,只需要集成BaseDao即可。当BaseDao中的方法无法满足时,可以通过获取session,然后按照jdbc的操作方法来完成。