Spring4整合Hibernate4.3

Spring还没学完,先整合Hibernate玩玩…

整合Hibernate所需jar包

这里写图片描述
如果缺少了spring-orm jar包
这里写图片描述

Spring核心配置文件
方式一: 在spring配置文件中配置hibernate属性
<?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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

        <!-- 定义数据源Bean, 使用C3p0数据源实现, 并注入数据源的必要信息 -->
        <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
            p:driverClass="com.mysql.jdbc.Driver"
            p:jdbcUrl="jdbc:mysql://localhost:3306/hibernate?useUnicode=true&amp;characterEncoding=UTF8&amp;useSSL=true"
            p:user="root"
            p:password="root"
            p:maxPoolSize="40"
            p:minPoolSize="2"
            p:initialPoolSize="2"
            p:maxIdleTime="30"/>
        <!-- 定义Hibernate的SessionFactory, SessionFactory需要依赖的数据源, 注入数据源 -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <property name="dataSource" ref="c3p0DataSource"/>
            <!-- 用来列出所有持久化类-->
            <property name="annotatedClasses">
                <list>
                    <!-- 持久化类的关联使用的是注解方式 -->
                    <value>pers.msidolphin.domain.User</value>
                </list>
            </property>
            <!-- 设置Hibernate配置文件 -->
            <property name="hibernateProperties">
                <props>    
                    <!-- 需要全部加上hibernate前缀 -->
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                    <prop key="hibernate.format_sql">true</prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.hbm2ddl.auto">update</prop> <!-- 这里很奇怪,改成了update才会自动建表 -->
                    <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
                </props>
            </property>
        </bean>

        <!-- 创建Dao对象 -->
        <bean id="userDao" class="pers.msidolphin.daoimpl.UserDao" p:sessionFactory-ref="sessionFactory"></bean>
        <!-- 创建Servive对象并注入dao对象 -->
        <bean id="userService" class="pers.msidolphin.service.UserService" p:dao-ref="userDao"></bean>

        <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
            <property name="sessionFactory" ref="sessionFactory" />  
        </bean> 

        <!-- 声明式事务 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="get*" read-only="true"/>
                <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" timeout="5"/>
            </tx:attributes>
        </tx:advice>

        <!-- AOP配置-->
        <aop:config>
            <!-- 给所有的service包的中类的所有方法织入事务控制增强 -->
            <aop:pointcut id="txPointcut" expression="execution(* pers.msidolphin.service.*.*(..))" />
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
        </aop:config>
</beans>
方式二:直接加载hibernate.cfg.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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

        <!-- 定义数据源Bean, 使用C3p0数据源实现, 并注入数据源的必要信息 -->
        <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
            p:driverClass="com.mysql.jdbc.Driver"
            p:jdbcUrl="jdbc:mysql://localhost:3306/hibernate?useUnicode=true&amp;characterEncoding=UTF8&amp;useSSL=true"
            p:user="root"
            p:password="root"
            p:maxPoolSize="40"
            p:minPoolSize="2"
            p:initialPoolSize="2"
            p:maxIdleTime="30"/>
        <!-- 定义Hibernate的SessionFactory, SessionFactory需要依赖的数据源, 注入数据源 -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" scope="singleton">
            <property name="dataSource" ref="c3p0DataSource"/>
            <property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
        </bean>

        <!-- 创建Dao对象 -->
        <bean id="userDao" class="pers.msidolphin.daoimpl.UserDao" p:sessionFactory-ref="sessionFactory"></bean>
        <!-- 创建Servive对象并注入dao对象 -->
        <bean id="userService" class="pers.msidolphin.service.UserService" p:dao-ref="userDao"></bean>

        <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
            <property name="sessionFactory" ref="sessionFactory" />  
        </bean> 

        <!-- 声明式事务 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="get*" read-only="true"/>
                <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" timeout="5"/>
            </tx:attributes>
        </tx:advice>

        <!-- AOP配置-->
        <aop:config>
            <!-- 给所有的service包的中类的所有方法织入事务控制增强 -->
            <aop:pointcut id="txPointcut" expression="execution(* pers.msidolphin.service.*.*(..))" />
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
        </aop:config>
</beans>

注意:在hibernate.cfg.xml配置文件中,current_session_context_class的值应该设置为org.springframework.orm.hibernate4.SpringSessionContext,因为spring提供了一个SpringSessionContext这个类来获得和管理session,如果写成其它的会导致spring无法帮你管理session,自己被这个问题困扰了一个多小时。。。

Dao:
import java.io.Serializable;

import org.hibernate.SessionFactory;

public class UserDao{

    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    public <T> T get(Class<T> entityClazz, Serializable id) {   
        return (T) sessionFactory.getCurrentSession().get(entityClazz, id);
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

}
Service:
public class UserService {

    private UserDao dao;

    public User getUser(Serializable id) {
        return dao.get(User.class, id);
    }

    public void setDao(UserDao dao) {
        this.dao = dao;
    }
}
测试类
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import pers.msidolphin.domain.User;
import pers.msidolphin.service.UserService;

public class TestClass {

    @Test
    public void testDao() {
        @SuppressWarnings("resource")
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService service = (UserService) ctx.getBean("userService");
        User user = service.getUser(1);
        System.out.println(user.getName());
    }
}
测试结果:

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值