欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring5+hibernate5整合加测试(全注解)

程序员文章站 2022-03-27 08:27:32
...

maven配置文件

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.zcj.test</groupId>
	<artifactId>mvc</artifactId>
	<version>1.0</version>
	<packaging>war</packaging>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.0.2.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>5.0.2.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.0.2.RELEASE</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/junit/junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.29</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.12.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>5.2.12.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
			<version>5.2.12.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>2.10.4</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.8.0-beta0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.8.0-beta0</version>
			<scope>test</scope>
		</dependency>



	</dependencies>
	<properties>
		<failOnMissingWebXml>false</failOnMissingWebXml>
	</properties>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

数据库配置文件

init.properties

#mysql database setting
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring?useUnicode=true&characterEncoding=utf-8
jdbc.user=root
jdbc.password=password
jdbc.checkoutTimeout=30000
jdbc.idleConnectionTestPeriod=60
jdbc.maxIdleTime=30
jdbc.initialPoolSize=5
jdbc.minPoolSize=5
jdbc.maxPoolSize=40
jdbc.acquireIncrement=5 

#hibernate config
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update
hibernate.current_session_context_class=thread
hibernate.cache.use_second_level_cache = false
hibernate.cache.use_query_cache=false
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path=ehcache.xml

 日志配置文件

log4j.properties

### set log levels ###  INFO
log4j.rootLogger = INFO,stdout,E
 
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.logger.org.quartz=INFO 
log4j.appender.E= org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =logs/mylogs.log
log4j.appender.E.DatePattern=yyyy-MM-dd'.log'
log4j.appender.E.Threshold =INFO
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}[%c] [%t\:%r] - [%p]  %m%n

#为了显示参数
log4j.logger.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
log4j.loggerorg.hibernate.type.descriptor.sql.BasicExtractor=TRACE

#查看查询中命名参数的值
 log4j.logger.org.hibernate.engine.QueryParameters=DEBUG
 log4j.logger.org.hibernate.engine.query.HQLQueryPlan=DEBUG

 缓存配置文件

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
	<defaultCache maxElementsInMemory="10000" eternal="false"
	timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false"></defaultCache>
</ehcache>

spring配置文件

bean.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:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	<context:annotation-config></context:annotation-config>
	<context:component-scan base-package="com.zcj"></context:component-scan>
	<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:init.properties</value>
			</list>
		</property>
	</bean>
	<!-- 配置数据源 c3p0 -->
	<bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.url}"></property>
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<!-- 请求超时时间 -->
        <property name="checkoutTimeout" value="${jdbc.checkoutTimeout}" />
        <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
        <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}" />
        <!-- 连接数据库连接池最大空闲时间 -->
        <property name="maxIdleTime" value="${jdbc.maxIdleTime}" />
        <!-- 连接池初始化连接数 -->
        <property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
        <property name="minPoolSize" value="${jdbc.minPoolSize}" />
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
        <property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
	</bean>
	<bean id="localSessionFactoryBean" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="comboPooledDataSource"></property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<!--                 <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop> -->
                <!-- 开启二级缓存 ehcache -->
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}</prop>
			</props>
		</property>
		<property name="packagesToScan" value="com.zcj.entry"/>
	</bean>
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="localSessionFactoryBean"/>
		<property name="dataSource" ref="comboPooledDataSource"/>
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 	<bean id="baseDao" class="com.zcj.service.test.BaseDao"> -->
<!-- 		<property name="sessionFactory" ref="localSessionFactoryBean"/> -->
<!-- 	</bean> -->
</beans>
 实体,采用全注解
package com.zcj.entry.test;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Student implements Serializable{
	private static final long serialVersionUID = 8021925565032055905L;
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;
	private String name;
	private Date date;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	
}

 dao层

package com.zcj.service.test;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
@Repository
public class BaseDao extends HibernateDaoSupport {
	@Autowired
	@Qualifier("localSessionFactoryBean")
	public void setSessionFactoryBase(SessionFactory sessionFactory){
		this.setSessionFactory(sessionFactory);
	}
}

 服务层

package com.zcj.service.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zcj.entry.test.Student;
@Transactional
@Service
public class TestService {
	private static final Logger logger = LoggerFactory.getLogger(TestService.class);
	@Autowired
	private BaseDao dao;
	public void save(Student student){
		dao.getSessionFactory().openSession().save(student);
	}
	public Student findOne(Long id){
		HibernateTemplate hibernateTemplate = dao.getHibernateTemplate();
		System.out.println(hibernateTemplate);
		Student student = hibernateTemplate.get(Student.class, id);
		System.out.println(student);
		return student ;
	}
}

 测试

package com.zcj.test;

import java.util.Date;

import org.junit.Test;
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 com.zcj.entry.test.Student;
import com.zcj.service.test.TestService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:bean.xml"})
public class MyTest {
	@Autowired
	public TestService service;
	@Test
	public void testInsert(){
		Student student = new Student();
		student.setDate(new Date());
		student.setName("zhoucanji");
		service.save(student);
	}
	@Test
	public void testFind(){
		service.findOne(1L);
	}
}

 如果觉得不错,请评价

相关标签: 框架整合