java:hibernate集成到spring,我看网上都是把hibernate的配置直接写到applicationContext.xml里
能还用之前的hibernate.cfg.xml吗?我这样:<beanid="sessionFactory"class="org.springframework.orm.h...
能还用之前的hibernate.cfg.xml吗?
我这样:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
但是运行程序获取连接抛异常 展开
我这样:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
但是运行程序获取连接抛异常 展开
3个回答
展开全部
我为这个问题专门写了一个测试用例:
看下面的几个文件:
可能贴的顺序上有点问题,楼主可以自己整理一下:
(1) applicationContext.xml
---------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "">
<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>$</value></property>
<property name="jdbcUrl"><value>$</value></property>
<property name="user"><value>$</value></property>
<property name="password"><value>$</value></property>
<property name="initialPoolSize"><value>$</value></property>
<property name="minPoolSize"><value>$</value></property>
<property name="maxPoolSize"><value>$</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[];
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[];
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"
"">
<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");
}
}
确信是调通的,
==================
看在我专门为回答这个问题写了这个测试用例,
给个高分?
看下面的几个文件:
可能贴的顺序上有点问题,楼主可以自己整理一下:
(1) applicationContext.xml
---------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "">
<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>$</value></property>
<property name="jdbcUrl"><value>$</value></property>
<property name="user"><value>$</value></property>
<property name="password"><value>$</value></property>
<property name="initialPoolSize"><value>$</value></property>
<property name="minPoolSize"><value>$</value></property>
<property name="maxPoolSize"><value>$</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[];
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[];
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"
"">
<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");
}
}
确信是调通的,
==================
看在我专门为回答这个问题写了这个测试用例,
给个高分?
展开全部
不可以,你要把hibernate交给spring管理。。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2010-12-24
展开全部
<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.SQLServerDialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/struts/dao/menu.hbm.xml</value>
</list>
</property></bean>
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/struts/dao/menu.hbm.xml</value>
</list>
</property></bean>
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询