Hibernate每個具體類一張表映射(使用註釋)

在每個類創建一張表的情況下, 表中不使用Null值的列。 這種方法的缺點是在子類表中創建了重複的列。

在這裏,我們需要在父類中使用[@Inheritance](https://github.com/Inheritance "@Inheritance")(strategy = InheritanceType.TABLE_PER_CLASS)註釋,並在子類中使用[@AttributeOverrides](https://github.com/AttributeOverrides "@AttributeOverrides")註釋。
[@Inheritance](https://github.com/Inheritance "@Inheritance")(strategy = InheritanceType.TABLE_PER_CLASS)指定正在使用每個具體類策略的表。它應該僅在父類中指定。

[@AttributeOverrides](https://github.com/AttributeOverrides "@AttributeOverrides")定義該類中的父類屬性將被覆蓋。 在表結構中,父類表列將被添加到子類表中。

我們來了解映射的層次結構。

Hibernate每個具體類一張表映射(使用註釋)

在每個具體類一張表的情況下,數據庫中將有三個表,每個表表示一個特定的類。

每個表的格結構如下:
Employee類的表結構 -

CREATE TABLE `emp122` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Regular_Employee類的表結構 -

CREATE TABLE `regemp122` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `salary` float DEFAULT NULL,
  `bonus` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Contract_Employee類的表結構 -

CREATE TABLE `contemp122` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `pay_per_hour` float DEFAULT NULL,
  `contract_duration` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

每個具體類的表示例

在這個例子中,我們創建了三個類,並在employee.hbm.xml文件中提供了這些類的映射。創建一個項目:inheritance2annotation, 完整的項目結構如下 -
Hibernate每個具體類一張表映射(使用註釋)

1)創建持久類

您需要創建表示繼承的持久化類。 讓我們爲上面的層次結構創建三個類:

文件:Employee.java

package com.yiibai;

import javax.persistence.*;
import javax.persistence.*;

@Entity
@Table(name = "employee102")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // setters and getters

}

文件:Regular_Employee.java

package com.yiibai;

/**
 * 
 * @author by maxsu
 * @copyright http://www.yiibai.com
 * @link download at: http://www.yiibai.com/siteinfo/download.html
 */
import javax.persistence.*;

@Entity
@Table(name = "regularemployee102")
@AttributeOverrides({
        @AttributeOverride(name = "id", column = @Column(name = "id")),
        @AttributeOverride(name = "name", column = @Column(name = "name")) })
public class Regular_Employee extends Employee {

    @Column(name = "salary")
    private float salary;

    @Column(name = "bonus")
    private int bonus;

    public float getSalary() {
        return salary;
    }

    public void setSalary(float salary) {
        this.salary = salary;
    }

    public int getBonus() {
        return bonus;
    }

    public void setBonus(int bonus) {
        this.bonus = bonus;
    }

    // setters and getters

}

文件:Contract_Employee.java

package com.yiibai;

/**
 * 
 * @author by maxsu
 * @copyright http://www.yiibai.com
 * @link download at: http://www.yiibai.com/siteinfo/download.html
 */
import javax.persistence.*;

@Entity
@Table(name = "contractemployee102")
@AttributeOverrides({
        @AttributeOverride(name = "id", column = @Column(name = "id")),
        @AttributeOverride(name = "name", column = @Column(name = "name")) })
public class Contract_Employee extends Employee {

    @Column(name = "pay_per_hour")
    private float pay_per_hour;

    @Column(name = "contract_duration")
    private String contract_duration;

    public float getPay_per_hour() {
        return pay_per_hour;
    }

    public void setPay_per_hour(float payPerHour) {
        pay_per_hour = payPerHour;
    }

    public String getContract_duration() {
        return contract_duration;
    }

    public void setContract_duration(String contractDuration) {
        contract_duration = contractDuration;
    }
}

2)在配置文件中添加hbm文件的映射

打開hibernate.cfg.xml文件,並添加如下映射資源的項:

<mapping class="com.yiibai.Employee" />
        <mapping class="com.yiibai.Contract_Employee" />
        <mapping class="com.yiibai.Regular_Employee" />

現在配置文件將如下所示:

文件:hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

    <session-factory>
        <property name="hbm2ddl.auto">update</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <property name="show_sql">true</property>

        <mapping class="com.yiibai.Employee" />
        <mapping class="com.yiibai.Contract_Employee" />
        <mapping class="com.yiibai.Regular_Employee" />
    </session-factory>

</hibernate-configuration>

hbm2ddl.auto屬性定義是用於在數據庫中創建自動錶。

4)創建存儲持久對象的類

在這個類中,我們只是將Employee 對象存儲在數據庫表中。

文件:MainTest.java

package com.yiibai;

import org.hibernate.*;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

/**
 * 
 * @author by maxsu
 * @copyright http://www.yiibai.com
 * @link download at: http://www.yiibai.com/siteinfo/download.html
 */

public class MainTest {
    public static void main(String[] args) {
        // 但在5.1.0版本彙總,hibernate則採用如下新方式獲取:
        // 1. 配置類型安全的準服務註冊類,這是當前應用的單例對象,不作修改,所以聲明爲final
        // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定資源路徑,默認在類路徑下尋找名爲hibernate.cfg.xml的文件
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        // 2. 根據服務註冊類創建一個元數據資源集,同時構建元數據並生成應用一般唯一的的session工廠
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata().buildSessionFactory();

        /**** 上面是配置準備,下面開始我們的數據庫操作 ******/
        Session session = sessionFactory.openSession();// 從會話工廠獲取一個session

        // creating transaction object
        Transaction t = session.beginTransaction();

        Employee e1 = new Employee();
        e1.setName("用戶名-01");

        Regular_Employee e2 = new Regular_Employee();
        e2.setName("yiibai su");
        e2.setSalary(50002);
        e2.setBonus(5);

        Contract_Employee e3 = new Contract_Employee();
        e3.setName("Mina su");
        e3.setPay_per_hour(1010);
        e3.setContract_duration("15 hours");

        session.persist(e1);
        session.persist(e2);
        session.persist(e3);

        t.commit();
        session.close();
        System.out.println("success");
    }
}

執行上面代碼運行測試即可,應該會自動創建三張表,並插入數據。