首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

spring 与Hibernate集成的配备

2012-12-24 
spring 与Hibernate集成的配置首先建个web项目,导入所需要的包,包名在这列出:hibernate3.3所用到的jar包:a

spring 与Hibernate集成的配置
首先建个web项目,导入所需要的包,包名在这列出:

hibernate3.3所用到的jar包:antlr-2.7.6.jar                   开源语法分析生成器(lib\required)commons-collections-3.1.jar       Commons集合类库,与连接池有关(lib\required)dom4j-1.6.1.jar                   xml解析类库(lib\required)javassist-3.9.0.GA.jar            分析,编辑和创建java字节码类库(lib\required)jta-1.1.jar                       事务处理api   (lib\required)        slf4j-api-1.5.8.jar               日志处理 (lib\required)-->用log4j实现hibernate3.jar                    核心ehcache-1.2.3.jar                 二级缓存(lib\optional\ehcache)Spring2.5安装包所用的jar包:dist\spring.jarlib\aspectj\aspectjweaver.jar、aspectjrt.jarlib\cglib\cgligb-nodep-2.1_3.jarlib\j2ee\common-annotations.jarlib\jakarta-commons\commons-logging.jar 、commons-dbcp.jar、commons-pool.jarlib\log4j\log4j-1.2.15.jar   供srping与hibernate使用的日志记录jar包lib\slf4j\ slf4j-log4j12-1.5.0.jar  日志转换jar包,实现把log4j.jar包适配到slf4j标准。


当然你可以根据自己的需要导入其他的包,这个也不一定是什么标准,看需要来配。


然后建个POJO:
package com.xll.bean;public class User {private String name;private Integer id;// getter & setter }


这里我没使用hibernate 注解,所以手动创建相应的.hbm.xml文件

<?xml version="1.0"?><!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.xll.bean.User"><id name="id"><generator /></class>         </hibernate-mapping>


然后建立相应的service及实现类:
package com.xll.service;import java.util.List;import com.xll.bean.User;public interface UserService {public void save(User user);public void delete(Integer id);public void update(User user);public User getUser(Integer id);public List<User> getUsers();}



实现类:
package com.xll.service.impl;import java.util.List;import org.hibernate.SessionFactory;import org.springframework.orm.hibernate3.HibernateTemplate;import com.xll.bean.User;import com.xll.service.UserService;public class UserServiceBean implements UserService{ private HibernateTemplate hibernateTemplate;    public void setSessionFactory(SessionFactory sessionFactory) {        this.hibernateTemplate = new HibernateTemplate(sessionFactory);    }public void save(User user) {hibernateTemplate.save(user);}public void delete(Integer id) {}public User getUser(Integer id) {return null;}public List<User> getUsers() {return null;}public void update(User user) {}}

这里我先只实现一个方法,跑起来再说。

然后在spring的主配置文件中进行配置了,这里我采用的是将Hibernate的sessionfactory注入到服务层实现类当中,初始化spring提供的HibernateTemplate

主配置如下:
<?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: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-2.5.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- 配置数据源 -->    <bean id="theDataSource"          value="com.mysql.jdbc.Driver" />               <property name="url" value="jdbc:mysql://localhost:3306/ssh" />               <property name="username" value="root" />               <property name="password" value="123" />               <property name="initialSize" value="2" />               <property name="maxActive" value="100" />               <property name="maxIdle" value="2" />               <property name="minIdle" value="1" />       </bean>      <!-- 事务管理-->           <bean id="txManager" ref="theDataSource" />           </bean>                <!-- 开启事务注解   -->         <tx:annotation-driven transaction-manager="txManager" />        <!-- Hibernate SessionFactory -->        <bean id="mySessionFactory" ref="theDataSource"/>   <property name="mappingResources">   <list>   <value>com/xll/bean/User.hbm.xml</value>   </list>   </property>   <property name="hibernateProperties">   <value>   hibernate.dialect=org.hibernate.dialect.MySQLDialecthibernate.hbm2ddl.auto=updatehibernate.show_sql=truehibernate.format_sql=true   </value>   </property>   </bean>         <bean id="userServiceBean" ref="mySessionFactory">   </property>   </bean></beans>


好了,代码一上,一目了然,下面进行测试:

package com.xll.impl.test;import org.junit.BeforeClass;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import com.xll.bean.User;import com.xll.service.UserService;public class TestUser {private static UserService us;@BeforeClasspublic static void  setUpBeforeClass() throws Exception{ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml"); us = (UserService)ctx.getBean("userServiceBean");}@Testpublic void testSave(){User u = new User();u.setName("xiaoliang");us.save(u);}}



跑起来了,结果如下:
08:37:38,343  INFO SchemaUpdate:155 - Running hbm2ddl schema update08:37:38,343  INFO SchemaUpdate:167 - fetching database metadata08:37:38,343  INFO SchemaUpdate:179 - updating schema08:37:38,375  INFO DatabaseMetadata:119 - table not found: User08:37:38,375  INFO DatabaseMetadata:119 - table not found: User08:37:38,375 DEBUG SchemaUpdate:203 - create table User (id integer not null, name varchar(255), primary key (id))08:37:38,437  INFO SchemaUpdate:217 - schema update complete[b]Hibernate:     select        max(id)     from        UserHibernate:     insert     into        User        (name, id)     values        (?, ?)[/b]


插入成功!


再来看看我的事务功能起作用了没,在service实现类的save()中做如下修改,先不添加事务功能,
// @Transactionalpublic void save(User user) {hibernateTemplate.save(user);int i = 10/0;}


运行下测试类控制台打印:
08:40:37,140  INFO SchemaUpdate:155 - Running hbm2ddl schema update08:40:37,140  INFO SchemaUpdate:167 - fetching database metadata08:40:37,140  INFO SchemaUpdate:179 - updating schema08:40:37,171  INFO TableMetadata:65 - table found: ssh.user08:40:37,171  INFO TableMetadata:66 - columns: [id, name]08:40:37,171  INFO TableMetadata:68 - foreign keys: []08:40:37,171  INFO TableMetadata:69 - indexes: [primary]08:40:37,171  INFO SchemaUpdate:217 - schema update complete[b]Hibernate:     select        max(id)     from        UserHibernate:     insert     into        User        (name, id)     values        (?, ?)[/b]


且Junit红条,除零异常!但数据插入成功...


接下来开启事务功能,
@Transactionalpublic void save(User user) {hibernateTemplate.save(user);int i = 10/0;}


测试结果:
08:43:17,140  INFO SchemaUpdate:155 - Running hbm2ddl schema update08:43:17,140  INFO SchemaUpdate:167 - fetching database metadata08:43:17,156  INFO SchemaUpdate:179 - updating schema08:43:17,203  INFO TableMetadata:65 - table found: ssh.user08:43:17,203  INFO TableMetadata:66 - columns: [id, name]08:43:17,203  INFO TableMetadata:68 - foreign keys: []08:43:17,203  INFO TableMetadata:69 - indexes: [primary]08:43:17,203  INFO SchemaUpdate:217 - schema update complete[b]Hibernate:     select        max(id)     from        User[/b]


同时也抛出除零异常,以及还有别的异常,这时数据没有插入数据库,事务回滚功能成功!

热点排行