1. 程式人生 > >Hibernate4與Spring4整合,使用Junit4測試相關學習筆記

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);
	}
}

測試即可~