Hibernate学习---第八节:继承关系的映射配置
1、单表继承
(1)、实体类,代码如下:
package learn.hibernate.bean; import java.util.Date; /**
* 持久化类设计
* 注意:
* 持久化类通常建议要有一个持久化标识符(ID)
* 持久化标识符通常建议使用封装类(例如:Integer 因为基本类型存在默认值)
* 持久化类通常建议手动添加一个无参构造函数 (因为有些操作是通过放射机制进行的)
* 属性通常建议提供 getter/setter 方法
* 持久化类不能使用 final 修饰
* 持久化类中如果使用了集合类型数据,只能使用集合所对应的接口类型来声明(List/Map/Set)
* 如下:ArrayList list = new ArrayList(); 不行
* List list = new ArrayList(); 可行
*/
public class Person { private Integer id;
private String name;
private int age;
private int passwork;
private Date birthday; public Person() { } public Person(String name, int age, int passwork, Date birthday) {
super();
this.name = name;
this.age = age;
this.passwork = passwork;
this.birthday = birthday;
} @Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age
+ ", passwork=" + passwork + ", birthday=" + birthday + "]";
} public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getPasswork() {
return passwork;
}
public void setPasswork(int passwork) {
this.passwork = passwork;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
package learn.hibernate.bean;
import java.util.Date;
public class Student extends Person {
private int number;
private float score;
public Student() {
}
public Student(String name, int age, int passwork, Date birthday,
int number, float score) {
super(name, age, passwork, birthday);
this.number = number;
this.score = score;
}
@Override
public String toString() {
return "Student [number=" + number + ", score=" + score + ", getId()="
+ getId() + ", getName()=" + getName() + ", getAge()="
+ getAge() + ", getPasswork()=" + getPasswork()
+ ", getBirthday()=" + getBirthday() + "]";
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
}
(2)、映射配置文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="learn.hibernate.bean">
<class name="Person" table="t_person">
<id name="id" column="person_id">
<generator class="native"/>
</id>
<!--
辨别列 区分不同的子类对象数据
type 指定辨别列类型(支持 string、int、char)
-->
<discriminator type="string" column="col_type"/>
<property name="name" column="t_name"/>
<property name="age"/>
<property name="passwork"/>
<property name="birthday"/> <!-- 通过 subclass 配置子类 -->
<subclass name="Student">
<property name="number"/>
<property name="score"/>
</subclass>
</class> <!--
如果辨别列使用的是 int 或 char 类型,必须手动给每个类添加辨别值
discriminator-value 指定辨别值
-->
<!-- <class name="Person" table="t_person" discriminator-value="1">
<id name="id" column="person_id">
<generator class="native"/>
</id>
<discriminator type="int" column="col_type"/>
<property name="name" column="t_name"/>
<property name="age"/>
<property name="passwork"/>
<property name="birthday"/> <subclass name="Student" discriminator-value="2">
<property name="number"/>
<property name="score"/>
</subclass>
</class> -->
</hibernate-mapping>
(3)、测试类:
package learn.hibernate.test; import static org.junit.Assert.*; import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set; import learn.hibernate.bean.Person;
import learn.hibernate.bean.Student; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class TestHibernate { SessionFactory factory = null;
Session session = null;
Transaction tx = null; /**
* 测试之前初始化数据
* @throws Exception
*/
@SuppressWarnings("deprecation")
@Before
public void setUp() throws Exception {
System.out.println("---------初始化数据----------"); Configuration config = new Configuration().configure();
ServiceRegistry sr = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
factory = config.buildSessionFactory(sr);
session = factory.openSession();
} /**
* 测试之后释放(销毁)数据
* @throws Exception
*/
@After
public void tearDown() throws Exception {
System.out.println("---------释放数据----------");
if(session.isOpen()){
session.close();
}
} @Test
public void testAdd(){
Student stu = new Student("hwl", 19, 123456, new Date(), 122, 99.0F);
tx = session.beginTransaction();
session.persist(stu);
tx.commit();
} @Test
public void testGet(){
Person p = (Person)session.get(Person.class, 1);
System.out.println(p);
}
}
(4)、hibernate 配置文件:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <!--声明Hibernate配置文件的开始-->
<hibernate-configuration>
<!--表明以下的配置是针对session-factory配置的,SessionFactory是Hibernate中的一个类,这个类主要负责保存HIbernate的配置信息,以及对Session的操作-->
<session-factory>
<!--hibernate.dialect 只是Hibernate使用的数据库方言,就是要用Hibernate连接那种类型的数据库服务器-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!--配置数据库的驱动程序,Hibernate 在连接数据库时,需要用到数据库的驱动程序-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!--设置数据库的连接url:jdbc:mysql://localhost/hibernate,其中localhost表示mysql服务器名称,此处为本机, hibernate是数据库名-->
<!--
jdbc:mysql://192.168.1.112:3305/hibernate 联网络数据库
jdbc:mysql:///hibernate 联本机
-->
<property name="hibernate.connection.url">jdbc:mysql:///hibernate</property>
<!--连接数据库是用户名-->
<property name="hibernate.connection.username">root</property>
<!--连接数据库是密码-->
<property name="hibernate.connection.password">123456</property>
<!-- 是否自动创建数据库表 他主要有一下几个值: validate:当sessionFactory创建时,自动验证或者schema定义导入数据库。 create:每次启动都drop掉原来的schema,创建新的。 create-drop:当sessionFactory明确关闭时,drop掉schema。 update(常用):如果没有schema就创建,有就更新。 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于差错,程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。项目部署后可以设置为false,提高运行效率-->
<property name="hibernate.show_sql">true</property>
<!--指定映射文件 -->
<mapping resource="learn\hibernate\bean\Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
2、具体表继承
(1)、实体类与以上没有差别,映射配置文件,代码如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="learn.hibernate.bean">
<class name="Person" table="t_person">
<id name="id" column="person_id">
<generator class="native"/>
</id>
<property name="name" column="t_name"/>
<property name="age"/>
<property name="passwork"/>
<property name="birthday"/> <!-- 通过 joined-subclass 配置子类 -->
<joined-subclass name="Student" table="t_student">
<key column="s_id"/>
<property name="number"/>
<property name="score"/>
</joined-subclass>
</class>
</hibernate-mapping>
(2)、测试类,代码如下:
package learn.hibernate.test; import static org.junit.Assert.*; import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set; import learn.hibernate.bean.Person;
import learn.hibernate.bean.Student; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class TestHibernate { SessionFactory factory = null;
Session session = null;
Transaction tx = null; /**
* 测试之前初始化数据
* @throws Exception
*/
@SuppressWarnings("deprecation")
@Before
public void setUp() throws Exception {
System.out.println("---------初始化数据----------"); Configuration config = new Configuration().configure();
ServiceRegistry sr = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
factory = config.buildSessionFactory(sr);
session = factory.openSession();
} /**
* 测试之后释放(销毁)数据
* @throws Exception
*/
@After
public void tearDown() throws Exception {
System.out.println("---------释放数据----------");
if(session.isOpen()){
session.close();
}
} @Test
public void testAdd(){
Student stu = new Student("hwl", 19, 123456, new Date(), 122, 99.0F);
tx = session.beginTransaction();
session.persist(stu);
tx.commit();
} @Test
public void testGet(){
Person p = (Person)session.get(Person.class, 1);
System.out.println(p);
}
}
3、每个具体类一个表
(1)、映射配置文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="learn.hibernate.bean">
<class name="Person" table="t_person">
<id name="id" column="person_id">
<generator class="hilo"/>
</id>
<property name="name" column="t_name"/>
<property name="age"/>
<property name="passwork"/>
<property name="birthday"/> <!-- 通过 union-subclass 配置子类 -->
<union-subclass name="Student" table="t_student">
<property name="number"/>
<property name="score"/>
</union-subclass>
</class>
</hibernate-mapping>
(2)、测试类:
package learn.hibernate.test; import static org.junit.Assert.*; import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set; import learn.hibernate.bean.Person;
import learn.hibernate.bean.Student; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class TestHibernate { SessionFactory factory = null;
Session session = null;
Transaction tx = null; /**
* 测试之前初始化数据
* @throws Exception
*/
@SuppressWarnings("deprecation")
@Before
public void setUp() throws Exception {
System.out.println("---------初始化数据----------"); Configuration config = new Configuration().configure();
ServiceRegistry sr = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
factory = config.buildSessionFactory(sr);
session = factory.openSession();
} /**
* 测试之后释放(销毁)数据
* @throws Exception
*/
@After
public void tearDown() throws Exception {
System.out.println("---------释放数据----------");
if(session.isOpen()){
session.close();
}
} @Test
public void testAdd(){
Student stu = new Student("hwl", 19, 123456, new Date(), 122, 99.0F);
tx = session.beginTransaction();
session.persist(stu);
tx.commit();
} @Test
public void testGet(){
Person p = (Person)session.get(Person.class, 1);
System.out.println(p);
}
}
Hibernate学习---第八节:继承关系的映射配置的更多相关文章
- [原创]java WEB学习笔记81:Hibernate学习之路--- 对象关系映射文件(.hbm.xml):hibernate-mapping 节点,class节点,id节点(主键生成策略),property节点,在hibernate 中 java类型 与sql类型之间的对应关系,Java 时间和日期类型的映射,Java 大对象类型 的 映射 (了解),映射组成关系
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- hibernate学习(5)——多对多关系映射
1.创建实体和映射 package com.alice.hibernate03.vo; import java.util.HashSet; import java.util.Set; public c ...
- hibernate学习(设计一对一 关系 映射)
//主表 package org.crazy.app.domain; import javax.persistence.*; @Entity @Table(name="person_inf& ...
- 【hibernate学习杂记】维护关系的一方和不维护关系的一方的区别与联系
双向多对一/一对多例子 维护关系一方为User:多方 不维护关系的一方为Group:一方 以下是多方代码: package Hibernate_demo1.Demo8.Entity.OneToMany ...
- Hibernate单向多对一对象关系模型映射
单向的many-to-one 案例: 班级和学生 父亲和子女 单向:只能由其中一方维护关系 Many-to-one中有many的一方法维护或者体现两者之间的关系. 单向的many-to-one描述学生 ...
- Hibernate之jpa实体映射的三种继承关系
在JPA中,实体继承关系的映射策略共有三种:单表继承策略(table per class).Joined策略(table per subclass)和Table_PER_Class策略. 1.单表继承 ...
- Hibernate注解方式配置-继承关系
在JPA中,实体继承关系的映射策略共有三种:单表继承策略(table per class).Joined策略(table per subclass)和Table_PER_Class策略. 1.单表继承 ...
- sqlmap映射继承机制及映射字段顺序与SQL查询字段顺序无关
<typeAlias alias="TblSpPartsinfo" type="com.bn.car.biz.supply.dao.po.PartsInfoPO&q ...
- Django ORM的继承关系
ORM中通常将对象引用映射到外键,但是对于继承,关系数据库中没有自然有效的方法来对应.从数据存储的角度来看,在映射继承关系时,可以采用几种方式(参考JPA中的InheritanceType.定义): ...
随机推荐
- php 生成下载连接
public function showdownload(){ $file_url=$_GET['url']; $new_name='激活码'; if(!isset($file_url)||trim( ...
- vue面试题,知识点汇总(有答案)
一. Vue核心小知识点 1.vue中 key 值的作用 key 的特殊属性主要用在 Vue的虚拟DOM算法,在新旧nodes对比时辨识VNodes.如果不使用key,Vue会使用一种最大限度减少动态 ...
- Coursera machine learning 第二周 quiz 答案 Linear Regression with Multiple Variables
https://www.coursera.org/learn/machine-learning/exam/7pytE/linear-regression-with-multiple-variables ...
- Cross Frame Script (跨框架脚本) 攻击
一.Cross Frame Script (跨框架脚本) 攻击 什么是Cross Frame Script? 很简单,做个实验就知道了.把下面的这段HTML代码另存为一个html文件,然后用ie浏览器 ...
- Lumen开发:lumen源码解读之初始化(2)——门面(Facades)与数据库(db)
版权声明:本文为博主原创文章,未经博主允许不得转载. 紧接上一篇 $app->withFacades();//为应用程序注册门面. $app->withEloquent();//为应用程序 ...
- CentOS 7.x samba 服务器安装
以下以root用户执行 1.安装: # yum install samba samba-client -y 2.设置开机启动: # systemctl enable smb.service ln ...
- leetCode 57.Insert Interval (插入区间) 解题思路和方法
Insert Interval Given a set of non-overlapping intervals, insert a new interval into the intervals ...
- git介绍和常用指令
Git介绍和常用指令 介绍:Git和SVN一样都是版本控制工具.不同的是Git是分布式的,SVN是集中式的.Git开始用可能感觉难点,等你用习惯了你就会觉得svn是有点恐怖.(如果一个项目有好多人一起 ...
- debian切换sh shell到bash shell
1 安装dpkg-reconfigure命令 切换到root账户即可. 2 dpkg-reconfigure dash 选择no
- Webpack探索【4】--- entry和output详解
本文主要讲entry和output相关内容.