1,我们如果没有加spring的配置式事务,那么你的这个session是要手动关闭的。
2,我们在使用spring+hibernate的时候,不一定非得获得session,再做数据库操作,我们可以直接用 getHibernateTemplate().xxx 来做数据库的操作。
3,建议使用配置式事务,这样session 的创建和关闭都由spring容器管理,
我们的代码量将减少很多。
我这里给一个spring + hibernate ,使用配置事务的简单例子:
看下面的几个文件:
可能贴的顺序上有点问题,楼主可以自己整理一下:
(1) applicationContext.xml
---------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "
http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- 引入参数配置文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>jdbc.properties</value>
</list>
</property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass"><value>${jdbc.driverClass}</value></property>
<property name="jdbcUrl"><value>${jdbc.url}</value></property>
<property name="user"><value>${jdbc.user}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
<property name="initialPoolSize"><value>${jdbc.initialPoolSize}</value></property>
<property name="minPoolSize"><value>${jdbc.minPoolSize}</value></property>
<property name="maxPoolSize"><value>${jdbc.maxPoolSize}</value></property>
</bean>
<!-- spring Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.jdbc.fetch_size">80</prop>
<prop key="hibernate.jdbc.batch_size">35</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/spring/demo/bean/mapping/Book.hbm.xml</value>
</list>
</property>
</bean>
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<!-- 事务代理拦截器的配置 -->
<bean id="baseTransactionProxy" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="hibernate_BookDao" class="com.spring.demo.dao.Hibernate_BookDao" >
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="hibernate_BookManager" parent="baseTransactionProxy">
<property name="target">
<bean class="com.spring.demo.manager.Hibernate_BookManager">
<property name="dao">
<ref bean="hibernate_BookDao"/>
</property>
</bean>
</property>
</bean>
</beans>
---------------------
(2) jdbc.properties
## 这个事连接mysql数据库的具体参数配置,
## 楼主要根据自己的数据来配置,不可直接使用
---------------------
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdemo?useUnicode=true&characterEncoding=utf-8
jdbc.user=root
jdbc.password=root
jdbc.initialPoolSize=1
jdbc.minPoolSize=1
jdbc.maxPoolSize=10
---------------------
说明:applicationContext.xml 应用了jdbc.properties文件
,我自己测试,没有问题,而且是spring配置式事务的。
需要JAR包
spring.jar
c3p0.jar
mysql.jar
cglib.jar
asm.jar
antlr.jar
hibernate3.jar
jta.jar
dom4j.jar
commons-collections.jar
commons-logging.jar
-----------
Hibernate_BookDao.java
--------------
package com.spring.demo.dao;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.spring.demo.bean.Book;
/**
*
* @author wangyudong
*
*/
public class Hibernate_BookDao extends HibernateDaoSupport {
/**
* 添加一本书
* @param book
*/
public void insertBook(Book book){
this.getHibernateTemplate().save(book);
}
/**
* 修改一本书
* @param book
*/
public void updateBook(Book book){
this.getHibernateTemplate().update(book);
}
/**
* 根据ID来删除一本书
* @param id
*/
public void deleteBook(Integer id){
Book book = new Book();
book.setId(id);
this.getHibernateTemplate().delete(book);
}
/**
* 根据ID来查询书对象
* @param id
* @return
*/
public Book selectBookById(Integer id){
String hql = "from Book b where b.id=?";
Object[] params = new Object[]{id};
List list = this.getHibernateTemplate().find(hql, params );
if(list!=null && list.size()>0){
return (Book)list.get(0);
}
return null ;
}
/**
* 根据书名来查询相关书记录列表
* @param name
* @return
*/
public List selectBookByName(String name){
String hql = "from Book b where b.name like ?";
Object[] params = new Object[]{"%"+name+"%"};
return this.getHibernateTemplate().find(hql, params);
}
}
--------------
(2) Hibernate_BookManager.java
---------------
package com.spring.demo.manager;
import java.util.List;
import com.spring.demo.bean.Book;
import com.spring.demo.dao.Hibernate_BookDao;
public class Hibernate_BookManager {
private Hibernate_BookDao dao ;
/**
* 批量添加书本,如果列表长度超过3,就抛出异常
* @param books
*/
public void insertBooks(List books){
for(int i=0 ; i<books.size() ;i++){
if(i>2){
throw new RuntimeException("中断事务异常,当列表长度大于3的时候故意抛出,看看事务是否回滚");
}
Book book = (Book)books.get(i);
dao.insertBook(book);
}
}
/**
* 添加一本书
* @param book
*/
public void insertBook(Book book){
this.dao.insertBook(book);
}
/**
* 修改一本书
* @param book
*/
public void updateBook(Book book){
this.dao.updateBook(book);
}
/**
* 根据ID来删除一本书
* @param id
*/
public void deleteBook(Integer id){
this.dao.deleteBook(id);
}
/**
* 根据ID来查询书对象
* @param id
* @return
*/
public Book selectBookById(Integer id){
return this.dao.selectBookById(id);
}
/**
* 根据书名来查询相关书记录列表
* @param name
* @return
*/
public List selectBookByName(String name){
return this.dao.selectBookByName(name);
}
// getter and setter //
public Hibernate_BookDao getDao() {
return dao;
}
public void setDao(Hibernate_BookDao dao) {
this.dao = dao;
}
}
---------------
(3)Book.java
--------------
package com.spring.demo.bean;
import java.io.Serializable;
/*
DROP TABLE IF EXISTS book ;
CREATE TABLE book(
id int(11) NOT NULL auto_increment COMMENT 'primary key',
name varchar(60) default NULL COMMENT 'book name',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='my book table';
*/
public class Book implements Serializable {
public Book(){}
public Book(String name){
this.name = name;
}
/**
* ID
*/
private Integer id ;
/**
* 书名
*/
private String name ;
// getter and setter
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
--------------
(4)Book.hbm.xml
---------------
<?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.spring.demo.bean.Book" table="BOOK" >
<id name="id" type="integer" length="11">
<column name="id" />
<generator class="identity" />
</id>
<property name="name" column="NAME" type="string" length="60" ></property>
</class>
</hibernate-mapping>
---------------
#mysql的造表语句,指定了数据库springdemo#
---------------------
MYSQL 的BOOK 表创建语句
CREATE DATABASE IF NOT EXISTS springdemo;
USE springdemo;
DROP TABLE IF EXISTS book ;
CREATE TABLE book(
id int(11) NOT NULL auto_increment COMMENT 'primary key',
name varchar(60) default NULL COMMENT 'book name',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='my book table';
---------------------
下面是我的测试方法:
===========
package com.spring.demo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.demo.bean.Book;
import com.spring.demo.manager.Hibernate_BookManager;
public class HibernateDemo {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml") ;
Hibernate_BookManager manager = (Hibernate_BookManager)context.getBean("hibernate_BookManager");
List books = new ArrayList();
books.add(new Book("book_01"));
books.add(new Book("book_02"));
books.add(new Book("book_03"));
books.add(new Book("book_04"));
manager.insertBooks(books);
System.out.println("OK");
}
}
确信是调通的,
==================