spring與hibernate的整合

開發流程

1、創建持久化類和映射文件
2、創建hibernate的配置文件
3、寫spring的配置文件,引入sessionFactory
4、測試sessionFactory
5、寫dao層和service層的接口和類
6、把dao層和service層的類放入到spring容器中
7、在spring的配置文件中進行aop的配置
……
8、測試

1、創建Person持久化類和映射文件

Person持久化類

import java.io.Serializable;
public class Person implements Serializable{
    private int pid;
    private String name;
    private String description;

    public Person(){}

    public Person(String name,String description){
        this.name = name;
        this.description=description;
    }

    public int getPid() {
        return pid;
    }

    public void setPid(int pid) {
        this.pid = pid;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

映射文件Person.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!-- 
        class用來描述一個類
           name 類的全名
           table 該持久化類對應的表名   可以不寫,默認值爲類名
           catalog  數據庫的名稱
     -->
    <class name="com.zhiyou.domain.Person" table="person">
        <!-- 
            用來描述主鍵
              name 屬性的名稱
              column 屬性的名稱對應的表的字段   可以不寫  默認值就是屬性的名稱
              length  屬性的名稱對應的表的字段的長度  如果不寫,默認是最大的長度
         -->
        <id name="pid" column="pid" length="5">
            <!-- 
                主鍵的產生器
             -->
            <generator class="increment"></generator>
        </id>

        <property name="name" length="20" type="string"></property>

        <property name="description" length="50" type="java.lang.String"></property>
    </class>
</hibernate-mapping>

2、創建hibernate的配置文件

hibernate.cfg.xml文件

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <!-- 一個sessionFactory代表數據庫的一個連接 -->
<session-factory>
    <!-- 鏈接數據庫的用戶名 -->
    <property name="connection.username">root</property>
    <!-- 鏈接數據庫的密碼 -->
    <property name="connection.password">123456</property>
    <!-- 鏈接數據庫的驅動 -->
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <!-- 鏈接數據庫的url -->
    <property name="connection.url">
        jdbc:mysql://localhost:3306/test
    </property>
    <!-- 
        方言
        告訴hibernate用什麼樣的數據庫
    -->
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>
    <!-- 
        validate 加載hibernate時,驗證數據庫的結構  默認值
        update  加載hibernate時,檢查數據庫,如果表不存在,則創建,如果存在,則更新
        create  每次加載hiberante,都會創建表
        create-drop  每次加載hiberante,創建,卸載hiberante時,銷燬
    -->
    <property name="hbm2ddl.auto">update</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <mapping resource="com/zhiyou/domain/Person.hbm.xml" />

</session-factory>
</hibernate-configuration>

3、寫dao層和service層的接口和類

Dao層接口

import com.zhiyou.domain.Person;

public interface PersonDao {
    public void savePerson(Person person);

}

Dao層實現

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.zhiyou.dao.PersonDao;
import com.zhiyou.domain.Person;

public class PersonDaoImpl extends HibernateDaoSupport implements PersonDao {

    @Override
    public void savePerson(Person person) {
        // TODO Auto-generated method stub
        this.getHibernateTemplate().save(person);

    }

}

service層接口

import com.zhiyou.domain.Person;

public interface PersonService {
    public void  savePerson(Person person);

}

service層接口實現

import com.zhiyou.dao.PersonDao;
import com.zhiyou.domain.Person;
import com.zhiyou.service.PersonService;

public class PersonServiceImpl implements PersonService {
    private PersonDao personDao;

    public PersonDao getPersonDao() {
        return personDao;
    }

    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }
    public PersonServiceImpl() {
        // TODO Auto-generated constructor stub
    }
    public PersonServiceImpl(PersonDao personDao) {
        // TODO Auto-generated constructor stub
        this.personDao=personDao;
    }

    @Override
    public void savePerson(Person person) {
        // TODO Auto-generated method stub
        this.personDao.savePerson(person);

    }

}

4、寫一個數據連接池jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/test
jdbc.username=root
jdbc.password=123456

5、把dao層和service層的類放入到spring容器中,在spring的配置文件中進行aop的配置

寫spring的配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
    <!-- 
        引入properties配置文件
     -->
    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>classpath:jdbc.properties</value>
        </property>
    </bean>
    <bean id="dataSource" destroy-method="close"
        class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <bean id="sessionFactory1" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
    </bean>

    <bean id="sessionFactory2" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 
            映射文件所在的路徑
         -->
        <property name="mappingDirectoryLocations">
            <list>
                <!-- 
                    spring容器會去該包及子包下搜索所有的映射文件
                 -->
                <value>com/zhiyou/domain</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>
    <bean id="personDao" class="com.zhiyou.dao.impl.PersonDaoImpl">
        <property name="sessionFactory">
          <ref bean="sessionFactory2"/>
        </property>
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
           <ref bean="sessionFactory2"/>
        </property>
    </bean>
    <tx:advice transaction-manager="transactionManager" id="tx"></tx:advice>
    <bean id="personService" class="com.zhiyou.service.impl.PersonServiceImpl">
        <property name="personDao">
           <ref bean="personDao"/>
        </property>
    </bean>
    <aop:config>
       <aop:pointcut expression="execution(* com.zhiyou.service.impl.PersonServiceImpl.*.*(..))" id="preform"/>
       <aop:advisor advice-ref="tx" pointcut-ref="preform"/>
    </aop:config>
    </beans>

6、測試


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

import com.zhiyou.domain.Person;
import com.zhiyou.service.PersonService;

public class Hibernate_spring_Test {
    @Test
    public void test1()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        PersonService personService=(PersonService)context.getBean("personService");
        Person person=new Person();
        person.setPid(8);
        person.setName("嫦娥姐姐");
        person.setDescription("豬八戒又來了");
        personService.savePerson(person);

    }

}

7、結果

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章