通過Spring整合hibernate並進行單元測試(詳細),hibernate單元測試

來源:互聯網
上載者:User

通過Spring整合hibernate並進行單元測試(詳細),hibernate單元測試

一.

沒有基礎hibernate基礎的可以點擊這裡 ---------->ORM----hibernate入門Demo(無敵詳細版)

這裡我就不詳細介紹了..

二.

hibernat.cfg.xml檔案是Hibernate中重要的設定檔,當Spring和Hibernate整合時,由於hibernate.cfg.xml檔案中的配置資訊可以教育Spring來管理,

所以可以選擇是否使用hibernate.cfg.xml檔案.

這裡將從使用hibernate.cfg.xml檔案來講解Spring和Hibernate的整合

在講解Spring和Hibernate的整合前,首先需要瞭解三個重要的對象,具體如下:

1.HibernateTemplate:相當於Hibernate的session可以直接操作PO類,依賴於SessionFactory.

2.LocalSessionFactoryBean:擷取SessionFactory.

3.HibernateTransactionManager:Hibernate的事物管理器.

三.實現代碼:

整個項目所需jar包:

 

1.使用hibernate.cfg.xml檔案整合Spring.

1).首先建立一張user表:

2).建立User類

public class User {  private Integer id;       //使用者id  private String  username;     //使用者名稱稱  private String password;  //使用者密碼public Integer getId() {return id;    }public void setId(Integer id) {this.id = id;    }public String getUsername() {return username;    }public void setUsername(String username) {this.username = username;    }public String getPassword() { return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "User [id=" + id + ", username=" + username + ", password=" + password + "]";}  }

3).編寫對應的User.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>      <!-- name代表的是實體類名,table代表的是表名 -->      <class name="com.hck.entity.User" table="user">          <!-- name=id代表的是user類中屬性  column=id代表的是table表中的欄位 -->          <id name="id" column="id">             <!-- 主鍵建置原則 -->             <generator class="native"/>          </id>          <!-- 其他屬性使用property標籤來映射 -->          <property name="username" column="username" type="string"/>          <property name="password" column="password" type="string"/>      </class>  </hibernate-mapping> 

4).編寫UserDao介面

public interface UserDao {  public void save(User user);      //添加使用者  public void update(User user);    //更新使用者  public void delete(User user);    //刪除使用者  public User findById(Integer id); //根據使用者id尋找使用者資料  public List<User>  findAll();     //返回所有使用者資料}

5).編寫介面實作類別:UserDaoImpl

//開啟註解模式,這句相當於在spring中//<bean name="userDao" class="com.hck.dao.impl.UserDaoImpl"/>@Repository("userDao")public class UserDaoImpl implements UserDao {//依賴注入@Autowiredprivate HibernateTemplate hibernateTemplate;//插入操作public void save(User user) {          hibernateTemplate.save(user);}    //更新操作public void update(User user) {      hibernateTemplate.update(user);}    //刪除操作public void delete(User user) {   hibernateTemplate.delete(user);}    //根據ID尋找使用者public User findById(Integer id) {return hibernateTemplate.get(User.class, id);}//返回所有使用者資料@SuppressWarnings("unchecked")public List<User> findAll() {return (List<User>) hibernateTemplate.find("from User");}}

6).編寫UserService介面

public interface UserService {      public void save(User user);      //添加使用者      public void update(User user);    //更新使用者      public void delete(User user);    //刪除使用者      public User findById(Integer id); //根據使用者id尋找使用者資料      public List<User>  findAll();     //返回所有使用者資料}

7).編寫UserServiceImpl類

//開啟註解模式,這句相當於在spring中//<bean name="userService" class="com.hck.service.impl.UserServiceImpl"/>@Service("userService")public class UserServiceImpl implements UserService {//依賴注入@Autowiredprivate UserDao userDao;//插入資料public void save(User user) {userDao.save(user);}    //更新資料public void update(User user) {    userDao.update(user);}//刪除資料public void delete(User user) {userDao.delete(user);}    //根據id尋找使用者public User findById(Integer id) {return userDao.findById(id);}    //返回所有使用者資訊public List<User> findAll() {return userDao.findAll();}}

