Spring 與Hibernate 整合

Spring 與Hibernate 整合

                 ---  ONE Goal , ONE Passion !

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

        <!--配置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 {

        ...
    }

8. 測試

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

        <!--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);

        }

    }
發佈了122 篇原創文章 · 獲贊 74 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章