歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Spring整合Hibernate詳細步驟

閱讀目錄

  • 一、概述
  • 二、整合步驟

一、概述

  Spring整合Hibernate有什麼好處?

  1、由IOC容器來管理Hibernate的SessionFactory

  2、讓Hibernate使用上Spring的聲明式事務

二、整合步驟

  整合前准備:

  持久化類:

@Entity
public class Book
{
    private Integer id;
    private String bookName;
    private String isbn;
    private int price;
    private int stock;
    public Integer getId()
    {
        return id;
    }
    public void setId(Integer id)
    {
        this.id = id;
    }
    public String getBookName()
    {
        return bookName;
    }
    public void setBookName(String bookName)
    {
        this.bookName = bookName;
    }
    public String getIsbn()
    {
        return isbn;
    }
    public void setIsbn(String isbn)
    {
        this.isbn = isbn;
    }
    public int getPrice()
    {
        return price;
    }
    public void setPrice(int price)
    {
        this.price = price;
    }
    public int getStock()
    {
        return stock;
    }
    public void setStock(int stock)
    {
        this.stock = stock;
    }
    public Book(Integer id, String bookName, String isbn, int price, int stock)
    {
        super();
        this.id = id;
        this.bookName = bookName;
        this.isbn = isbn;
        this.price = price;
        this.stock = stock;
    }
}

  Dao層:

public interface BookDao
{
    public String findBookById(int id);
    
    public void saveBook(Book book);
}

  DaoImpl:

 

@Repository
public class BookDaoImpl implements BookDao
{
    @Autowired
    private SessionFactory sessionFactory;
    
    //獲取和當前線程綁定的Seesion
    private Session getSession()
    {
        return sessionFactory.getCurrentSession();
    }
    public String findBookById(int id)
    {
        String hql="SELECT bookName from Book where id=?";
        Query query=getSession().createQuery(hql).setInteger(0, id);
        String str= query.uniqueResult().toString();
        return str;
    }
    public void saveBook(Book book)
    {
        getSession().save(book);
    }
}
 

  Service層:

public interface BookService
{
    public String findBookById(int id);
    public void saveBook(Book book);
}

  ServiceImpl:

 
@Service
public class BookServiceImpl implements BookService
{
    @Autowired
    private BookDao bookDao;
    public String findBookById(int id)
    {
        return bookDao.findBookById(id);
    }
    public void saveBook(Book book)
    {
        bookDao.saveBook(book);
        
    }
}
 

  1、加入Hibernate

  • 加入hibernate jar包
  • 添加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>
    <session-factory>
        <!-- 配置Hibernate的基本屬性 -->
        <!-- 1.數據源配置到IOC容器中 -->
        <!-- 2.關聯的.hbm.xml也在IOC容器配置SessionFactory實例 -->
        <!-- 3.配置Hibernate的基本屬性:方言,SQL顯示及格式化,生成數據表的策略以及二級緩存 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>
  • 編寫持久化類對應的.hbm.xml文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-3-15 16:30:05 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.demo.ssm.po.Book" table="BOOK">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="bookName" type="java.lang.String">
            <column name="BOOK_NAME" />
        </property>
        <property name="isbn" type="java.lang.String">
            <column name="ISBN" />
        </property>
        <property name="price" type="int">
            <column name="PRICE" />
        </property>
        <property name="stock" type="int">
            <column name="STOCK" />
        </property>
    </class>
</hibernate-mapping>

  2、加入Spring

  • 加入spring jar包
  • 加入Spring配置文件
<?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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
    <context:component-scan base-package="com.demo.ssm"></context:component-scan>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/test" />
        <property name="username" value="root"></property>
        <property name="password" value="281889"></property>
    </bean>  
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="false">
        <!-- 注入datasource,給sessionfactoryBean內setdatasource提供數據源 -->
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <!-- //加載實體類的映射文件位置及名稱 -->
        <property name="mappingLocations" value="classpath:com/demo/ssm/po/*.hbm.xml"></property>
    </bean>  
    
    <!-- 配置Spring聲明式事務 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean> 
    <!-- 配置事務事務屬性 -->
     <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置事務切點,並把切點和事務屬性關聯起來 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.demo.ssm.daoImpl.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
</beans>

  3、編寫測試類

public class BookDaoImplTest
{
    private ApplicationContext context=null;
    private BookService bookService=null;
    
    {
         context= new ClassPathXmlApplicationContext("applicationContext.xml");  
         bookService=context.getBean(BookService.class);
    }
    @Test
    public void test()
    {
        DataSource dataSource=(DataSource) context.getBean(DataSource.class);
        System.out.println(dataSource);
    }
    @Test
    public void test2()
    {
        String bookName=bookService.findBookById(1);
        System.out.println(bookName);
    }
    
    @Test
    public void test3()
    {
        bookService.saveBook(new Book(2, "Android源碼分析", "1002", 45, 10));
    }
}

Hibernate3.1.2_中文文檔PDF  http://www.linuxidc.com/Linux/2016-02/128462.htm

Hibernate學習入門教程  http://www.linuxidc.com/Linux/2015-08/121498.htm

在Hibernate中開啟日志 http://www.linuxidc.com/Linux/2015-07/120499.htm

Hibernate+JUnit測試實體類生成數據庫表  http://www.linuxidc.com/Linux/2015-07/120161.htm

Hibernate整體理解 http://www.linuxidc.com/Linux/2014-07/104405.htm

Hibernate的映射機制  http://www.linuxidc.com/Linux/2014-12/110265.htm

Hibernate 的詳細介紹:請點這裡
Hibernate 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved