在每个子类一张表的情况下,表是根据持久类创建的,但是它们使用主键和外键来重新定义。 所以关系中不会有重复的列。

我们需要在子类中的使用@PrimaryKeyJoinColumn注释和在父类指定@Inheritance(strategy = InheritanceType.JOINED)

下面来看看看我们要映射的类的层次结构。

每个表的结构如下:
Employee类的表结构 -

  1. CREATE TABLE `emp122` (
  2. `id` int(11) NOT NULL,
  3. `name` varchar(255) DEFAULT NULL,
  4. PRIMARY KEY (`id`)
  5. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL

Regular_Employee类的表结构 -

  1. CREATE TABLE `regemp122` (
  2. `id` int(11) NOT NULL,
  3. `name` varchar(255) DEFAULT NULL,
  4. `salary` float DEFAULT NULL,
  5. `bonus` int(11) DEFAULT NULL,
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL

Contract_Employee类的表结构 -

  1. CREATE TABLE `contemp122` (
  2. `id` int(11) NOT NULL,
  3. `name` varchar(255) DEFAULT NULL,
  4. `pay_per_hour` float DEFAULT NULL,
  5. `contract_duration` varchar(255) DEFAULT NULL,
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL

Hibernate每个子类一张表(使用注释)实例

在这个例子中,我们创建了三个类,并在employee.hbm.xml文件中提供了这些类的映射。创建一个项目:inheritance2annotation, 完整的项目结构如下 -

1)创建持久类

您需要创建表示继承的持久化类。为上面的层次结构类创建三个类:

文件:Employee.java

  1. package com.yiibai;
  2. import javax.persistence.*;
  3. @Entity
  4. @Table(name = "employee103")
  5. @Inheritance(strategy = InheritanceType.JOINED)
  6. public class Employee {
  7. @Id
  8. @GeneratedValue(strategy = GenerationType.AUTO)
  9. @Column(name = "id")
  10. private int id;
  11. @Column(name = "name")
  12. private String name;
  13. public int getId() {
  14. return id;
  15. }
  16. public void setId(int id) {
  17. this.id = id;
  18. }
  19. public String getName() {
  20. return name;
  21. }
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25. }
Java

文件:Regular_Employee.java

  1. package com.yiibai;
  2. import javax.persistence.*;
  3. @Entity
  4. @Table(name = "regularemployee103")
  5. @PrimaryKeyJoinColumn(name = "ID")
  6. public class Regular_Employee extends Employee {
  7. @Column(name = "salary")
  8. private float salary;
  9. @Column(name = "bonus")
  10. private int bonus;
  11. public float getSalary() {
  12. return salary;
  13. }
  14. public void setSalary(float salary) {
  15. this.salary = salary;
  16. }
  17. public int getBonus() {
  18. return bonus;
  19. }
  20. public void setBonus(int bonus) {
  21. this.bonus = bonus;
  22. }
  23. }
Java

文件:Contract_Employee.java

  1. package com.yiibai;
  2. import javax.persistence.*;
  3. @Entity
  4. @Table(name = "contractemployee103")
  5. @PrimaryKeyJoinColumn(name = "ID")
  6. public class Contract_Employee extends Employee {
  7. @Column(name = "pay_per_hour")
  8. private float pay_per_hour;
  9. @Column(name = "contract_duration")
  10. private String contract_duration;
  11. public float getPay_per_hour() {
  12. return pay_per_hour;
  13. }
  14. public void setPay_per_hour(float pay_per_hour) {
  15. this.pay_per_hour = pay_per_hour;
  16. }
  17. public String getContract_duration() {
  18. return contract_duration;
  19. }
  20. public void setContract_duration(String contract_duration) {
  21. this.contract_duration = contract_duration;
  22. }
  23. // setters and getters
  24. }
Java

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

打开hibernate.cfg.xml文件,并添加如下映射资源的项:

  1. <mapping class="com.yiibai.Employee" />
  2. <mapping class="com.yiibai.Contract_Employee" />
  3. <mapping class="com.yiibai.Regular_Employee" />
XML

现在配置文件将如下所示:

文件:hibernate.cfg.xml

  1. <?xml version='1.0' encoding='UTF-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5. <!-- Generated by MyEclipse Hibernate Tools. -->
  6. <hibernate-configuration>
  7. <session-factory>
  8. <property name="hbm2ddl.auto">update</property>
  9. <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  10. <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
  11. <property name="connection.username">root</property>
  12. <property name="connection.password">123456</property>
  13. <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
  14. <property name="show_sql">true</property>
  15. <mapping class="com.yiibai.Employee" />
  16. <mapping class="com.yiibai.Contract_Employee" />
  17. <mapping class="com.yiibai.Regular_Employee" />
  18. </session-factory>
  19. </hibernate-configuration>
XML

hbm2ddl.auto属性定义是用于在数据库中创建自动表。

4)创建存储持久对象的类

在这个类中,我们只是将Employee 对象存储在数据库表中。

文件:MainTest.java

  1. package com.yiibai;
  2. import org.hibernate.*;
  3. import org.hibernate.boot.MetadataSources;
  4. import org.hibernate.boot.registry.StandardServiceRegistry;
  5. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
  6. /**
  7. *
  8. * @author by maxsu
  9. * @copyright http://www.yiibai.com
  10. * @link download at: http://www.yiibai.com/siteinfo/download.html
  11. */
  12. public class MainTest {
  13. public static void main(String[] args) {
  14. // 但在5.1.0版本汇总,hibernate则采用如下新方式获取:
  15. // 1. 配置类型安全的准服务注册类,这是当前应用的单例对象,不作修改,所以声明为final
  16. // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定资源路径,默认在类路径下寻找名为hibernate.cfg.xml的文件
  17. final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
  18. .configure("hibernate.cfg.xml").build();
  19. // 2. 根据服务注册类创建一个元数据资源集,同时构建元数据并生成应用一般唯一的的session工厂
  20. SessionFactory sessionFactory = new MetadataSources(registry)
  21. .buildMetadata().buildSessionFactory();
  22. /**** 上面是配置准备,下面开始我们的数据库操作 ******/
  23. Session session = sessionFactory.openSession();// 从会话工厂获取一个session
  24. // creating transaction object
  25. Transaction t = session.beginTransaction();
  26. Employee e1 = new Employee();
  27. e1.setName("用户名-01");
  28. Regular_Employee e2 = new Regular_Employee();
  29. e2.setName("yiibai su");
  30. e2.setSalary(50002);
  31. e2.setBonus(5);
  32. Contract_Employee e3 = new Contract_Employee();
  33. e3.setName("Mina su");
  34. e3.setPay_per_hour(1010);
  35. e3.setContract_duration("15 hours");
  36. session.persist(e1);
  37. session.persist(e2);
  38. session.persist(e3);
  39. t.commit();
  40. session.close();
  41. System.out.println("success");
  42. }
  43. }
Java

执行上面代码运行测试即可,应该会自动创建三张表,并插入数据。

Hibernate每个子类一张表(使用注释)实例的更多相关文章

  1. Hibernate每个子类一张表(使用XML文件)实例

    在每个子类一张表的情况下,子类映射表与主键和外键关系与父类映射表相关. 类的<joined-subclass>元素用于使用主键和外键关系将子类与父对象进行映射. 在这个例子中,我们将使用h ...

  2. [jnhs]hibernate只能创建一张/表不创建表com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'kaihu.t_client_info' doesn't exist和org.hibernate.exception.SQLGrammarException: could not execute statement

    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'kaihu.t_client_info' doesn't exist ...

  3. Hibernate每个具体类一张表映射(使用注释)

    在每个类创建一张表的情况下, 表中不使用Null值的列. 这种方法的缺点是在子类表中创建了重复的列. 在这里,我们需要在父类中使用@Inheritance(strategy = Inheritance ...

  4. Hibernate每个层次类一张表(使用注释)

    在上一文章中,我们使用xml文件将继承层次映射到一个表. 在这里,我们将使用注释来执行同样的任务.需要使用@Inheritance(strategy = InheritanceType.SINGLE_ ...

  5. Hibernate每个具体类一张表映射(使用XML)

    在每个具体类一个表中,数据库中将有三个表但彼此之间没有关系(关联). 根据具体类策略将表格映射到表有两种方法. 由union-subclass元素指定 通过自我为每个类创建表 我们来了解映射的层次结构 ...

  6. oracle表连接——处理连接过程中另外一张表没有相关数据不显示问题

    一个数据表基本上很难满足我们的查询要求,同时,将所有的数据都保存在一个表格中显然也不是一种好的数据库设计,为了避免数据的冗余,删除.更新异常,我们通常需要建立一张外键表,通过表连接,来获取我们自己想要 ...

  7. mysql查询在一张表不在另外一张表的记录

    mysql查询在一张表不在另外一张表的记录   问题:    查询一个表(tb1)的字段记录不在另一个表(tb2)中      条件:tb1的字段key的值不在tbl2表中      -------- ...

  8. idea中Hibernate错误:无法解析表

    idea中Hibernate错误:无法解析表 这种情况主要是在idea中使用hibernate自定义注解,idea无法检查数据源 this inspecton controls whether the ...

  9. EF Core中如何正确地设置两张表之间的关联关系

    数据库 假设现在我们在SQL Server数据库中有下面两张表: Person表,代表的是一个人: CREATE TABLE [dbo].[Person]( ,) NOT NULL, ) NULL, ...

随机推荐

  1. sqlserver 删除临时表

    sqlserver 删除临时表 if object_id('tempdb..#tempTable') is not null Begin drop table #tempTable End

  2. EasyUI-解决EasyUI 加载两次url的问题

    1.传统方式 $(function () { var url = "../Source/Query/jhDataQry.ashx?action=query"; $(dg).data ...

  3. (转)Vue.use源码分析

    我想有过vue开发经验的,对于vue.use并不陌生.当使用vue-resource或vue-router等全局组件时,必须通过Vue.use方法引入,才起作用.那么vue.use在组件引入之前到底做 ...

  4. mac中yeoman构建你的项目

    一开始用在mac中构建一个项目就遇到一个很奇怪的事, 做好各种准备工作后,我开始创建一个angular01作为测试目录,结果运行yo脚手架之后,选择angular工作流进行构建项目,出来的结果我开始慌 ...

  5. JSON--百度百科

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族 ...

  6. IOS Exception2 this class is not key value coding-compliant for the key Click

    2015-06-16 23:00:53.706 MyIOSPackage[823:280049] *** Terminating app due to uncaught exception 'NSUn ...

  7. Apache Nifi在Windows环境下搭建伪群集及证书登录

    代码地址如下:http://www.demodashi.com/demo/11986.html 前些时间做了关于Apache Nifi分布式集群的搭建分享,但很多时候要搭建分布式集群机器资源是个问题, ...

  8. Problem-1001:Sum Problem

    Sum Problem Sample code : #include <stdio.h> int main() { int i,n; int sum; while(scanf(" ...

  9. lucene 查询

    csdn blog - Lucene 3.0 的Query Parser(查询语法)   ibm developerWorks - 使用 Apache Lucene 2.4.1 搜索文本   osch ...

  10. WPF入门教程系列二

    WPF控件和布局 一.  前言  公司项目基于WPF开发,最近项目上线有点空闲时间写一篇基于wpf的基础教材,WPF也是近期才接触,学习WPF也是在网上查资料与微软的MSDN进行学习,写本博客的目为了 ...