38.Spring-spring和hibernate整合.md


目录

1.定义各种类对象

package per.liyue.sh.demo1;

/**
 * 此类对应数据库表person * 属性和表字段对应关系 *  private int personId:person_id    private String personName:person_name    private String personIdNumber:person_id_number
 */
public class Person
{
    private int personId;

    public int getPersonId()
    {
        return personId;
    }

    public void setPersonId(int personId)
    {
        this.personId = personId;
    }

    public String getPersonName()
    {
        return personName;
    }

    public void setPersonName(String personName)
    {
        this.personName = personName;
    }

    public String getPersonIdNumber()
    {
        return personIdNumber;
    }

    public void setPersonIdNumber(String personIdNumber)
    {
        this.personIdNumber = personIdNumber;
    }

    private String personName;
    private String personIdNumber;

    @Override
    public String toString()
    {
        return "身份信息: 名字:" + personName + " 号码:" + personIdNumber;
    }
}
package per.liyue.sh.demo1;

import org.hibernate.SessionFactory;

/**
 * Person类的Dao类
 */
public class PersonDao
{    //IOC   
    private SessionFactory sessionFactory;

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

    public void savePerson(Person person)
    {
        sessionFactory.getCurrentSession().save(person);
    }
}
package per.liyue.sh.demo1;

/**
 * Person类的Service类
 */
public class PersonService
{    //IOC    
    private PersonDao personDao;

    public void setPersonDao(PersonDao personDao)
    {
        this.personDao = personDao;
    }

    public void save(Person person)
    {
        personDao.savePerson(person);
    }
}

2.创建Hibernate配置文件

注意:有多种方式配置可以实现Spring和Hibernate的融合,但是这里只用Hibernate完全托管于Spring的方式,所以,不需要配置hibernate.cfg.xml文件。只需要配置表对应类的HIbernate配置文件既*.hbm.xml

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><!-- Generated Nov 9, 2006 6:27:53 PM by Hibernate Tools 3.2.0.beta7 --><!-- package:类对象所在的包     auto-import:表面是自动导入包,如果设定为false,则需要在执行hql语句时候将包名写清楚:     Demo:在true时候可以写为session.createQuery("from Employee").list();               在false时候必须写为session.createQuery("from per.liyue.code.hibernatehello.Employee").list(); -->
<hibernate-mapping package="per.liyue.sh.demo1"
                   auto-import="true">    
    <!-- 类与表的对应         
    name:类名称         
    table:表名称     -->
    <class name="Person" table="person">        
        <!-- 主键 注意和类成员和表列名称的一致对应 -->
        <id name="personId"
            column="person_id">           
            <!-- 主键的生成策略:                 
            1.identity  自增长(mysql,db2)                 
            2.sequence  自增长(序列), oracle中自增长是以序列方法实现                
            3.native  自增长【会根据底层数据库自增长的方式选择identity或sequence】                            
            如果是mysql数据库, 采用的自增长方式是identity                            
            如果是oracle数据库, 使用sequence序列的方式实现自增长                 
            4.increment  自增长(会有并发访问的问题,一般在服务器集群环境使用会存在问题。)                 
            5.assigned  指定主键生成策略为手动指定主键的值                 
            6.uuid      指定uuid随机生成的唯一的值                 
            7.foreign   (外键的方式, one-to-one讲)             
            -->
            <generator class="native"/>
        </id>        
        <!-- 非主键,同样一一映射            
         name:类的属性名称             
         column:表的字段名称             
         length:设定字段的长度,默认为255             
         type:设定映射表的类型,如果不写匹配类对应属性的类型                     
         java类型:必须带完整包名:java.lang.String                     
         hibernate类型:全部都是小写       
          -->
        <property name="personName" column="person_name"></property>
        <property name="personIdNumber" column="person_id_name"></property>
    </class>
</hibernate-mapping>

3.配置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/context        http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx.xsd        http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop.xsd">    <!--1.Hibernate配置-->    <!--a.数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///hi"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>    <!--b.SessionFactory        Spring框架负责SessionFactory的维护,所以不需要hibernate.cfg.xml    -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">        <!--i.数据源-->
        <property name="dataSource" ref="dataSource"></property>        <!--ii.基本配置:方言等-->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>        <!--iii.映射配置-->
        <property name="mappingLocations">
            <list>
                <value>classpath:per/liyue/sh/demo1/*.hbm.xml</value>
            </list>
        </property>
    </bean>    <!--c.事务配置-->    <!--i.事务管理器-->
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>    <!--ii.事务增强管理-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="save*"/>
        </tx:attributes>
    </tx:advice>    <!--iii.aop切面-->
    <aop:aspectj-autoproxy proxy-target-class="false"></aop:aspectj-autoproxy>
    <aop:config>
        <aop:pointcut id="pt" expression="execution(* per.liyue.sh.demo1.*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"></aop:advisor>
    </aop:config>    <!--2.IOC配置-->
    <bean id="person" class="per.liyue.sh.demo1.Person"></bean>
    <bean id="personDao" class="per.liyue.sh.demo1.PersonDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <bean id="personService" class="per.liyue.sh.demo1.PersonService">
        <property name="personDao" ref="personDao"></property>
    </bean>
</beans>

4.注意事项

  1. 在配置applicationContext的时候,事务配置中要注意,属性中注入的是SessionFactory。
  2. 配置项较多,配置的时候一定注意检查,否则容易出错
原文地址:https://www.cnblogs.com/bugstar/p/8513491.html