📅  最后修改于: 2021-01-02 15:33:05             🧑  作者: Mango
如前所述,在每个子类使用表策略的情况下,表是根据持久性类创建的,但是使用主键和外键对其进行处理。因此,该关系中将没有任何重复的列。
我们需要在父类中指定@Inheritance(strategy = InheritanceType.JOINED) ,在子类中指定@PrimaryKeyJoinColumn注释。
让我们看看我们要映射的类的层次结构。
每个表的表结构如下:
在此示例中,我们将创建三个类,并在employee.hbm.xml文件中提供这些类的映射。
您需要创建代表继承的持久类。让我们为上述层次结构创建三个类:
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name = "employee103")
@Inheritance(strategy=InheritanceType.JOINED)
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
@Table(name="regularemployee103")
@PrimaryKeyJoinColumn(name="ID")
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.*;
@Entity
@Table(name="contractemployee103")
@PrimaryKeyJoinColumn(name="ID")
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 StoreData {
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");
}
}