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. 阶段1 语言基础+高级_1-2 -面向对象和封装_15练习使用private关键字定义

    练习使用private关键字定义一个学生类.通过这个联系说明一种特殊情况 先定义了name个age分别再定义getter和setter的方法 boolean类型的getter方法不能叫做get开头的. ...

  2. UI自动化之三种等待

    UI自动化中常用三种等待 目录 1.强制等待 2.隐式等待 3.显示等待 1.强制等待 执行到某一条语句后,然后sleep(3),等待3秒后,才会继续执行后面的语句 2.隐式等待 隐式等待只需要声明一 ...

  3. 5 centos 6.10 三节点安装apache hadoop 2.9.1

    Hadoop 版本: apache hadoop 2.9.1JDK 版本: Oracle JDK1.8集群规划master(1): NN, RM, DN, NM, JHSslave1(2): DN, ...

  4. 前端框架React入门课程【视频】

    视频教程列表: http://v1.mukewang.com/1a8228ac-5f7f-48de-b1c5-7d1b8bce9c77/L.mp4 1-1 React入门课程介绍 http://v1. ...

  5. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

    今天执行mysql操作的时候出现了错误:ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run ...

  6. 并查集入门(hdu1232“畅通工程”)

    在学习并查集之前,首先需要明白基本的并查集可以完成的功能.并查集主要是用于处理不相交集合的合并问题.它是一种基础算法,在离散数学中,可以利用并查集求一个图的连通分支,利用其这个特性可以为我们解决一系列 ...

  7. codeforces#1215E. Marbles(状压DP)

    题目大意:给出一个由N个整数组成的序列,通过每次交换相邻的两个数,使这个序列的每个相同的数都相邻.求最小的交换次数. 比如给出序列:1 2 3 2 1 ,那么最终序列应该是 1 1 2 2 3 ,最小 ...

  8. 应用安全 - 安全设备 - WAF原理/检测/绕过

    原理 基于Cookie值 Citrix Netscaler(2013年使用广泛) “Citrix Netscaler”会在HTTP返回头部Cookie位置加入“ns_af”的值,可以以此判断为Citr ...

  9. python3.5+django2.0快速入门(二)

    昨天写了python3.5+django2.0快速入门(一)今天将讲解配置数据库,创建模型,还有admin的后台管理. 配置数据库 我们打开mysite/mysite/settings.py这个文件. ...

  10. Vue 基础 day03

    定义Vue 组件 什么是组件:组件的出现,就是为了拆分 Vue 实例的代码量,能够让我们以不同的组件,来划分不同的功能模块,将来我们需要什么样的功能,就可以去调用对应的组件: 组件化和模块化的不同: ...