关于Spring 2.5 和 Hibernate 3 基于Annotation的集成

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

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

首先定义Spring配置文件(也是最主要的一块),内容如下:
//spring.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"
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 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

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

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

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

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还需要更进一步的学习~~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值