📅  最后修改于: 2021-01-02 13:41:35             🧑  作者: Mango
在上一页中,我们已使用xml文件将继承层次结构映射到一个表。在这里,我们将使用注释执行此任务。您需要对每个层次结构策略使用@Inheritance(strategy = InheritanceType.SINGLE_TABLE),@ DiscriminatorColumn和@DiscriminatorValue批注来映射表。
如果每个层次结构都有表,则只需要一个表即可映射继承层次结构。在此,在表中创建了一个额外的列(也称为鉴别符列)以标识类。
让我们看一下继承层次结构:
在此层次结构中有三个类。 Employee是Regular_Employee和Contract_Employee类的超类。
该层次结构的表结构如下所示:
您需要按照以下步骤创建简单的示例:
您需要创建代表继承的持久类。让我们为上述层次结构创建三个类:
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name = "employee101")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="employee")
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
//setters and getters
}
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@DiscriminatorValue("regularemployee")
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
//setters and getters
}
package com.javatpoint.mypackage;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("contractemployee")
public class Contract_Employee extends Employee{
@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
private String contract_duration;
//setters and getters
}
打开pom.xml文件,然后单击源。现在,在
org.hibernate
hibernate-core
5.3.1.Final
com.oracle
ojdbc14
10.2.0.4.0
打开hibernate.cgf.xml文件,并添加如下所示的实体类条目:
update
org.hibernate.dialect.Oracle9Dialect
jdbc:oracle:thin:@localhost:1521:xe
system
jtp
oracle.jdbc.driver.OracleDriver
定义了hbm2ddl.auto属性,用于在数据库中创建自动表。
在此类中,我们仅将雇员对象存储在数据库中。
package com.javatpoint.mypackage;
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 StoreTest {
public static void main(String args[])
{
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
Employee e1=new Employee();
e1.setName("Gaurav Chawla");
Regular_Employee e2=new Regular_Employee();
e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);
Contract_Employee e3=new Contract_Employee();
e3.setName("Arjun Kumar");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}