sh_Spring整合Hibernate

周江霄發表於2015-06-29

    分別介紹了Sping和Hibernate,下面是將它們整合到一塊去了。


    一、Hibernate內容


    1.建立PO類。

    

package cn.tgb.domain;

//User實體
public class User {
	private Integer id;
	private String username;
	private String password;	
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}		
}

    2.編寫User.hbm.xml    

    

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
   
<hibernate-mapping>
	<class name="cn.tgb.domain.User" table="t_user">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<property name="username"></property>
		<property name="password"></property>
	</class>
</hibernate-mapping>

    3.編寫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>
		<!-- #1核心四項 -->
		<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
		<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433; DatabaseName=hibernate02</property>
		<property name="hibernate.connection.username">sa</property>
		<property name="hibernate.connection.password">123456</property>
		
		<!-- #2設定方言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
		
		<!-- #3 sql -->
		<!-- * 輸出sql-->
		<property name="hibernate.show_sql">true</property>
		<!-- * 格式化sql -->
		<property name="hibernate.format_sql">true</property>
		<!-- * 是否建立表 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- #4整合c3p0 -->
		<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
		
		<!-- #5 web專案6.0 取消bean校驗 -->
		<property name="javax.persistence.validation.mode">none</property>			
		
		<!-- #6新增對映檔案 -->
		<mapping resource="cn/tgb/domain/User.hbm.xml"/>
	</session-factory>
</hibernate-configuration> 

    二、Spring內容


    1.Dao實現類:使用HibernateTemplate對PO類進行操作。

    

package cn.tgb.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;

import cn.tgb.dao.UserDao;
import cn.tgb.domain.User;

public class UserDaoImpl implements UserDao{

	//使用hibernateTemplate對PO類進行操作
	private HibernateTemplate hibernateTemplate;
	//提供set方法
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	@Override
	public void save(User user) {
		this.hibernateTemplate.save(user);
	}

	@Override
	public void update(User user) {
		this.hibernateTemplate.update(user);
	}

	@Override
	public void delete(User user) {
		this.hibernateTemplate.delete(user);
	}

	@Override
	public User findById(Integer uid) {
		return this.hibernateTemplate.get(User.class, uid);
	}

	@Override
	public List<User> findAllUser() {
		return this.hibernateTemplate.find("from User");
	}
	
}

    2.Service實現類:直接使用dao層,通過spring tx管理事務


package cn.tgb.service.impl;

import java.util.List;

import cn.tgb.dao.UserDao;
import cn.tgb.domain.User;
import cn.tgb.service.UserService;

public class UserServiceImpl implements UserService{
	//引入UserDao
	private UserDao userDao;
	//提供set方法
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public void addUser(User user) {
		this.userDao.save(user);
	}

	@Override
	public void updateUser(User user) {
		this.userDao.update(user);
	}

	@Override
	public void deleteUser(User user) {
		this.userDao.delete(user);
	}

	@Override
	public User findUserById(Integer uid) {
		return this.userDao.findById(uid);
	}

	@Override
	public List<User> findAllUser() {
		return this.userDao.findAllUser();
	}

}


    3.配置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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx.xsd">
	
     <!-- #1配置sessionFactory,
     	通過LocalSessionFactoryBean載入配置獲得SessionFactory 
     -->  
     
     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
     	<!-- #1.1確定配置檔案的位置 -->
     	<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
     </bean>
     <!-- #2 hibernateTemplate -->  
     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
     	<!-- 需要使用sessionFactory獲得session,操作PO物件 -->
     	<property name="sessionFactory" ref="sessionFactory"></property>
     </bean>	  	
     <!-- #3 dao -->  	
     <bean id="userDao" class="cn.tgb.dao.impl.UserDaoImpl">
     	<property name="hibernateTemplate" ref="hibernateTemplate"></property>
     </bean>
     <!-- #4 service -->  	
     <bean id="userService" class="cn.tgb.service.impl.UserServiceImpl">
     	<property name="userDao" ref="userDao"></property>
     </bean>
     
     <!-- #5 事務管理 -->
     <!-- #5.1事務管理器 -->
     <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
     	<!-- 必須確定sessionFactory。從而獲得session,再獲得事務 -->
     	<property name="sessionFactory" ref="sessionFactory"></property>
	 </bean>
	 
	 <!-- #5.2事務通知(增強),對指定目標方法進行增強 -->
	 <tx:advice id="txAdvice" transaction-manager="txManager">
	 	<tx:attributes>
	 		<tx:method name="add*"/>
	 		<tx:method name="update*"/>
	 		<tx:method name="delete*"/>
	 		<tx:method name="find*" read-only="true"/>
	 	</tx:attributes>	 
	 </tx:advice>	
	 
	 <!-- #5.3使用aop生成代理,進行增強 -->
	 <aop:config>
	 	<!-- 確定切入點 -->
	 	<aop:pointcut expression="execution(* cn.tgb.service..*.*(..))" id="txPointCut"/>
	 	<!-- 宣告切面 -->
	 	<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
	 </aop:config>				  
</beans>

    至此,Spring和Hibernate就算整合好了,下面編寫一個測試類測試下。


package cn.tgb.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.tgb.domain.User;
import cn.tgb.service.UserService;

public class TestApp {
	public static void main(String[] args) {
		
		//1.建立建使用者
		User user = new User();
		user.setUsername("jiangxiao");
		user.setPassword("123");
		
		//2.獲取Sping配置檔案
		String xmlPathString="applicationContext.xml";
		ApplicationContext applicationContext= new ClassPathXmlApplicationContext(xmlPathString);
		
		//3.通過Ioc獲得UserService
		UserService userService = (UserService) applicationContext.getBean("userService");
		
		//4.執行新增使用者操作
		userService.addUser(user);
	}
}

   

    分析總結:

    


    這張思維導圖大概介紹了一下配置檔案的配置內容和載入過程,其中藍色的雲朵部分是Spring整合Hibernate的內容。程式執行時,通過載入配置檔案,便將程式中所有的配置資訊都載入了。如果有個擴充套件修改什麼的也方便。日後會繼續介紹它們兩個與Struts的整合。


相關文章