Hibernate实战——组件属性包含的关联实体

一 配置

<?xml version="1.0" encoding="GBK"?>
<!-- 指定Hibernate配置文件的DTD信息 -->
<!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- hibernate-configuration是配置文件的根元素 -->
<hibernate-configuration>
     <session-factory>
           <!-- 指定连接数据库所用的驱动 -->
           <property  name="connection.driver_class">com.mysql.jdbc.Driver</property>
           <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
           <property  name="connection.url">jdbc:mysql://localhost/hibernate</property>
           <!-- 指定连接数据库的用户名 -->
           <property name="connection.username">root</property>
           <!-- 指定连接数据库的密码 -->
           <property name="connection.password">32147</property>
           <!-- 指定连接池里最大连接数 -->
           <property  name="hibernate.c3p0.max_size">20</property>
           <!-- 指定连接池里最小连接数 -->
           <property name="hibernate.c3p0.min_size">1</property>
           <!-- 指定连接池里连接的超时时长 -->
           <property  name="hibernate.c3p0.timeout">5000</property>
           <!-- 指定连接池里最大缓存多少个Statement对象 -->
           <property  name="hibernate.c3p0.max_statements">100</property>
           <property  name="hibernate.c3p0.idle_test_period">3000</property>
           <property  name="hibernate.c3p0.acquire_increment">2</property>
           <property  name="hibernate.c3p0.validate">true</property>
           <!-- 指定数据库方言 -->
           <property  name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
           <!-- 根据需要自动创建数据库 -->
           <property name="hbm2ddl.auto">update</property>
           <!-- 显示Hibernate持久化操作所生成的SQL -->
           <property name="show_sql">true</property>
           <!-- 将SQL脚本进行格式化后再输出 -->
           <property name="hibernate.format_sql">true</property>
           <!-- 罗列所有持久化类的类名 -->
           <mapping class="org.crazyit.app.domain.Person"/>
           <mapping class="org.crazyit.app.domain.School"/>
     </session-factory>
</hibernate-configuration>

二 PO

1 Person

package org.crazyit.app.domain;

import java.util.*;

import javax.persistence.*;

@Entity
@Table(name="person_inf")
public class Person
{
    // 标识属性
    @Id @Column(name="person_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    // Person的name属性
    private String name;
    // 保留Person的age属性
    private int age;
    // 定义一个组件属性
    private Address address;

    // id的setter和getter方法
    public void setId(Integer id)
    {
        this.id = id;
    }
    public Integer getId()
    {
        return this.id;
    }

    // name的setter和getter方法
    public void setName(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return this.name;
    }

    // age的setter和getter方法
    public void setAge(int age)
    {
        this.age = age;
    }
    public int getAge()
    {
        return this.age;
    }

    // address的setter和getter方法
    public void setAddress(Address address)
    {
        this.address = address;
    }
    public Address getAddress()
    {
        return this.address;
    }
}

2 Address

package org.crazyit.app.domain;

import java.util.*;

import javax.persistence.*;
import org.hibernate.annotations.Parent;

@Embeddable
public class Address
{
    // 代表地址详细信息的成员变量
    @Column(name="address_detail")
    private String addressDetail;
    // 定义该组件属性所在的包含实体
    @Parent
    private Person person;
    // 定义保留关联实体的Set集合
    @OneToMany(targetEntity=School.class)
    // 映射外键列,此处告诉Hibernate在School实体对应的表中增加外键列
    // 该外键列的列名为address_id,参照person_inf表的peron_id主键列
    @JoinColumn(name="address_id", referencedColumnName="person_id")
    private Set<School> schools
        = new HashSet<>();

    public Address(){}

    public Address(String addressDetail)
    {
        this.addressDetail = addressDetail;
    }

    // addressDetail的setter和getter方法
    public void setAddressDetail(String addressDetail)
    {
        this.addressDetail = addressDetail;
    }
    public String getAddressDetail()
    {
        return this.addressDetail;
    }

