Hibernate4与Spring4整合,使用Junit4测试相关学习笔记

一、在myeclipse中创建web project


1.导入Hibernate4.1与Spring4.1的Libraries。其中myeclipse自带的spring libraries中缺少spring-test.jar包,需要自己从网上下载。mysql与c3p0数据库连接池支持下载一下。


2.导入Junit4的jar包,myeclipse中自带的,使用Junit4测试hibernate4与spring4整合,必须使用4.4往后的版本,切记。我是myeclipse直接导入,myeclipse2017 c1版本中自带的。

二,添加Hibernate配置文件(hibernate.cfg.xml)

各配置文件位置:


hibernate.cfg.xml配置文件:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    	<!-- 配置hibernate基本信息 -->  
      	<!-- 1.数据源配置在IOC容器中,此处不需要额外配置 -->  
     	<!-- 2.关联的.hbm.xml文件也在IOC容器配置SessionFactory时配置 -->  
     	<!-- 3.此处配置hibernate的基本信息:数据库方言、SQL显示及格式化,及生成数据表的策略,二级缓存等 --> 
    	<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    	<property name="hibernate.show_sql">true</property>
    	<property name="hibernate.format_sql">true</property>
    	<property name="hibernate.hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>

1.创建测试使用的持久化类以及生成Hibernate映射文件

持久化类:

package com.test.entity;

public class People {
	private int id;
	private String name;
	private int pid;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	
}

hibernate映射文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.test.entity.People" table="people">
		<id name="id"  type="int">
			<column name="id"></column>
			<generator class="native"></generator>
		</id>
		<property name="name"  type="string"><!-- 注意写String类型时首字母不能大写-->
			<column name="name"></column>
		</property>
		<property name="pid"  type="int">
			<column name="pid"></column>
		</property>
	</class>
</hibernate-mapping>

三、加入Spring配置文件

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:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"
	xmlns:tx="http://www.springframework.org/schema/tx">
	<!--使用到的声明一定一定要写对写全↑-->
	<context:component-scan base-package="com.test"></context:component-scan>
	
	<context:property-placeholder location="classpath:db.properties"/>
	
	<bean  id="dataSource"  class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user"   value="${jdbc.user}"></property>
		<property name="password"  value="${jdbc.password}"></property>
		<property name="driverClass"  value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl"  value="${jdbc.jdbcUrl}"></property>
		<property name="initialPoolSize"   value="${jdbc.initPoolSize}"></property>
		<property name="maxPoolSize"  value="${jdbc.maxPoolSize}"></property>
	</bean>
	
	<!-- 配置Hibernate的SessionFactory,通过spring提供的 LocalSessionFactoryBean配置--> 
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		 <!-- 配置依赖的数据源属性 --> 
		<property name="dataSource" 	ref="dataSource"></property>
		<!-- hibernate 配置文件的路径 --> 
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
		<!-- 配置hibernate映射文件的路径,可以使用通配符 --> 
		<property name="mappingLocations" value="classpath:com/test/entity/*.hbm.xml"></property> 
	</bean>
	
	<!-- 配置 Spring 的声明式事物 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	
	<!-- 配置事物属性 ,需要事物管理器-->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">  
       		<tx:attributes>  
          		<tx:method name="get*" read-only="true"/>  
          		<tx:method name="purchase" propagation="REQUIRES_NEW"/>  
          		<tx:method name="*"/>  
       		</tx:attributes>  
    	</tx:advice>
    
    	<aop:config>  
     	 	<aop:pointcut expression="execution(* com.test.service.*.*(..))" id="txPointcut"/>  
     	 	<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>  
    	</aop:config> 
	<tx:annotation-driven transaction-manager="transactionManager" />
	
	<bean id="peopleService"  class="com.test.serviceimpl.PeopleServiceImpl"></bean>
	
</beans>

依赖的数据库配置文件db.properties:

jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/hibernate
jdbc.initPoolSize=5
jdbc.maxPoolSize=10

四、整合测试

工程目录:


新建上述各目录:

在dao包中创建接口

package com.test.dao;

import java.util.List;
import com.test.entity.People;

public interface PeopleDao {
	public People findByID(int id);
	public List<People> findAll();
	public List<People> findByPage(int page);
	public void add(People people);
	public void update(People people);
	public void delete(People people);
}

对应的在impl下完成上述接口的实现类(注解@Repository,用来标注持久层,同时表示此组件交给spring的IOC容器管理)

package com.test.daoimpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.test.dao.PeopleDao;
import com.test.entity.People;

@Repository
public class PeopleDaoImpl implements PeopleDao{
	@Autowired
	private SessionFactory sessionFactory;
	@Override
	public People findByID(int id) {
		Session session = sessionFactory.getCurrentSession();
		People people = (People) session.get(People.class, id);//此处使用load方法时用Junit4测试就会报错
		return people;
	}

	@Override
	public List<People> findAll() {
		Session session = sessionFactory.getCurrentSession();
		String hqlString = "from People";
		Query query = session.createQuery(hqlString);
		List<People> lists = query.list();
		return lists;
	}

	@Override
	public List<People> findByPage(int page) {
		Session session = sessionFactory.getCurrentSession();
		String hqlString = "from People";
		Query query = session.createQuery(hqlString);
		query.setFirstResult((page-1)*5);
		query.setMaxResults(5);
		List<People> lists = query.list();
		return lists;
	}

	@Override
	public void add(People people) {
		Session session = sessionFactory.getCurrentSession();
		session.save(people);
	}

	@Override
	public void update(People people) {
		Session session = sessionFactory.getCurrentSession();
		session.update(people);
	}

	@Override
	public void delete(People people) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(people);
	}

}

在service包下创建接口:

package com.test.service;

import java.util.List;
import com.test.entity.People;

public interface PeopleService {
	public People findByID(int id);
	public List<People> findAll();
	public List<People> findByPage(int page);
	public void add(People people);
	public void update(People people);
	public void delete(People people);
}

在serviceimpl包下创建实现类:

package com.test.serviceimpl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.test.dao.PeopleDao;
import com.test.entity.People;
import com.test.service.PeopleService;

public class PeopleServiceImpl implements PeopleService{
	@Autowired
	private PeopleDao peopleDao;
	@Override
	public People findByID(int id) {
		People people = peopleDao.findByID(id);
		return people;
	}

	@Override
	public List<People> findAll() {
		List<People> lists = peopleDao.findAll();
		return lists;
	}

	@Override
	public List<People> findByPage(int page) {
		List<People> lists = peopleDao.findByPage(page);
		return lists;
	}

	@Override
	public void add(People people) {
		peopleDao.add(people);
	}

	@Override
	public void update(People people) {
		peopleDao.update(people);
	}

	@Override
	public void delete(People people) {
		peopleDao.delete(people);
	}

}


填写测试类:

package com.test.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.test.entity.People;
import com.test.service.PeopleService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test {
	@Autowired
	private PeopleService peopleService;//采用注解使用peopleService时,applicationContext.xml配置文件中记得写出对应的bean
	@org.junit.Test
	public void peopleTest(){
//		People people = new People();
//		people.setName("杨八蛋");
//		people.setPid(0);
//		peopleService.add(people);
//		List<People> lists = peopleService.findByPage(1);
//		for (People people : lists) {
//			System.out.println(people.getId()+"-"+people.getName()+"-"+people.getPid());
//		}
		int id = 1;
		People people = peopleService.findByID(id);
		System.out.println(people);
	}
}

测试即可~



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值