Hibernate - 每個具體類一張表



引言

在 Hibernate 中,Java 類對映到資料庫表。假設我們有一個類,並且它有幾個子類,Hibernate 提供了三種方法將這些類對映到表:

  • 每層級一張表

  • 每個具體類一張表

  • 每個子類一張表

讓我們詳細討論一下“每個具體類一張表”以及一個示例。

每個具體類一張表

假設我們有一個類“Shape”,它有兩個子類,“Circle”和“Rectangle”。在這種對映型別中,資料庫中將有三個表。

Class Hierachy

層次結構中有三個類。**Shape** 是超類,**Circle** 和 **Rectangle** 是子類。子類的表將僅包含子類的欄位。為了檢視子類的所有欄位,需要對超類和子類進行連線。

SELECT col1, col2…coln FROM superclass_table
UNION
SELECT col_a, col_b,..col_n FROM subclass_table;

這將選擇子類(包括父類中的那些)的所有屬性。**UNION** 運算子預設只選擇不同的值。要允許重複值,請使用 **UNION ALL**。這就是為什麼 **每個具體類一張表** 也被稱為 **連線子類**。為了對映這些類,我們將在 *.hbm.xml 檔案中使用 **union-subclass** 元素,如下所示:

<class name="com.tutorialspoint.Shape" table="shape">
...
      <union-subclass name="com.tutorialspoint.Circle"
         table="circle">
         <property name="radius"></property>
      </union-subclass>
	  <union-subclass name="com.tutorialspoint.Rectangle"
         table="rectangle">
         <property name="length"></property>
         <property name="width"></property>
      </union-subclass>
...

建立對映類

讓我們建立其資料需要持久化到資料庫中的 POJO 類。

Shape.java

package com.tutorialspoint;

public class Shape {
   public int Id;
   public String type;
   public double area;

   public Shape() {
      this.type = "Shape";
   }

   public double calculateArea() {
      this.area= 0;
      setArea(area);
      return area;
   }

   public int getId() {
      return Id;
   }

   public void setId(int i) {
      this.Id = i;
   }

   public String getType() {
      return this.type;
   }
   public double getArea() {
      return area;
   }
   public void setArea(double i) {
      area = i;
   }
}

Circle.java

package com.tutorialspoint;

import java.math.*;

public class Circle extends Shape {

   private double radius;

   public Circle(double rad ) {
      this.radius = rad;
      this.type = "Circle";
   }

   @Override
   public double calculateArea() {
      area =  Math.PI * radius * radius;
      return area;
   }
   public void setArea() {
      this.area = calculateArea();
   }
   public double getArea() {
      return area;
   }
}

Rectangle.java

package com.tutorialspoint;

public class Rectangle extends Shape {

   private double length, width;

   public Rectangle(double length, double width) {
      this.length = length;
      this.width = width;
      this.type = "Rectangle";
   }

   @Override
   public double calculateArea() {
      return length * width;
   }
   public void setArea() {
      this.area = calculateArea();
   }
   public double getArea() {
      return area;
   }
}

建立資料庫表

讓我們在資料庫中建立表。將有三個表對應於上述物件,您希望提供永續性。考慮上述物件需要儲存到以下 RDBMS 表中並從中檢索:

CREATE TABLE students.shape( 
   id int NOT NULL, 
   type VARCHAR(20),
   area float
);

CREATE TABLE students.circle( 
   id int NOT NULL, 
   type VARCHAR(20),
   area float,
   radius float
);

CREATE TABLE students.rectangle( 
   id int NOT NULL, 
   type VARCHAR(20),
   area float,
   length float,
   width float
);

建立對映配置檔案

現在建立一個對映檔案,該檔案指示 Hibernate 如何將定義的類對映到資料庫表。

shape.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 5.3//EN"
   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
   <class name="com.tutorialspoint.Shape" table="shape">
      <id name="id">
         <generator class="increment"></generator>
      </id>
      <property name="type"></property>
      <property name="area"></property>
      <union-subclass name="com.tutorialspoint.Circle"
         table="circle">
         <property name="radius"></property>
      </union-subclass>
      <union-subclass name="com.tutorialspoint.Rectangle"
         table="rectangle">
         <property name="length"></property>
         <property name="width"></property>
      </union-subclass>
   </class>
</hibernate-mapping>

建立 Hibernate 配置檔案

現在為資料庫和其他詳細資訊建立一個 hibernate 配置檔案。

hibernate.cfg.xml

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
   "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
      <property name="hbm2ddl.auto">update</property>
      <property name = "hibernate.dialect">
         org.hibernate.dialect.MySQL8Dialect
      </property>
      <property name = "hibernate.connection.driver_class">
         com.mysql.cj.jdbc.Driver
      </property>
      <!—'students' is the database name -->
      <property name = "hibernate.connection.url">
         jdbc:mysql:///students
      </property>
      <property name = "hibernate.connection.username">
         root
      </property>
      <property name = "hibernate.connection.password">
         guest123
      </property>
      <!-- List of XML mapping files -->
      <mapping resource = "shape.hbm.xml"/>
   </session-factory>
</hibernate-configuration>

將屬性 **hbm2ddlauto** 設定為 **update** 將在程式執行期間建立表(如果表不存在)。

建立應用程式類

最後,我們將使用 main() 方法建立我們的應用程式類來執行應用程式。我們將使用此應用程式來測試“每個具體類一張表”對映。

TestTablePerConcrete.java

package com.tutorialspoint;

import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.Transaction;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  

public class TestTablePerConcrete{ {    
   public static void main(String[] args) {    
      // create a hibernate configuration 
      StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
      Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
      // get the sessionfactory and open the session
      SessionFactory factory=meta.getSessionFactoryBuilder().build();  
      Session session=factory.openSession();  

      // begin the transaction
      Transaction t=session.beginTransaction();    

      // create Shape instance and set details to persist
      Shape s1=new Shape();    
      s1.setType(s1.getType());
      s1.setArea(s1.calculateArea());

      // create Circle instance and set details to persist
      Circle c1=new Circle(2);    
      c1.setType(c1.getType());
      c1.setArea();  

      // create Rectangle instance and set details to persist
      Rectangle r1 = new Rectangle(3,4);    
      r1.setType(r1.getType());
      r1.setArea();

      // persist all instances
      session.persist(s1);    
      session.persist(c1);    
      session.persist(r1);    

      // commit the transaction and close the session
      t.commit();    
      session.close();    
      System.out.println(" Successfully persisted 3 classes. Please check your database for results.");    
   } 
}

編譯和執行

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

輸出

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

$java TestTablePerHierarchy
 Successfully persisted 3 classes. Please check your database for results.

如果您檢查您的表,則它們應該包含以下記錄:

mysql> select * from shape;
+----+-------+------+
| id | type  | area |
+----+-------+------+
|  1 | Shape |    0 |
+----+-------+------+
1 row in set (0.00 sec)

mysql> select * from circle;
+----+--------+-------+--------+
| id | type   | area  | radius |
+----+--------+-------+--------+
|  1 | Circle | 12.56 |      2 |
+----+--------+-------+--------+
1 row in set (0.00 sec)

mysql> select * from rectangle;
+----+-----------+------+--------+-------+
| id | type      | area | length | width |
+----+-----------+------+--------+-------+
|  1 | Rectangle |   12 |      3 |     4 |
+----+-----------+------+--------+-------+
1 row in set (0.00 sec)
廣告
© . All rights reserved.