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)即可

spring+hibernate单元测试案例的更多相关文章

  1. SpringMVC+Spring+Hibernate+Maven+mysql整合

    一.准备工作 1.工具:jdk1.7.0_80(64)+tomcat7.0.68+myeclipse10.6+mysql-5.5.48-win322. 开发环境安装配置.Maven项目创建(参考:ht ...

  2. spring+hibernate+struts整合(1)

    spring+hibernate:整合 步骤1:引入类包 如下图:这里是所有的类包,为后面的struts整合考虑

  3. spring+hibernate 配置多个数据源过程 以及 spring中数据源的配置方式

    spring+hibernate 配置多个数据源过程 以及 spring中数据源的配置方式[部分内容转载] 2018年03月27日 18:58:41 守望dfdfdf 阅读数:62更多 个人分类: 工 ...

  4. 转: 基于netty+ protobuf +spring + hibernate + jgroups开发的游戏服务端

    from: http://ybak.iteye.com/blog/1853335 基于netty+ protobuf +spring + hibernate + jgroups开发的游戏服务端 游戏服 ...

  5. Struts+Spring+Hibernate项目的启动线程

    在Java Web项目中,经常要在项目开始运行时启动一个线程,每隔一定的时间就运行一定的代码,比如扫描数据库的变化等等.要实现这个功能,可以现在web.xml文件中定义一个Listener,然后在这个 ...

  6. SSH面试题(struts2+Spring+hibernate)

    struts2 + Spring +hibernate Hibernate工作原理及为什么要用?   原理:   1.读取并解析配置文件   2.读取并解析映射信息,创建SessionFactory ...

  7. SSH(Struts2+Spring+Hibernate)框架搭建流程<注解的方式创建Bean>

    此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblo ...

  8. Struts,spring,hibernate三大框架的面试

    Struts,spring,hibernate三大框架的面试 1.Hibernate工作原理及为什么要用? 原理: 1.读取并解析配置文件 2.读取并解析映射信息,创建SessionFactory 3 ...

  9. Hibernate入门案例及增删改查

    一.Hibernate入门案例剖析: ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private I ...

随机推荐

  1. postman的断言/环境变量的处理

    我们做接口测试都会有一个断言操作:也有一个变量被频繁使用,这时候可以用环境变量来处理 目录 1.postman之断言 2.postman之环境变量 1.postman之断言 同样以postman的登录 ...

  2. Linux pip命令报错 -bash: pip: command not found

    下载 $ wget https://bootstrap.pypa.io/get-pip.py 安装 $ python get-pip.py 查看版本 $ pip -V 查看安装路径: find / - ...

  3. Java课堂笔记(二):面向对象

    几乎每一本介绍Java语言的书中都会提到“面向对象”的这个概念,然而博主初学Java时看到这方面的内容一般都是草草地看一看,甚至是直接略过.原因很简单:考试基本不考,而且初学阶段写代码也很少用上.但事 ...

  4. 前端 CSS的选择器 基本选择器

    基本选择器包括: 标签选择器 类选择器 ID选择器 通用选择器 标签选择器 就是通过标签名来选择元素: 选中p标签 <!DOCTYPE html> <html lang=" ...

  5. “希希敬敬对”团队--‘百度贴吧小爬虫’Alpha版本展示博客

    希希敬敬对的 Alpha阶段测试报告 随笔链接地址 https://www.cnblogs.com/xiaoyoushang/p/10078826.html   Alpha版本发布说明 随笔链接地址 ...

  6. Consul集群Server+Client模式

    Consul集群Server+Client模式 架构示意图 只使用Consul的Server模式有以下2个问题: 因为Consul Server数量受到控制所以压力承载(扩展性)是个问题. Serve ...

  7. INPUT输入子系统——按键

    一.什么是input输入子系统? 1.1. Linux系统支持的输入设备繁多,例如键盘.鼠标.触摸屏.手柄或者是一些输入设备像体感输入等等,Linux系统是如何管理如此之多的不同类型.不同原理.不同的 ...

  8. ZPL文件打印

    ZPL:全称是Zebra Printer Language,目前能够直接打印zpl文件的打印机只有斑马打印机 如何打印zpl文件呢? 软件类: 一.Print Conductor(桌面打印软件) ht ...

  9. for循环延伸

    经典面试题解析: for(var i = 1 ; i < 5 ; i++){ console.log(i) } //1 2 3 4 ------------------------------- ...

  10. Scrapy抓取jobbole数据

    1.python版本3.6.1 2.python编辑器:JetBrains PyCharm 2.安装virtualenvwrapper-win pip3 install virtualenvwrapp ...