Spring与Hibernate三种整合方式

本文主要是介绍Spring和Hibernate三种整合方式的配置文件,即在DAO层注入问题,仅当做自己的一次笔记

applicationContext.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:config.properties" />

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.zhihua.*" />
    <context:annotation-config />

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>

        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>

    <!-- 配置Hibernate的SessionFactory,通过spring提供的 LocalSessionFactoryBean配置 -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 配置依赖的数据源属性 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- hibernate配置文件的路径 -->
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <!-- 配置hibernate映射文件的路径,可以使用通配符 -->
        <property name="mappingLocations" value="classpath:com/zhihua/entity/*.hbm.xml"></property>
    </bean>

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

    <!-- 配置Spring的声明式事务 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/> 
    <!-- 配置事物属性 ,需要事物管理器 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED" />
            <tx:method name="find*" read-only="true" propagation="NOT_SUPPORTED" />
            <tx:method name="select*" read-only="true" propagation="NOT_SUPPORTED" />
            <tx:method name="query*" read-only="true" propagation="NOT_SUPPORTED" />
            <tx:method name="save*" propagation="REQUIRED" rollback-for="Throwable" />
            <tx:method name="insert*" propagation="REQUIRED" rollback-for="Throwable" />
            <tx:method name="add*" propagation="REQUIRED" rollback-for="Throwable" />
            <tx:method name="update*" propagation="REQUIRED" rollback-for="Throwable" />
            <tx:method name="delete*" propagation="REQUIRED" rollback-for="Throwable" />
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>

    <!-- 配置事物切点,并把事物属性和切点关联起来 -->
    <aop:config>
        <aop:pointcut
            expression="execution(* com.zhihua.service.impl.*.*(..))"
            id="txPointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
    </aop:config>

</beans>

1、直接注入SessionFactory

package com.zhihua.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.zhihua.dao.StudentDao;
import com.zhihua.entity.Student;
import com.zhihua.page.Page;

@Repository("studentDaoImp")
public class StudentDaoImp implements StudentDao{

    @Autowired
    private SessionFactory sessionFactory;

    /**
     * 获取当前线程绑定的session
     * <请替换成功能描述> <br>
     * <请替换成详细描述>
     * @return
     * @author caizh
     * @since [1.0.0]
     * @version [1.0.0,2017年2月22日]
     */
    private Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    /**
     * 根据用户名和密码查询
     */
    @Override
    public Student findByNameAndPwd(String sname, String password) {
        String hql = "from Student where sname=:sname and password=:password";
        Query query = this.getSession().createQuery(hql);
        query.setParameter("sname", sname);
        query.setParameter("password",password);
        return (Student) query.uniqueResult();
    }

    /**
     * 查询所有,立即加载
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Student> findAll() {
        String hql = "from Student";
        Query query = this.getSession().createQuery(hql);
        return query.list();
    }

    /**
     * 保存
     */
    @Override
    public int save(Student student) {
        int num = 1;
        try{
            Session session = this.getSession();           
            session.save(student);
        }catch(HibernateException e){
            num = 0;
            e.printStackTrace();
        }
        return num;
    }

    /**
     * 根据主键查询
     */
    @Override
    public Student findById(Integer sid) {
        /**
         * 因为在修改时要提前查询单条,和session关联已经变成持久化对象,
         * 而在修改时session执行update方法时
         * 首先会查询该主键id是否存在
         * 如果存在,则根据主键id修改
         */
        return (Student) this.getSession().get(Student.class, sid);
    }

    /**
     * 修改
     * <请替换成功能描述> <br>
     * <请替换成详细描述>
     * @param stu
     * @return
     * @author caizh
     * @since [1.0.0]
     * @version [1.0.0,2017年2月23日]
     */
    @Override
    public int update(Student stu) {
        int num = 1;
        try{
            Session session = this.getSession();           
            session.update(stu);
        }catch(HibernateException e){
            e.printStackTrace();
            num = 0;
        }
        return num;
    }

    /**
     * 删除
     * <请替换成功能描述> <br>
     * <请替换成详细描述>
     * @param stu
     * @return
     * @author caizh
     * @since [1.0.0]
     * @version [1.0.0,2017年2月23日]
     */
    @Override
    public int delete(Student stu) {
        int num = 1;
        try{
            Session session = this.getSession();          
            session.delete(stu);            
        }catch(HibernateException e){
            e.printStackTrace();
            num = 0;
        }
        return num;
    }

    /**
     * 分页查询
     * <请替换成功能描述> <br>
     * <请替换成详细描述>
     * @param page
     * @return
     * @author caizh
     * @since [1.0.0]
     * @version [1.0.0,2017年2月23日]
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Student> findPage(Page page) {
        //获取session
        Session session = this.getSession();
        //定义查询的最大记录数的hql
        String hql = "from Student";
        //定义查询最大记录数的Query对象
        Query queryPage = session.createQuery(hql);
        //查询最大记录数的数据
        queryPage.setMaxResults(page.getPagesize());
        //确定查询起点
        queryPage.setFirstResult(page.getStartrow());
        //分页查询
        return queryPage.list();
    }

    /**
     * 查询总条数
     * <请替换成功能描述> <br>
     * <请替换成详细描述>
     * @return
     * @author caizh
     * @since [1.0.0]
     * @version [1.0.0,2017年2月23日]
     */
    @Override
    public int getTotalCount() {
        //获取session
        Session session = this.getSession();
        //定义查询总条数hql语句
        String hqlCount = "select count(*) from Student";
        //利用session创建Query对象
        Query queryCount = session.createQuery(hqlCount);
        //获取总条数(返回单行数据uniqueResult)
        Integer totalCount = Integer.parseInt(queryCount.uniqueResult().toString());
        return totalCount;
    }

    @Override
    public int getConnection() {

        return 0;
    }

}

2、直接注入HibernateTemplate

package com.zhihua.dao.impl;

import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.zhihua.entity.Account;

@Repository("accountDao")
public class AccountDaoImp {

    @Autowired
    private HibernateTemplate hibernateTemplate;

    @Transactional
    public void queryById(int id){
        Account account = new Account();
        String sql = "select count(1) from Account";
        Query query = hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(sql);
        Integer count =  Integer.parseInt(query.uniqueResult().toString());
        System.out.println(count);
    }

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountDaoImp accountDaoImp = (AccountDaoImp) context.getBean("accountDao");
        accountDaoImp.queryById(1);

    }
}

3、使用 HibernateDaoSupport

package com.zhihua.dao.impl;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.zhihua.entity.Account;

@Repository("accountDao2")
public class AccountDaoImp2 extends HibernateDaoSupport{

    @Resource(name="sessionFactory")  
    public void setSuperSessionFactory(SessionFactory sessionFactory){  
        super.setSessionFactory(sessionFactory);  
    } 

    //  或者为其注入hibernateTemplate  
//    @Resource(name="hibernateTemplate")  
//    public void setSuperHibernateTemplate(HibernateTemplate hibernateTemplate){  
//        super.setHibernateTemplate(hibernateTemplate);  
//    }  

    @Transactional
    public void queryById(int id){
        Account account = new Account();
        String sql = "select count(1) from Account";
        Query query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(sql);
        Integer count =  Integer.parseInt(query.uniqueResult().toString());
        System.out.println("一共有记录数:"+count);
    }

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountDaoImp2 accountDaoImp = (AccountDaoImp2) context.getBean("accountDao2");
        accountDaoImp.queryById(1);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值