    // person的setter和getter方法
    public void setPerson(Person person)
    {
        this.person = person;
    }
    public Person getPerson()
    {
        return this.person;
    }

    // schools的setter和getter方法
    public void setSchools(Set<School> schools)
    {
        this.schools = schools;
    }
    public Set<School> getSchools()
    {
        return this.schools;
    }
}

3 School

package org.crazyit.app.domain;
import javax.persistence.*;

@Entity
@Table(name="school_inf")
public class School
{
     // 定义标识属性
     @Id @Column(name="school_id")
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private Integer id;
     // 定义该学校的name成员变量
     private String name;
     // 无参数的构造器
     public School()
     {
     }
     // 初始化全部成员变量的构造器
     public School(String name)
     {
           this.name = name;
     }
     // id的setter和getter方法
     public void setId(Integer id)
     {
           this.id = id;
     }
     public Integer getId()
     {
           return this.id;
     }
     // name的setter和getter方法
     public void setName(String name)
     {
           this.name = name;
     }
     public String getName()
     {
           return this.name;
     }
}

三 测试

1 工具类

package lee;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*;

public class HibernateUtil
{
    public static final SessionFactory sessionFactory;
    static
    {
        try
        {
            // 使用默认的hibernate.cfg.xml配置文件创建Configuration实例
            Configuration cfg = new Configuration()
                .configure();
            // 以Configuration实例来创建SessionFactory实例
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).build();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        }
        catch (Throwable ex)
        {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    // ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
    public static final ThreadLocal<Session> session
        = new ThreadLocal<Session>();

    public static Session currentSession()
        throws HibernateException
    {
        Session s = session.get();
        // 如果该线程还没有Session,则创建一个新的Session
        if (s == null)
        {
            s = sessionFactory.openSession();
            // 将获得的Session变量存储在ThreadLocal变量session里
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException
    {
        Session s = session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}

2 测试类

package lee;

import org.hibernate.Transaction;
import org.hibernate.Session;

import java.util.Date;
import java.util.Set;
import java.util.HashSet;

import org.crazyit.app.domain.*;

public class PersonManager
{
    public static void main(String[] args)
    {
        PersonManager mgr = new PersonManager();
        mgr.testPerson();
        HibernateUtil.sessionFactory.close();
    }
    // 保存Person和School对象
    private void testPerson()
    {
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        // 创建一个Person对象
        Person p = new Person();
        // 设置Person的name为crazyit
        p.setName("crazyit");
        p.setAge(21);
        session.save(p);
        // 创建一个Address对象
        Address a = new Address("广州天河");
        // 设置Person对象的Address属性
        p.setAddress(a);
        // 创建2个School对象
        School s1 = new School("疯狂iOS训练营");
        School s2 = new School("疯狂Java训练营");
        // 保存2个School实体
        session.save(s1);
        session.save(s2);
        // 设置Address对象和两个School的关联关系
        a.getSchools().add(s1);
        a.getSchools().add(s2);
        tx.commit();
        HibernateUtil.closeSession();
    }
}

四 测试结果

Hibernate:
    insert
    into
        person_inf
        (address_detail, age, name)
    values
        (?, ?, ?)
Hibernate:
    insert
    into
        school_inf
        (name)
    values
        (?)
Hibernate:
    insert
    into
        school_inf
        (name)
    values
        (?)
Hibernate:
    update
        person_inf
    set
        address_detail=?,
        age=?,
        name=?
    where
        person_id=?
Hibernate:
    update
        school_inf
    set
        address_id=?
    where
        school_id=?
Hibernate:
    update
        school_inf
    set
        address_id=?
    where
        school_id=?

Hibernate实战——组件属性包含的关联实体

Hibernate实战——组件属性包含的关联实体

上一篇:爬虫入门之xpath的使用


下一篇:数据库的备份和还原