Hibernate - 每个层次结构一张表



介绍

在 Hibernate 中,Java 类映射到数据库表。假设我们有一个类,并且它有几个子类,Hibernate 提供了三种将类映射到表的方式:

  • 每个层次结构一张表

  • 每个具体类一张表

  • 每个子类一张表

让我们详细讨论一下每个层次结构一张表,并举例说明。

每个层次结构一张表

假设我们有一个类“Shape”,它有两个子类,“Circle”和“Rectangle”。在这种类型的映射中,我们只会在数据库中拥有一个表。

Class Hierachy

层次结构中有三个类。Shape 是超类,CircleRectangle 是子类。考虑type 变量。它的值对于 Shape 类是shape,对于 Circle 类是circle,对于 Rectangle 类是rectangle。这让我们可以从数据库中知道存储的是哪种类型的对象。因此,它是鉴别器

创建映射类

让我们创建其数据需要持久化到数据库中的 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() {
      return 0; // default implementation. 
   }

   public int getId() {
      return Id;
   }

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

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

   public double getArea() {
      return this.area;
   }
}

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;
   }
}

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;
   }
}

创建数据库表

让我们在数据库中创建一个表。对于上述对象,将有一个表对应于您希望提供的持久性。请考虑需要将上述对象存储和检索到以下 RDBMS 表中:

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

创建映射配置文件

现在创建一个映射文件,该文件指示 Hibernate 如何将定义的类映射到数据库表。

shape.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
   "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
   "https://hibernate.com.cn/dtd/hibernate-mapping-3.0.dtd">  
<hibernate-mapping>  
   <class name="com.tutorialspoint.Shape" table="shape" discriminator-value="Shape">  
      <id name="id">  
         <generator class="increment"></generator>  
      </id>  
      <discriminator column="type" type="string"></discriminator>  
      <property name="area"></property>  
      <subclass name="com.tutorialspoint.Circle" discriminator-value="Circle">  
         <property name="radius"></property>  
      </subclass>  
      <subclass name="com.tutorialspoint.Rectangle" discriminator-value="Rectangle">  
         <property name="width"></property>  
         <property name="length"></property>  
      </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>

创建应用程序类

最后,我们将创建我们的应用程序类,其中包含 main() 方法来运行应用程序。我们将使用此应用程序来测试每个层次结构一张表的映射。

TestTablePerhierarchy.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 TestTablePerHierarchy {    
   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(c1.calculateArea());  

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

      // 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.

如果您检查 Shape 表,它应该包含以下记录:

mysql> select * from shape;
+----+-----------+--------+--------+-------+-------+
| id | type      | radius | length | width | area  |
+----+-----------+--------+--------+-------+-------+
|  1 | Shape     |   NULL |   NULL |  NULL |     0 |
|  2 | Circle    |      2 |   NULL |  NULL | 12.56 |
|  3 | Rectangle |   NULL |      3 |     4 |    12 |
+----+-----------+--------+--------+-------+-------+
3 rows in set (0.00 sec)
广告

© . All rights reserved.