8).編寫核心設定檔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>          <!--指定方言 -->          <property name="hibernate.dialect">            org.hibernate.dialect.MySQLDialect          </property>          <!-- 資料庫驅動 -->          <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>          <!-- 串連資料庫的url -->          <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tb_test</property>          <!-- 資料庫使用者名稱 -->          <property name="hibernate.connection.username">root</property>          <!-- 資料庫密碼 -->          <property name="hibernate.connection.password">123456</property>          <!-- 其他配置 -->          <!-- 顯示sql語句 -->          <property name="show_sql">true</property>          <!-- 配置c3p0 -->          <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>          <!-- 用來關聯hbm設定檔 -->                  <!-- <mapping resource="com/hck/entity/Customer.hbm.xml"/> -->          <mapping resource="com/hck/entity/User.hbm.xml"/>         </session-factory>  </hibernate-configuration>

9).編寫Spring的設定檔applicationContext.xml同樣放在src目錄下

<?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:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-4.3.xsd        http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-4.3.xsd        http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-4.3.xsd">     <!-- 開啟註解 -->     <context:annotation-config/>     <!-- 1.配置sessionFactory -->     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">     <!-- 載入Hibernate核心設定檔 -->     <property name="configLocation" value="classpath:hibernate.cfg.xml"/>      </bean>     <!-- 2.配置Hibernate模版 -->     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">          <!-- 通過工廠獲得Session,操作PO類 -->          <property name="sessionFactory" ref="sessionFactory"/>     </bean>     <!-- 交易管理 -->     <!-- #1交易管理員,就是平台,Sprring工具產生,依賴於使用持久方案 -->     <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">           <property name="sessionFactory" ref="sessionFactory"/>     </bean>     <!-- #2通知:增強事務 -->     <tx:advice id="txAdvice" transaction-manager="txManager">           <tx:attributes>                <tx:method name="save*"/>                <tx:method name="update*"/>                <tx:method name="delete*"/>                <!-- 唯讀 -->                <tx:method name="find*" read-only="true"/>           </tx:attributes>     </tx:advice>     <!-- #3 切面:將切入點與通知點關聯 -->     <aop:config>            <aop:pointcut expression="execution(* com.hck.service.*.*(..))" id="allDaoMethod" />            <aop:advisor advice-ref="txAdvice" pointcut-ref="allDaoMethod"/>     </aop:config>     <!-- 包掃描 -->     <context:component-scan base-package="com.hck"/></beans>

10).編寫單元測試類:

public class SpringHibernateTest { //定義變數      ApplicationContext ac;   //讀取Spring設定檔,返回內容物件     UserService userService; //用於接收一個UserServiceImpl執行個體     @Before     public void setUp(){     ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");     userService=(UserService) ac.getBean("userService");     }     @Test     public void insert()     {     User user=new User();     user.setUsername("張三");     user.setPassword("123456");     userService.save(user);     }     @Test     public void findById()     {     User user=userService.findById(1);     System.out.println(user);     }     //修改使用者名稱     @Test     public void update()     {     User user=new User();
user.setId(1); user.setUsername("李四"); user.setPassword("123456"); userService.update(user); } //先尋找再刪除 @Test public void delete() { User user=userService.findById(1); userService.delete(user); } //尋找所有 @Test public void findAll() { List<User> list =userService.findAll(); for(User user:list) { System.out.println(user); } }}

11)測試結果:

A.插入操作:

控制台列印的sql語句,然後到mysql查看資料是否插入成功;這裡我再插入兩條資訊使用者分開顯示查詢所有使用者資訊

B.查詢操作(查詢使用者id為1的資訊):

 C.更新操作,(將id=1的使用者名稱修改為李四)

D.刪除操作,(將id=1的使用者資訊刪除)

 

E.查詢所有使用者資訊

四.總結

   以上是完整的帶hibernate.cfg.xml檔案的Spring跟Hibernate的整合過程,如有疑問可以留言~

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.