首页 > 学院 > 开发设计 > 正文

java框架篇---spring hibernate整合

2019-11-15 00:09:51
字体:
来源:转载
供稿:网友
java框架篇---sPRing hibernate整合

在会使用hibernate 和spring框架后 两个框架的整合就变的相当容易了,

为什么要整合Hibernate?1、使用Spring的IOC功能管理sessionFactory对象LocalSessionFactoryBean2、使用Spring管理Session对象HibernateTemplate3、使用Spring的功能实现声明式的事务管理

第一步:搭建hibernate环境(包括引入hibernate的jar,包配置数据源,建立类和表的映射),为什么这么做。我觉得hibernate是最重要的。因为没有spring不影响我往数据里面添加记录。Spring仅仅是一个容器。这就不多说了。

第二步:配置spring的环境(引入jar和写一个bean.xml的配置信息)

省略了hibernate.cfg.xml文件 全部托管于spring配置文件

在纯粹的Hibernate访问中,应用程序需要手动创建SessionFactory实例,可想而知,这不是一个优秀的策略。在实际开发中,希望以一种声明式的方式管理SessionFactory实例,直接以配置文件来管理SessionFactory实例,在示范Struts的PlugIn扩展点时,

Spring的IoC容器则提供了更好的管理方式,它不仅能以声明式的方式配置Session- Factory实例,也可充分利用IoC容器的作用,为SessionFactory注入数据源引用。

下面是Spring配置文件中配置Hibernate SessionFactory的示范代码:

<?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:aop="http://www.springframework.org/schema/aop"       xsi:schemaLocation="http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd           http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context-3.1.xsd           http://www.springframework.org/schema/aop                       http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  " default-autowire="byName">    <context:annotation-config />    <context:component-scan base-package="com.bjsxt" />    <!--     也可以使用这种方法        <bean id="dataSource"        class="org.apache.commons.dbcp.BasicDataSource"        destroy-method="close">                        <property name="driverClassName" value="com.MySQL.jdbc.Driver" />        <property name="url" value="jdbc:mysql://localhost:3306/myuse" />        <property name="username" value="root" />        <property name="passWord" value="root" />        </bean>    -->    <bean        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="locations">            <value>classpath:jdbc.properties</value>        </property>    </bean>    <bean id="dataSource" destroy-method="close"        class="org.apache.commons.dbcp.BasicDataSource">        <property name="driverClassName"            value="${jdbc.driverClassName}" />        <property name="url" value="${jdbc.url}" />        <property name="username" value="${jdbc.username}" />        <property name="password" value="${jdbc.password}" />    </bean>    <bean id="sessionFactory"        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <property name="annotatedClasses">            <list>                <value>com.bjsxt.model.User</value>            </list>        </property>        <property name="hibernateProperties">            <props>                <prop key="hibernate.dialect">                    org.hibernate.dialect.MySQLDialect                </prop>                <prop key="hibernate.show_sql">true</prop>            </props>        </property>    </bean></beans>

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc/:mysql/://localhost/:3306/myusejdbc.username=rootjdbc.password=root  

第三步:在spring里面注册hibernate。

<bean id="txManager"        class="org.springframework.orm.hibernate3.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory" />    </bean>    <tx:annotation-driven transaction-manager="txManager"/>

在Dao组件中,所有的持久化操作都通过HibernateTemplate实例完成,而HibernateTemplate操作数据库非常简洁,大部分CRUD操作都可通过一行代码解决问题。下面介绍如何通过HibernateTemplate进行持久层访问。

HibernateTemplate提供了非常多的常用方法来完成基本的操作,比如通常的增加、删除、修改、查询等操作,Spring 2.0更增加了对命名SQL查询的支持,也增加了对分页的支持。大部分情况下,使用Hibernate的常规用法,就可完成大多数DAO对象的CRUD操作。下面是HibernateTemplate的常用方法简介:

● void delete(Object entity),删除指定持久化实例。

● deleteAll(Collection entities),删除集合内全部持久化类实例。

● find(String queryString),根据HQL查询字符串来返回实例集合。

● findByNamedQuery(String queryName),根据命名查询返回实例集合。

● get(Class entityClass, Serializable id),根据主键加载特定持久化类的实例。

● save(Object entity),保存新的实例。

● saveOrUpdate(Object entity),根据实例状态,选择保存或者更新。

● update(Object entity),更新实例的状态,要求entity是持久状态。

● setMaxResults(int maxResults),设置分页的大小。

下面是一个完整DAO类的源代码:

测试:

package com.bjsxt.service;import org.junit.Test;import org.springframework.context.applicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.bjsxt.model.User;//Dependency Injection//Inverse of Controlpublic class UserServiceTest {    @Test     public void testAdd() throws Exception {        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");                UserService service = (UserService)ctx.getBean("userService");        System.out.println(service.getClass());        service.save(new User());                ctx.destroy();            }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表