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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。