`

Spring 2.5 和 Hibernate 3 基于Annotation的集成

    博客分类:
  • SSH
阅读更多

网上的例子不少,但没有一个是说的很清楚的,而且有的例子和我的目标不同,于是自己尝试着配了一下~

目标:尽量多的使用Annotation,完成事务自动管理
版本:Spring-2.5.6 Hibernate-3.3.1及相关的包

首先定义Spring配置文件(也是最主要的一块),内容如下:
//spring.xml

Xml代码 复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3.     xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xsi:schemaLocation="   
  8.         http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
  10.         http://www.springframework.org/schema/context   
  11.         http://www.springframework.org/schema/context/spring-context-2.5.xsd   
  12.         http://www.springframework.org/schema/tx   
  13.         http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"   
  14.     default-autowire="autodetect"  
  15. >  
  16.   
  17.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  18.         <property name="driverClassName" value="org.postgresql.Driver"/>  
  19.         <property name="url" value="jdbc:postgresql://localhost/demo"/>  
  20.         <property name="username" value="demo"/>  
  21.         <property name="password" value="demo"/>  
  22.     </bean>  
  23.        
  24.     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  25.         <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />  
  26.         <property name="configLocations" value="hibernate.model.xml" />  
  27.         <property name="hibernateProperties">  
  28.             <props>  
  29.                 <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>  
  30.                 <prop key="hibernate.show_sql">true</prop>  
  31.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  32.             </props>  
  33.         </property>  
  34.     </bean>  
  35.        
  36.     <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" />  
  37.        
  38.     <context:component-scan base-package="com.itone.spring.demo.service">  
  39.         <context:include-filter type="regex" expression=".*ServiceImpl" />    
  40.     </context:component-scan>  
  41.        
  42.     <tx:annotation-driven transaction-manager="txManager"/>  
  43.        
  44. </beans>  
<?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"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-2.5.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
	default-autowire="autodetect"
>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="org.postgresql.Driver"/>
		<property name="url" value="jdbc:postgresql://localhost/demo"/>
		<property name="username" value="demo"/>
		<property name="password" value="demo"/>
	</bean>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
		<property name="configLocations" value="hibernate.model.xml" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
	</bean>
	
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" />
	
	<context:component-scan base-package="com.itone.spring.demo.service">
		<context:include-filter type="regex" expression=".*ServiceImpl" /> 
	</context:component-scan>
	
	<tx:annotation-driven transaction-manager="txManager"/>
	
</beans>



由于Hibernate model的定义一般会很多(本例不多,呵呵),所以我把它放到另一个文件中,代码如下:
//hibernate.model.xml

Xml代码 复制代码
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC   
  3.     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"   
  4.     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.     <session-factory>  
  8.         <mapping class="com.itone.spring.demo.model.Book"/>  
  9.     </session-factory>  
  10. </hibernate-configuration>  
<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<mapping class="com.itone.spring.demo.model.Book"/>
	</session-factory>
</hibernate-configuration>



这里需要注意的几点:
1、是要加上命名空间tx,因为我们用到了tx:annotation-driven;
2、default-autowire="autodetect"或default-autowire="byName",因为我不知道怎么将sessionFactory或hibernateTemplate annotate到我的ServiceImpl中;
3、要用接口/实现的方式来做Service。

看一下我们的Hibernate model代码吧,很简单,代码如下:
//Book.java

Java代码 复制代码
  1. package com.itone.spring.demo.model;   
  2.   
  3. import java.io.Serializable;   
  4.   
  5. import javax.persistence.Entity;   
  6. import javax.persistence.GeneratedValue;   
  7. import javax.persistence.GenerationType;   
  8. import javax.persistence.Id;   
  9.   
  10. import org.hibernate.annotations.Proxy;   
  11.   
  12. @Entity  
  13. @Proxy(lazy = false)   
  14. public class Book implements Serializable {   
  15.   
  16.     private static final long serialVersionUID = 1L;   
  17.   
  18.     @Id  
  19.     @GeneratedValue(strategy = GenerationType.IDENTITY)   
  20.     public int id;   
  21.   
  22.     public String name;   
  23. }  
package com.itone.spring.demo.model;

import java.io.Serializable;

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

import org.hibernate.annotations.Proxy;

@Entity
@Proxy(lazy = false)
public class Book implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public int id;

	public String name;
}



接下来就是服务接口及实现了,只做读和写操作,以验证@Transactional是否起作用。
//BookService.java

Java代码 复制代码
  1. package com.itone.spring.demo.service;   
  2.   
  3. import java.util.List;   
  4.   
  5. import com.itone.spring.demo.model.Book;   
  6.   
  7. public interface BookService {   
  8.   
  9.     public void save(Book book) throws Exception;   
  10.   
  11.     public List<Book> list() throws Exception;   
  12. }  
package com.itone.spring.demo.service;

import java.util.List;

import com.itone.spring.demo.model.Book;

public interface BookService {

	public void save(Book book) throws Exception;

	public List<Book> list() throws Exception;
}



//BookServiceImpl.java

Java代码 复制代码
  1. package com.itone.spring.demo.service;   
  2.   
  3. import java.util.List;   
  4.   
  5. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;   
  6. import org.springframework.stereotype.Service;   
  7. import org.springframework.transaction.annotation.Transactional;   
  8.   
  9. import com.itone.spring.demo.model.Book;   
  10.   
  11. @Service("bookService")   
  12. public class BookServiceImpl extends HibernateDaoSupport implements BookService {   
  13.   
  14.     @Transactional(readOnly = false, rollbackFor = Throwable.class)   
  15.     public void save(Book book) throws Exception {   
  16.         getHibernateTemplate().save(book);   
  17.         //throw new Exception("test exception");这样会回滚   
  18.     }   
  19.   
  20.     @SuppressWarnings("unchecked")   
  21.     @Transactional(readOnly = true, rollbackFor = Throwable.class)   
  22.     public List<Book> list() throws Exception {   
  23.                 //这里如果有写操作也会出异常   
  24.         return getSession().createCriteria(Book.class).list();   
  25.     }   
  26. }  
package com.itone.spring.demo.service;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itone.spring.demo.model.Book;

@Service("bookService")
public class BookServiceImpl extends HibernateDaoSupport implements BookService {

	@Transactional(readOnly = false, rollbackFor = Throwable.class)
	public void save(Book book) throws Exception {
		getHibernateTemplate().save(book);
		//throw new Exception("test exception");这样会回滚
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<Book> list() throws Exception {
                //这里如果有写操作也会出异常
		return getSession().createCriteria(Book.class).list();
	}
}



然后来做个测试吧
//Test.java

Java代码 复制代码
  1. package com.itone.spring.demo;   
  2.   
  3. import java.util.List;   
  4.   
  5. import org.springframework.context.ApplicationContext;   
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;   
  7.   
  8. import com.itone.spring.demo.model.Book;   
  9. import com.itone.spring.demo.service.BookService;   
  10.   
  11. public class Test {   
  12.     public static void main(String[] args) throws Exception {   
  13.         ApplicationContext ctx = new ClassPathXmlApplicationContext(   
  14.                 new String[] { "spring.xml" });   
  15.   
  16.         BookService bookService = (BookService) ctx.getBean("bookService");   
  17.   
  18.         Book book = new Book();   
  19.         book.name = "血色浪漫";   
  20.         bookService.save(book);   
  21.   
  22.         List<Book> books = bookService.list();   
  23.         for (Book b : books) {   
  24.             System.out.println(b.id + ":" + b.name);   
  25.         }   
  26.     }   
  27. }  
package com.itone.spring.demo;

import java.util.List;

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

import com.itone.spring.demo.model.Book;
import com.itone.spring.demo.service.BookService;

public class Test {
	public static void main(String[] args) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				new String[] { "spring.xml" });

		BookService bookService = (BookService) ctx.getBean("bookService");

		Book book = new Book();
		book.name = "血色浪漫";
		bookService.save(book);

		List<Book> books = bookService.list();
		for (Book b : books) {
			System.out.println(b.id + ":" + b.name);
		}
	}
}



然后的任务就是来改动BookServiceImpl的Annotation设置及代码,来检验一下是否起作用了,我发现是起作用的。

这里只写了一个简单的模型,对于Spring的Annotation还需要更进一步的学习~~

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics