Spring与Hibernate结合

一、先来看代码


1.准备好所需要的Jar包

antlr-2.7.6.jar
aopalliance-1.0.jar
c3p0-0.9.1.2.jar
commons-collections-3.2.1.jar
commons-logging.jar
dom4j-1.6.1.jar
ejb3-persistence.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate3.jar
javassist-3.11.0.GA.jar
jta-1.1.jar
ojdbc6.jar
slf4j-api-1.6.1.jar
spring-aop-3.2.4.RELEASE.jar
spring-beans-3.2.4.RELEASE.jar
spring-context-3.2.4.RELEASE.jar
spring-core-3.2.4.RELEASE.jar
spring-expression-3.2.4.RELEASE.jar
spring-jdbc-3.2.4.RELEASE.jar
spring-orm-3.2.4.RELEASE.jar
spring-tx-3.2.4.RELEASE.jar

2.准备数据库

create table USER_INFO(
id number(8,0) primary key,
USERNAME varchar2(32),
PASSWORD varchar2(32)
);

3.准备实体类

package net.csdn.model;

/**
 * 实体类
 * @author Bowen
 *
 */
public class UserInfoEntity {
    /** ********** 成员变量 ********** **/
    //映射表中的id字段
    private int id;
    //映射表中的username字段
    private String username;
    //映射表中的password字段
    private String password;

    /** ********** Get方法 ********** **/
    public int getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    /** ********** Set方法 ********** **/
    public void setId(int id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }


}

4.准备映射文件




<hibernate-mapping package="net.csdn.model">
    <class name="UserInfoEntity" table="USER_INFO">
        <id name="id" column="ID"/>
        <property name="username" />
        <property name="password" />
    class>
hibernate-mapping>

5.重点:配置Spring配置文件


<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" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.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
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="oracle.jdbc.driver.OracleDriver" />
        <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl" />
        <property name="user" value="CNDS" />
        <property name="password" value="CNDS" />
        <property name="autoCommitOnClose" value="true" />
        <property name="checkoutTimeout" value="10000" />
        <property name="initialPoolSize" value="10" />
        <property name="minPoolSize" value="3" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
        <property name="acquireIncrement" value="3" />
        <property name="maxIdleTimeExcessConnections" value="1800" />
    bean>
    
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource">property>
        
        <property name="hibernateProperties">
            <props>
                
                <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialectprop>
                
                <prop key="hibernate.show_sql">trueprop>
                
                <prop key="hibernate.hbm2ddl.auto">updateprop>
            props>
        property>
        
        <property name="mappingLocations">
            <list>
                
                <value>classpath:net/csdn/model/*.hbm.xmlvalue>
            list>
        property>
    bean>
    
    
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        
        <property name="sessionFactory" ref="sessionFactory">property>
    bean>
    
    <tx:advice id="txAdvice" transaction-manager="txManager">
        
        <tx:attributes>
            
             
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
        tx:attributes>
    tx:advice>
    
    <aop:config>
        
        <aop:pointcut id="ap" expression="execution(* net.csdn.*.*(..))"/>
        
        <aop:advisor advice-ref="txAdvice" pointcut-ref="ap" />
    aop:config>
      
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"/>
    bean>

    <bean id="userInfoDaoImpl" class="net.csdn.dao.impl.UserInfoDaoImpl">
        <property name="hibernateTemplate" ref="hibernateTemplate"/>
    bean>

    <bean id="userInfoEntity" class="net.csdn.model.UserInfoEntity"/>

beans>

6.Dao层接口

package net.csdn.dao.inter;

import java.util.List;

import net.csdn.model.UserInfoEntity;
/**
 * Dao层接口
 * @author Bowen
 *
 */
public interface UserInfoDaoInter{
    /**
     * 保存
     * @param entity
     */
    public void save(UserInfoEntity entity);
    /**
     * 分页查询
     * @param hql
     * @param offset
     * @param length
     * @return
     */
    public List queryPage(final String hql,final int offset,final int length);
}

7.Dao层实现类

package net.csdn.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import net.csdn.dao.inter.UserInfoDaoInter;
import net.csdn.model.UserInfoEntity;

/**
 * Dao层实现类
 * @author Bowen
 *
 */
public class UserInfoDaoImpl implements UserInfoDaoInter{

    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
    /**
     * 保存方法
     */
    @Override
    public void save(UserInfoEntity entity){
        this.hibernateTemplate.save(entity);
    }
    /**
     * 这里举例一个常用的利用executeFind()方法获取到原始的session
     * 常用的比如分页查询便需要使用到这种方法
     * 在这个方法中用到了匿名类的应用
     * 注意要使用这个匿名类并且像里面传入变量,则必须将变量改为常量
     * 即使用final修饰
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public List queryPage(final String hql,final int offset,final int length){

        return this.hibernateTemplate.executeFind(new HibernateCallback(){
            @Override
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Query query = session.createQuery(hql);
                query.setFirstResult(offset);
                query.setMaxResults(length);
                return query.list();
            }
        });
    }






}

8.测试类

package net.csdn.test;

import java.util.List;

import net.csdn.dao.inter.UserInfoDaoInter;
import net.csdn.model.UserInfoEntity;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试类 通过Junit单元测试功能来实现测试
 * 
 * @author Bowen
 * 
 */
public class TestClass {
    //定义的Dao层接口
    private UserInfoDaoInter userInfoDaoInter;
    //定义的实体类
    private UserInfoEntity userInfoEntity;

    private ApplicationContext context;

    /**
     * 在测试前先注入
     */
    @Before
    public void init() {
        context = new ClassPathXmlApplicationContext("applicationContext.xml");
        this.userInfoDaoInter = (UserInfoDaoInter) context.getBean("userInfoDaoImpl");
        this.userInfoEntity = (UserInfoEntity) context.getBean("userInfoEntity");
    }
    /**
     * 测试保存方法
     */
    @Test
    public void testSave(){
        userInfoEntity.setId(1101);
        userInfoEntity.setUsername("csdn");
        userInfoEntity.setPassword("csdn");
        userInfoDaoInter.save(userInfoEntity);
    }
    /**
     * 测试分页查询
     */
    @Test
    public void testQueryPage(){
        List list = userInfoDaoInter.queryPage("from UserInfoEntity", 0, 3);
        for(UserInfoEntity userInfo:list){
            System.out.println(userInfo.getUsername());
        }
    }
}

9.最终目录结构图

Spring与Hibernate结合_第1张图片

二 、简述

Spring结合Hibernate可以有效的进行AOP(切面)结构的搭建,并且通过Spring的事务管理机制来管理Hibernate的事务从而提高开发效率

你可能感兴趣的:(java,Java每日)