在上一文章中,我们使用xml文件将继承层次映射到一个表。 在这里,我们将使用注释来执行同样的任务。需要使用@Inheritance(strategy = InheritanceType.SINGLE_TABLE)@DiscriminatorColumn@DiscriminatorValue注释,以便根据层次结构策略映射表。

在每个层次结构一张表的情况下,只需要一个表来映射继承层次结构。 这里,在表中创建一个额外的列(也称为discriminator列)来标识该类。

下面来看看看继承层次结构:

这个层次结构中有三个类。 EmployeeRegular_EmployeeContract_Employee类的父类。

此层次结构的表结构如下所示:

列名 数据类型 是否为空 默认值 是否主键
id int(10) -
type varchar(254) - -
name varchar(254) - -
salary float - -
bonus int(10) - -
pay_per_hour float - -
contract_duration   - -

使用注释的每个层次结构一张表示例

您需要按照以下步骤创建简单示例:

  • 创建持久化类
  • 创建配置文件
  • 创建类来存储提取数据

创建一个项目名称为:,其结构如下图所示 -

1)创建持久类

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

文件:Employee.java

package com.yiibai;

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

文件: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
@DiscriminatorValue("regularemployee")
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;
} }
Java

文件: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
@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; 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;
}
}
Java

2)在配置文件中添加持久化类

打开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>
XML

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

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

在这个类中,我们只是将 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");
}
}
Java

执行上面示例,输出结果如下 -

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Sun Mar 26 02:19:13 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Sun Mar 26 02:19:14 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into employee101 (name, type, id) values (?, 'employee', ?)
Hibernate: insert into employee101 (name, bonus, salary, type, id) values (?, ?, ?, 'regularemployee', ?)
Hibernate: insert into employee101 (name, contract_duration, pay_per_hour, type, id) values (?, ?, ?, 'contractemployee', ?)
success
Shell

查看数据表,应该会看到相应的数据记录

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

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

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

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

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

  3. 【原创】Hibernate通过实体类自动建表时type=MyISAM的问题

    ι 版权声明:本文为博主原创文章,未经博主允许不得转载. 当使用的mysql数据库为5.5版本时,方言需要设置为 <property name="hibernate.dialect&q ...

  4. 配置hibernate根据实体类自动建表功能

    Hibernate支持自动建表,在开发阶段很方便,可以保证hbm与数据库表结构的自动同步. 如何使用呢?很简单,只要在hibernate.cfg.xml里加上如下代码 Xml代码<propert ...

  5. Hibernate根据实体类自动创建表

    Hibernate支持自动建表,在开发阶段很方便,可以保证hbm与数据库表结构的自动同步. 如何使用呢?很简单,只要在hibernate.cfg.xml里加上如下代码 Xml代码<propert ...

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

    在每个子类一张表的情况下,表是根据持久类创建的,但是它们使用主键和外键来重新定义. 所以关系中不会有重复的列. 我们需要在子类中的使用@PrimaryKeyJoinColumn注释和在父类指定@Inh ...

  7. Hibernate使用xml文件的每个类层次一张表

    通过这种继承策略,我们可以通过单表映射整个层次结构. 这里,在表中创建一个额外的列(也称为discriminator列)来标识该类. 让我们先了解问题.下面给出的整个层次类映射到数据库的一个表中图解说 ...

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

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

  9. Hibernate由model类自动同步数据库表结构

    在开发中遇到了个问题,每次测试数据库增加表结构的时候,本地pull下最新代码导致启动报错,上网搜了快速解决办法---->hibernate 配置属性中,hibernate.hbm2ddl.aut ...

随机推荐

  1. Jquery获取对象的几种方式介绍

    参考: 1.http://blog.csdn.net/zengyonglan/article/details/53995295 2.http://api.jquery.com/category/sel ...

  2. 自己做的roguelike+恶魔城游戏《魔塔猎人》已发布。

    游戏仍然是标准的roguelike,死亡后回到出生点重新开始,宏观架构上参考了<死亡细胞>,战斗设计上更加强调轻重攻击的组合,再配合236和28系列的搓招技.空中的突进飞腿.副武器等等. ...

  3. D3.js系列——交互式操作和布局

    一.图表交互操作 与图表的交互,指在图形元素上设置一个或多个监听器,当事件发生时,做出相应的反应. 交互,指的是用户输入了某种指令,程序接受到指令之后必须做出某种响应.对可视化图表来说,交互能使图表更 ...

  4. JS组件系列——显示隐藏密码切换的jQuery插件

    <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8& ...

  5. spring+mybatis项目启动报错Initializing Spring root WebApplicationContext

    这个问题很怪异,各种各样的情况都会导致这个问题的出现,主要是由于sping加载读取配置文件的时候出了问题.我在处理mybatis的时候出现了这个问题,后来排查发现,在mybatis的配置文件中如果有大 ...

  6. Druid对比Cassandra

    不是Cassandra专家, 如果描绘有错误, 请通过邮件列表或者其他方式告知, 我们会修正. Druid对扫描和聚合做了很大程度的优化, 不用提前计算就支持任意的向下钻取, 还可以实时摄入流式数据并 ...

  7. (转)Netty : writeAndFlush的线程安全及并发问题

    rocketmq用netty实现的网络连接,发现它多个线程掉用一个channel连接,所以这个是线程安全的? 使用Netty编程时,我们经常会从用户线程,而不是Netty线程池发起write操作,因为 ...

  8. 时光轴二之RecyclerView版时光轴效果

    由于如今RecyclerView是support-v7包中的新组件,是一个强大的滑动组件.与经典的ListView相比,相同拥有item回收复用的功能,可是直接把viewholder的实现封装起来,用 ...

  9. 表单提交时上传图片 表单ajax提交

    页面 <script type="text/javascript" src="js/jquery.form.js"></script>& ...

  10. hibernate学习系列-----(6)hibernate对集合属性的操作之Set集合篇

    先说一段废话吧,本打算每天把所学的知识总结为博客的,但是昨天为什么没有写呢?没有学习吗?No,那是为什么?贪玩,对,这位同学说对了,老实说昨天感觉身体不怎么舒服,大家都知道,这其实就是为自己懒找借口, ...