Hibernate - Spring 整合



Spring 是一個用於構建企業級 Java 應用程式的開源框架。Spring 有一個 **applicationContext.xml** 檔案。我們將使用此檔案提供所有資訊,包括資料庫配置。由於資料庫配置包含在 Hibernate 的 **hibernate.cfg.xml** 中,因此我們不再需要它。

在 Hibernate 中,我們使用 StandardServiceRegistry、MetadataSources、SessionFactory 獲取 Session 和 Transaction。Spring 框架提供了一個 **HibernateTemplate** 類,您只需呼叫 save 方法即可將資料持久化到資料庫。**HibernateTemplate** 類位於 **org.springframework.orm.hibernate3** 包中。

語法

// create a new student object
Student s1 = new Student( 111, "Karan", "Physics");

// save the student object in database using HibernateTemplate instance
hibernateTemplate.persist(s1);

所需庫

您還需要將 Hibernate-core jar 檔案放入您的 CLASSPATH 中。

HibernateTemplate 類的有用方法

以下是 HibernateTemplate 類重要方法的列表

序號 方法和描述
1

void persist(Object entity)

將物件儲存到資料庫中的對映表中。

2

Serializable save(Object entity)

將物件儲存到資料庫中的對映表記錄中並返回 ID。

3

void saveOrUpdate(Object entity)

儲存或更新與物件對映的表。如果輸入了 ID,則更新記錄;否則儲存。

4

void update(Object entity)

更新與物件對映的表。

5

void delete(Object entity)

根據 ID 刪除資料庫中與表對映的給定物件。

示例

讓我們詳細討論 Spring Hibernate 整合以及一個示例。

建立對映類

讓我們建立 POJO 類,其資料將持久化到資料庫中。

Student.java

package com.tutorialspoint;

public class Student {

   private long id;
   private String name;
   private String dept;
   public long getId() {
      return id;
   }
   public void setId(long id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getDept() {
      return dept;
   }
   public void setDept(String dept) {
      this.dept = dept;
   }
}

建立 DAO 類

建立 DAO 類,它將使用 HibernateTemplate 類來建立、更新和刪除學生物件。

StudentDAO.java

package com.tutorialspoint;

import org.springframework.orm.hibernate3.HibernateTemplate;

public class StudentDAO{

   HibernateTemplate template;

   public void setTemplate(HibernateTemplate template) {
      this.template = template;
   }

   public void saveStudent(Student s){
      template.save(s);
   }

   public void updateStudent(Student s){
      template.update(s);
   }

   public void deleteStudent(Student s){
      template.delete(s);
   }
}

建立對映 XML

為學生物件建立 Hibernate 對映以持久化到資料庫中。

student.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
   <!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
   <class name="Student" table="student_hib">
      <id name="id">
         <generator class="assigned"></generator>
      </id>          
      <property name="name"></property>
      <property name="dept"></property>
   </class>          
</hibernate-mapping>

建立 Application Context XML

建立 Spring Application Context

applicationContext.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:p="http://www.springframework.org/schema/p"  
   xsi:schemaLocation="http://www.springframework.org/schema/beans          
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
   <bean id="dataSource" class=" com.mysql.cj.jdbc.MysqlDataSource">  
      <property name="driverClassName"  value=" com.mysql.cj.jdbc.Driver"></property>  
      <property name="url" value=" jdbc:mysql:///TUTORIALSPOINT"></property>  
      <property name="username" value="root"></property>  
      <property name="password" value="guest123"></property>  
   </bean>  
   <bean id="localSessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
      <property name="dataSource" ref="dataSource"></property>  
      <property name="mappingResources">  
         <list>  
            <value>student.hbm.xml</value>  
         </list>  
      </property>  
      <props>  
         <prop key="hibernate.dialect"> org.hibernate.dialect.MySQL8Dialect</prop>  
         <prop key="hibernate.hbm2ddl.auto">update</prop>  
      </props>  
   </bean>  
   <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">  
      <property name="sessionFactory" ref="localSessionFactory"></property>  
   </bean>  
   <bean id="st" class="StudentDAO">  
      <property name="template" ref="hibernateTemplate"></property>  
   </bean>  
</beans> 

建立應用程式類

最後,我們將建立包含 main() 方法的應用程式類來執行應用程式。我們將使用此應用程式來測試 Spring Hibernate 整合。

PersistStudent.java

package com.tutorialspoint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class PersistStudent {
   public static void main(String[] args) {

      Resource r=new ClassPathResource("applicationContext.xml");
      BeanFactory factory=new XmlBeanFactory(r);

      StudentDAO dao=(StudentDAO)factory.getBean("st");

      Student s=new Student();
      s.setId(190);
      s.setName("Danny Jing");
      s.setDept("Physics");
      dao.persistStudent(s);
      System.out.println(" Successfully persisted the student. Please check your database for results."); 
	  
   }
}

編譯和執行

執行 PersistStudent 二進位制檔案以執行程式。

輸出

您將得到以下結果,並且記錄將被建立到 Shape 表中。

$java PersistStudent
 Successfully persisted the student. Please check your database for results.

如果您檢查您的表,則應該有以下記錄:

mysql> select * from student;
mysql> select * from student;
+------+------------+---------+
| id   | name       | dept    |
+------+------------+---------+
|  190 | Danny Jing | Physics |
+------+------------+---------+
1 row in set (0.00 sec)
廣告
© . All rights reserved.