1,maven创建web工程
2,导入相关依赖 pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId> <artifactId>test</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <url>http://maven.apache.org</url> <properties> <spring.version>4.3.3.RELEASE</spring.version> <mysql.connector.version>5.1.40</mysql.connector.version> <hibernate.version>4.3.11.Final</hibernate.version> </properties> <dependencies> <!-- servlet jar --> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2.1-b03</version> <scope>provided</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> <!-- 连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.1</version> </dependency> <!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate.common</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>4.0.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> </dependencies> </project>
3,配置相关文件
(1) db.properties
db.user=root
db.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
db.password=123456
db.driver=com.mysql.jdbc.Driver
db.initialPoolSize=2
db.minPoolSize=2
db.maxpoolSize=5
db.checkoutTimeout=50000
db.timeBetweenEvictionRunsMillis=60000
db.minEvictableTimeMillis=300000
(2)applicationContext.xml
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置扫描的包,完成Bean创建和自动依赖注入的功能 --> <context:component-scan base-package="com.test.*" /> <!-- 引入配置文件 --> <context:property-placeholder location="classpath*:*.properties" /> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 连接数据库基本参数 --> <property name="url" value="${db.url}"></property> <property name="username" value="${db.user}"></property> <property name="password" value="${db.password}"></property> <!-- druid连接池加密 --> <!-- <property name="filters" value="config"></property> <property name="connectionProperties" value="config.decrypt=true"></property> --> <property name="driverClassName" value="${db.driver}"></property> <!-- 初始化大小,最小,最大连接数 --> <property name="initialSize" value="${db.initialPoolSize}"></property> <property name="minIdle" value="${db.minPoolSize}"></property> <property name="maxActive" value="${db.maxpoolSize}"></property> <!-- 获取连接等待超时的时间 --> <property name="maxWait" value="${db.checkoutTimeout}"></property> <!-- 间隔检测时长,检测需要关闭的空闲连接,单位毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${db.timeBetweenEvictionRunsMillis}"></property> <!-- 一个连接在池中最小生存的时间,单位毫秒 --> <property name="minEvictableIdleTimeMillis" value="${db.minEvictableTimeMillis}"></property> <!-- ?? --> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="false"></property> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"></property> <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 --> <!-- <property name="filters" value="stat"/> --> </bean> <!-- hibernate+spring整合 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!-- hibernate相关属性配置 --> <property name="hibernateProperties"> <value> <!-- 设置方言 --> hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect <!-- 设置自动创建|更新|验证数据库表结构 --> hibernate.hbm2ddl.auto=update <!-- 是的在控制台显示sql --> hibernate.show_sql=true <!-- 是否格式化sql,优化显示 --> hibernate.format_sql=true <!-- 是否开启二级缓存 --> hibernate.cache.use_second_level_cache=false <!-- 是否开启查询缓存 --> hibernate.cache.use_query_cache=false <!-- 数据库批量查询最大数 --> hibernate.jdbc.fetch_size=50 <!-- 数据库批量更新、添加、删除操作最大数 --> hibernate.jdbc.batch_size=50 <!-- 是否自动提交事务 --> <!-- hibernate.connection.autocommit=false --> <!-- 指定hibernate在何时释放JDBC连接 --> <!-- hibernate.connection.release_mode=auto --> <!-- 创建session方式hibrenate4的方式 --> hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext </value> </property> <!-- xml实体映射使用 --> <property name="mappingLocations"> <value>classpath*:/com/test/entity/*.hbm.xml</value> </property> </bean> <!-- 启动对事务注解的支持 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 定义事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 事务的执行方式 --> <tx:attributes> <tx:method name="create*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="remove*" propagation="REQUIRED"/> <tx:method name="del*" propagation="REQUIRED"/> <tx:method name="next*" propagation="REQUIRED"/> <tx:method name="import*" propagation="REQUIRED"/> <tx:method name="insert*" read-only="false" propagation="REQUIRED"/> <!-- read-only="true"表示只读 --> <tx:method name="get*" propagation="NOT_SUPPORTED"/> <tx:method name="find*" propagation="NOT_SUPPORTED"/> </tx:attributes> </tx:advice> <!-- 定义切面,在 .service 中执行有关的hibernate session的事务操作 --> <aop:config> <aop:pointcut id="serviceOperation" expression="execution(* com.test.service.*.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" /> </aop:config> <!-- 会自动注册validator ConversionService --> <mvc:annotation-driven validator="validator" conversion-service="conversion-service" /> <!-- 注册HandlerMapper、HandlerAdapter两个映射类 激活@Controller模式 --> <mvc:annotation-driven /> <!-- 定义 Autowired 自动注入 bean --> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> <!-- 访问静态资源 --> <mvc:default-servlet-handler /> <!-- spring-context.jar 以下validator ConversionService在使用mvc:annotation-driven会自动注册 --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <!-- 如果不加默认到classpath下的ValidationMessages.properties --> <property name="validationMessageSource" ref="messageSource"></property> </bean> <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="defaultEncoding" value="UTF-8" /> <property name="basenames"> <list> <value>classpath:ValidationMessages</value> </list> </property> </bean> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
(3)web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- 配置spring的加载文件路径及文件名称 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
4,写dao层和实现类
import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.orm.hibernate4.HibernateCallback; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; /*** * hibernate基础实现类 * @author * * @param <T> */ @Repository public class BaseDao<T> extends HibernateDaoSupport { @Autowired() @Qualifier("sessionFactory") public void setBaseSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } protected List<T> getList(final String entityName, final int beginIndex,final int length){ return this.getHibernateTemplate().execute(new HibernateCallback<List<T>>() { @Override public List<T> doInHibernate(Session session) throws HibernateException { final String hql=" from "+entityName; Query query=session.createQuery(hql); query.setFirstResult(beginIndex); query.setMaxResults(length); @SuppressWarnings("unchecked") List<T> list=query.list(); return list; } }); } }
import java.util.List; import org.springframework.stereotype.Repository; import com.test.entity.Goods; @Repository public interface GoodsDao { public List<Goods> getList(); }
import java.util.List; import org.springframework.stereotype.Repository; import com.test.dao.GoodsDao; import com.test.entity.Goods; @Repository public class GoodsDaoImpl extends BaseDao<Goods> implements GoodsDao { @Override public List<Goods> getList() { return this.getList("Goods", 0, 1); } }
5,service和实现类
import java.util.List; import org.springframework.stereotype.Service; import com.test.entity.Goods; @Service public interface GoodsService { public List<Goods> getList(); }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.test.dao.GoodsDao; import com.test.entity.Goods; import com.test.service.GoodsService; @Service public class GoodsServiceImpl implements GoodsService { @Autowired private GoodsDao goodsDao; @Override public List<Goods> getList() { // TODO Auto-generated method stub return goodsDao.getList(); } }
6,测试
import java.util.List; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.test.entity.Goods; import com.test.service.GoodsService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:applicationContext.xml" }) @Transactional public class GoodsTest { @Autowired private GoodsService goodsService; @org.junit.Test public void getList() { List<Goods> goods=goodsService.getList(); for(Goods g:goods) { System.out.println(g.getName()); } } }
注:在单元测试插入数据时,默认会将事务回滚,如果想阻止spring transactional回滚,在test方法上加注解@Rollback(false)即可