天天看點

Spring5整合Hibernate5

一、概述

  Spring整合Hibernate有什麼好處?      1、由IOC容器來管理Hibernate的SessionFactory      2、讓Hibernate使用上Spring的聲明式事務

二、整合步驟:

  步驟一:導包     建立Maven項目SpringHibernate,并導入資料庫驅動包、Hibernate開發包以及Spring開發包,完成後項目的pom.xml檔案内容如下:    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-context</artifactId>     <version>5.1.1.RELEASE</version> </dependency>         <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-core</artifactId>     <version>5.1.1.RELEASE</version> </dependency>         <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-beans</artifactId>     <version>5.1.1.RELEASE</version> </dependency>         <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-web</artifactId>     <version>5.1.1.RELEASE</version> </dependency>         <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-webmvc</artifactId>     <version>5.1.1.RELEASE</version> </dependency>     <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop --> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-aop</artifactId>     <version>5.1.1.RELEASE</version> </dependency>         <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx --> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-tx</artifactId>     <version>5.1.1.RELEASE</version> </dependency>         <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-jdbc</artifactId>     <version>5.1.1.RELEASE</version> </dependency>         <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-aspects</artifactId>     <version>5.1.1.RELEASE</version> </dependency>         <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --> <dependency>     <groupId>org.hibernate</groupId>     <artifactId>hibernate-core</artifactId>     <version>5.3.6.Final</version> </dependency>         <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 --> <dependency>     <groupId>org.hibernate</groupId>     <artifactId>hibernate-c3p0</artifactId>     <version>5.3.6.Final</version> </dependency>     <dependency>   <groupId>com.oracle</groupId>   <artifactId>ojdbc6</artifactId>   <version>11.2.0.4</version> </dependency>     <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --> <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-orm</artifactId>     <version>5.1.1.RELEASE</version> </dependency> 步驟二:建立Hibernate配置檔案    <session-factory>         <!-- 配置Hibernate的基本屬性:方言,SQL顯示及格式化,生成資料表的政策以及二級緩存 -->         <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>         <property name="hibernate.show_sql">true</property>         <property name="hibernate.format_sql">true</property>         <property name="hbm2ddl.auto">update</property>     </session-factory>   注意:   <!-- 1.資料源配置到Spring的IOC容器中 -->         <!-- 2.關聯的.hbm.xml也在IOC容器配置SessionFactory執行個體 --> 步驟三:建立實體類及其映射檔案:              package com.cn.pojo;    public class Book {      private Integer id;      private String bookName;      private String isbn;      private int price;      private int stock;         ...省略set/get方法...   } Book.hbm.xml檔案   <hibernate-mapping>     <class name="com.cn.pojo.Book" table="TB_BOOK">         <id name="id" type="java.lang.Integer">             <column name="ID" />             <generator class="native" />         </id>         <property name="bookName" type="java.lang.String">             <column name="BOOKNAME" />         </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>   步驟四:建立DAO層、Service層   1、DAO層接口:       package com.cn.dao;        import java.util.List;        import com.cn.pojo.Book;        public interface IBookDao {           public List<Book> findAll();           public String findBookById(int id);           public void save(Book book);           public void update(Book book);           public void delete(int id);       }   2、DAO層接口實作類:        package com.cn.dao;       public class BookDaoImpl implements IBookDao {        private SessionFactory sessionFactory;        public SessionFactory getSessionFactory() {           return sessionFactory;         }        public void setSessionFactory(SessionFactory sessionFactory) {           this.sessionFactory = sessionFactory;        }     //擷取和目前線程綁定的Seesion     private Session getSession()     {         return sessionFactory.getCurrentSession();     }     @Override     public List<Book> findAll() {         String hql = "from Book";         Query<Book> query = this.getSession().createQuery(hql);         return query.list();     }     @Override     public String findBookById(int id) {         // TODO Auto-generated method stub         return null;     }     @Override     public void save(Book book) {         this.getSession().save(book);     }     @Override     public void update(Book book) {         // TODO Auto-generated method stub     }     @Override     public void delete(int id) {         // TODO Auto-generated method stub     } } 3、服務層接口:   public interface IBookService {          public String findBookById(int id);          public void saveBook(Book book);          public List<Book> findAll();    } 4、服務層實作類:   public class BookServiceImpl implements IBookService {      private IBookDao dao;      public IBookDao getDao() {           return dao;      }      public void setDao(IBookDao dao) {           this.dao = dao;      }      @Override      public String findBookById(int id) {           return null;      }      @Override      public void saveBook(Book book) {             dao.save(book);      }      @Override      public List<Book> findAll() {           return dao.findAll();      } } 步驟五:建立Spring配置檔案   1、applicationContext.xml檔案:        <!-- 配置資料源 -->     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">                 <!-- 配置連接配接參數 -->          <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"/>          <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>          <property name="user" value="scott"/>          <property name="password" value="root"/>                   <!-- 配置連接配接池 -->          <property name="initialPoolSize" value="3"/>          <property name="maxPoolSize" value="10"/>          <property name="minPoolSize" value="1"/>          <property name="acquireIncrement" value="3"/>          <property name="maxIdleTime" value="60"/>     </bean>         <!-- 配置SessionFactory -->     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.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/cn/pojo/*.hbm.xml"/>     </bean>         <!-- 導入外部的配置檔案 -->     <import resource="classpath:applicationContext-beans.xml"/>         <!-- 配置Spring聲明式事務,采用AOP形式切入 -->     <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory"/>     </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 proxy-target-class="true">       <aop:pointcut expression="execution(* com.cn.dao.*.*(..))" id="txPointcut"/>       <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>     </aop:config>   2、applicationContext-beans.xml       <bean id="bookDao" class="com.cn.dao.BookDaoImpl">          <property name="sessionFactory" ref="sessionFactory"></property>       </bean>           <bean id="bookService" class="com.cn.dao.BookServiceImpl">          <property name="dao" ref="bookDao"></property>       </bean>   測試:            public class Test {             private static  String conf = "applicationContext.xml";             private static ApplicationContext context = null;             private static IBookService bookService = null;          public static void main(String[] args) {           context = new ClassPathXmlApplicationContext(conf);           bookService = context.getBean(BookServiceImpl.class);           Book book = new Book();           book.setId(2);           book.setBookName("Java程式設計");           book.setPrice(48);           book.setStock(78);           book.setIsbn("ISBN-001-0980");                      bookService.saveBook(book);      } }            

轉載于:https://www.cnblogs.com/lone5wolf/p/11065073.html