Spring 与Hibernate 整合

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring 与Hibernate 整合相关的知识,希望对你有一定的参考价值。

Hibernate 与Spring整合,还需要一个支持整合的jar包.
spring-orm-3.2.0.RELEASE.jar
整合方式之一引入式整合: 使用Hibernate.cfg.xml文件1.在src目录下创建一个UserModle的实体类
UserModle:

public class UserModle {

   public String name;
   public Integer age;
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public Integer getAge() {
       return age;
   }
   public void setAge(Integer age) {
       this.age = age;
   }

   }

2.编写与之对应的映射文件UserModle.hbm.xml
UserModle.hbm.xml:


<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC
            ‘-//Hibernate/Hibernate Mapping DTD 3.0//EN‘
            ‘http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd‘>
    <hibernate-mapping >
        <class name="cn.fy.domain.UserModle" table="tbl_user" >
            <id name="uuid">
                <generator class="native" />
            </id>
            <property name="name"/>
            <property name="age"/>
        </class>
    </hibernate-mapping>

3.在Hibernate的核心配置文件Hibernate.cfg.xml中添加次映射文件信息
Hibernate.cfg.xml:

<?xml version=‘1.0‘ encoding=‘utf-8‘?>
   <!DOCTYPE hibernate-configuration PUBLIC
           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
           "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
   <hibernate-configuration>
       <session-factory>
           <!-- 连接mysql数据库, 使用jdbc -->
           <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
           <property name="connection.url">jdbc:mysql://localhost:3306/ssh</property>
           <property name="connection.username">root</property>
           <property name="connection.password">123456</property>
           <!--mysql方言 -->
           <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
           <!--显示sql语句,以及格式化语句 -->
           <property name="show_sql">true</property>
           <property name="format_sql">false</property>

       <!-- <mapping resource="添加自定义的hbm.xml文件" /> -->
           <mapping resource="cn/fy/domain/UserModel.hbm.xml" />
   </session-factory>

</hibernate-configuration>
4.在src下创建dao包.在该包下创建接口UserDao以及UserDaoImpl
UserDao:

public interface UserDao {

          /**
           * 添加用户
           *
           * @param um  用户
           */
          void save(UserModle um);

          /**
           *  删除用户
           * @param um  删除的用户
           */
          void delete(UserModle um);

          /**
           * 更新用户
           * @param um  更新的用户
           */
          void update(UserModle um);

          /**
           *  根据id查找用户
           * @param id  用户id
           * @return  返回当前用户
           */
          UserModle findById(Integer id);

          /**
           * 查找所有用户
           * @return
           */
          List<UserModle> findAll();
          }

UserDaoImpl:

public class UserDaoImpl implements UserDao {
// 提供Hibernate模版
private HibernateTemplate hibTemplate;

  public void setHibernateTemplate(HibernateTemplate temp) {

      this.hibTemplate = temp;
  }

  public void save(UserModle um) {

      hibTemplate.save(um);
  }

  public void delete(UserModle um) {

      hibTemplate.delete(um);
  }

  public void update(UserModle um) {

      hibTemplate.update(um);
  }

  public UserModle findById(Integer id) {

      return hibTemplate.get(UserModle.class, id);
  }

  public List<UserModle> findAll() {

      return hibTemplate.find("from UserModle");
  }

}
5.在src下创建service包.在该包下创建接口UserService以及UserServiceImpl
UserServic:

public interface UserService {

    /**
     * 保存用户
     *
     * @param um
     */
    void savaUser(UserModle um);

    /**
     * 删除用户
     *
     * @param um
     *            删除的用户
     */
    void deleteUser(UserModle um);

    /**
     * 更新用户
     *
     * @param um
     *            更新的用户
     */
    void updateUser(UserModle um);

    /**
     * 根据id查找用户
     *
     * @param id
     *            用户id
     * @return 返回当前用户
     */
    UserModle findUserById(Integer id);

    /**
     * 查找所有用户
     *
     * @return
     */
    List<UserModle> findAllUser();

}

UserServiceImpl:

public class UserServiceImpl implements UserService {

   private UserDao dao;

   public void setUserDao(UserDao dao) {
       this.dao = dao;
   }

   public void savaUser(UserModle um) {

       dao.save(um);
   }

   public void deleteUser(UserModle um) {

       dao.delete(um);
   }

   public void updateUser(UserModle um) {

       dao.update(um);
   }

   public UserModle findUserById(Integer id) {
       return dao.findById(id);
   }

   public List<UserModle> findAllUser() {
       // TODO Auto-generated method stub
       return dao.findAll();
   }

}
6.在Spring配置文件applictionContext.xml中进行相应配置
applictionContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
[url=http://www.springframework.org/schema/beans]http://www.springframework.org/schema/beans[/url]
[url=http://www.springframework.org/schema/beans/spring-beans.xsd]http://www.springframework.org/schema/beans/spring-beans.xsd[/url]
[url=http://www.springframework.org/schema/tx]http://www.springframework.org/schema/tx[/url]
[url=http://www.springframework.org/schema/tx/spring-tx.xsd]http://www.springframework.org/schema/tx/spring-tx.xsd[/url]
[url=http://www.springframework.org/schema/aop]http://www.springframework.org/schema/aop[/url]
[url=http://www.springframework.org/schema/aop/spring-aop.xsd]http://www.springframework.org/schema/aop/spring-aop.xsd[/url]
[url=http://www.springframework.org/schema/context]http://www.springframework.org/schema/context[/url]
[url=http://www.springframework.org/schema/context/spring-context.xsd]http://www.springframework.org/schema/context/spring-context.xsd[/url]
">

    <!--配置sessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <!-- 加载Hibernate的核心配置文件 . classpath为src(类)路径下. 如果在src/config/hibernate.cfg.xml.那么要写成 
            classpath:config/hibernate.cfg.xml.通过配置hibernate.cfg.xml就可以将hibernate的sessionfactory交给spring控制 -->
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    </bean>
    <!--2.配置Hibernate 模版 -->

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <!-- 通过工厂获取session.操作po -->

        <property name="sessionFactory" ref="sessionFactory"></property>

    </bean>
    <!--3.配置dao -->
    <bean id="userDao" class="cn.fy.dao.UserDaoImpl">
        <property name="hibTemplate" ref="hibernateTemplate"></property>
    </bean>

    <!--4.配置service -->
    <bean id="userService" class="cn.fy.serivce.UserServiceImpl">
        <property name="dao" ref="userDao"></property>
    </bean>

    <!--5. 使用注解式事务.开启驱动 .-->
    <tx:annotation-driven transaction-manager="transactionManager" />

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

</beans>

如果不添加事务注解驱动的话. 执行测试会发sql语句, 但是数据库不会更新数据.
7.添加事务注解
在 UserDAO接口类前添加注解 @Transactional

@Transactional // 添加事务注解
public interface UserDao {

   ...

}

  1. 测试

public class TestApp {

    public static void main(String[] args) {

        UserModle um = new UserModle();
        um.setId(1);
        um.setAge(20);
        um.setName("fy");

        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        UserService userService = context.getBean("userService",
                UserService.class);
        userService.savaUser(um);

    }

}

整合方式之二: 不使用Hibernate.cfg.xml文件(推荐使用)重新创建一个文件applicationContext_independent.xml(其实就是更改applicationContext.xml中部分地方)
applicationContext_independent.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
[url=http://www.springframework.org/schema/beans]http://www.springframework.org/schema/beans[/url]
[url=http://www.springframework.org/schema/beans/spring-beans.xsd]http://www.springframework.org/schema/beans/spring-beans.xsd[/url]
[url=http://www.springframework.org/schema/tx]http://www.springframework.org/schema/tx[/url]
[url=http://www.springframework.org/schema/tx/spring-tx.xsd]http://www.springframework.org/schema/tx/spring-tx.xsd[/url]
[url=http://www.springframework.org/schema/aop]http://www.springframework.org/schema/aop[/url]
[url=http://www.springframework.org/schema/aop/spring-aop.xsd]http://www.springframework.org/schema/aop/spring-aop.xsd[/url]
[url=http://www.springframework.org/schema/context]http://www.springframework.org/schema/context[/url]
[url=http://www.springframework.org/schema/context/spring-context.xsd]http://www.springframework.org/schema/context/spring-context.xsd[/url]
">

   <!--1 ,配置sessionFactory -->
   <bean id="sessionFactory"
       class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

       //独立整合不再引入Hibernate.cfg.xml 文件.而是将文件内容抽成bean对象,这就是独立整合

       <!-- 数据库连接配置 -->
       <property name="dataSource" ref="dataSource"></property>
       <!-- 可选配置 -->
       <property name="hibernateProperties">
           <props>
               //   hibernate前缀必须有 
               <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
               <prop key="hibernate.show_sql">true</prop>
               <prop key="hibernate.format_sql">false</prop>
           </props>
       </property>

       <!-- 资源注册 -->
       <property name="mappingResources">
       <list>

       <value>cn/fy/domain/UserModel.hbm.xml</value>

       </list>

       </property>

       <!-- 二级缓存: 通常移入hbm.xml文件中 -->
   </bean>

   <!-- dataSource. 使用jdbc连接   (也可以使用c3p0) -->
   <bean id="dataSource"
       class="org.springframework.jdbc.datasource.DriverManagerDataSource">
       <property name="driverClassName" value="com.mysql.jdbc.Driver">
       </property>
       <property name="url" value="jdbc:mysql://localhost:3306/ssh">
       </property>
       <property name="username" value="root">
       </property>
       <property name="password" value="123456">
       </property>
   </bean>

   <!--2.配置Hibernate 模版 -->

   <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
       <!-- 通过工厂获取session.操作po -->
       <!-- 为什么配置sessionFactory属性的ref="sessionFactory"后没有配置 sessionFactory对应的bean 
           ? sessionFactory bean为:Spring中的类:org.springframework.orm.hibernate3.LocalSessionFactoryBean -->
       <property name="sessionFactory" ref="sessionFactory"></property>

   </bean>

   <!--3.配置dao -->
   <bean id="userDao" class="cn.fy.dao.UserDaoImpl_2">
       <property name="sessionFactory" ref="sessionFactory"></property>
   </bean>

   <!--4.配置service -->
   <bean id="userService" class="cn.fy.serivce.UserServiceImpl">
       <property name="dao" ref="userDao"></property>
   </bean>

   <!--5. 使用注解式事务.开启驱动 . -->
   <tx:annotation-driven transaction-manager="transactionManager" />
   <bean id="transactionManager"
       class="org.springframework.orm.hibernate3.HibernateTransactionManager">
       <property name="sessionFactory" ref="sessionFactory"></property>
   </bean>
   <!--使用注解格式添加事务 -->

</beans>
测试

public class TestApp {

    public static void main(String[] args) {

        UserModle um = new UserModle();
        um.setId(1);
        um.setAge(20);
        um.setName("fy");

        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext_independent.xml");

        UserService userService = context.getBean("userService",
                UserService.class);
        userService.savaUser(um);

    }

}

以上是关于Spring 与Hibernate 整合的主要内容,如果未能解决你的问题,请参考以下文章

Spring与Hibernate整合

Spring 与Hibernate 整合

Spring与Hibernate整合

Struts2+Spring+Hibernate step by step 06 整合Hibernate

spring 学习之三(spring 与hibernate, struts2整合)

Spring整合Hibernate与Struts