一 配置文件
<?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.Customer"/>
<mapping class="org.crazyit.app.domain.Employee"/>
<mapping class="org.crazyit.app.domain.Manager"/>
</session-factory>
</hibernate-configuration>
二 PO
1 Address
package org.crazyit.app.domain;
public class Address
{
// 定义代表该Address详细信息的成员变量
private String detail;
// 定义代表该Address邮编信息的成员变量
private String zip;
// 定义代表该Address国家信息的成员变量
private String country;
// 无参数的构造器
public Address()
{
}
// 初始化全部成员变量的构造器
public Address(String detail , String zip , String country)
{
this.detail = detail;
this.zip = zip;
this.country = country;
}
// detail的setter和getter方法
public void setDetail(String detail)
{
this.detail = detail;
}
public String getDetail()
{
return this.detail;
}
// zip的setter和getter方法
public void setZip(String zip)
{
this.zip = zip;
}
public String getZip()
{
return this.zip;
}
// country的setter和getter方法
public void setCountry(String country)
{
this.country = country;
}
public String getCountry()
{
return this.country;
}
}
2 Person
package org.crazyit.app.domain;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
@Entity
// 指定使用连接子类的映射策略
@Inheritance(strategy=InheritanceType.JOINED)
@Table(name="person_inf")
public class Person
{
// 标识属性
@Id @Column(name="person_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String name;
private char gender;
// 定义该Person实体的组件属性:address
@Embedded
@AttributeOverrides({
@AttributeOverride(name="detail",
column=@Column(name="address_detail")),
@AttributeOverride(name="zip",
column=@Column(name="address_zip")),
@AttributeOverride(name="country",
column=@Column(name="address_country"))
})
private Address address;
// 无参数的构造器
public Person()
{
}
// 初始化全部成员变量的构造器
public Person(Integer id , String name , char gender)
{
this.id = id;
this.name = name;
this.gender = gender;
}
// 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;
}
// gender的setter和getter方法
public void setGender(char gender)
{
this.gender = gender;
}
public char getGender()
{
return this.gender;
}
// address的setter和getter方法
public void setAddress(Address address)
{
this.address = address;
}
public Address getAddress()
{
return this.address;
}
}
3 Employee
package org.crazyit.app.domain;
import java.util.*;
import javax.persistence.*;
// 员工类继承了Person类
@Entity
@Table(name="employee_inf")
public class Employee extends Person
{
// 定义该员工职位的成员变量
private String title;
// 定义该员工工资的成员变量
private double salary;
// 定义和该员工保持关联的Customer关联实体
@OneToMany(cascade=CascadeType.ALL
, mappedBy="employee" , targetEntity=Customer.class)
private Set<Customer> customers
= new HashSet<>();
// 定义和该员工保持关联的Manager关联实体
@ManyToOne(cascade=CascadeType.ALL
,targetEntity=Manager.class)
@JoinColumn(name="manager_id", nullable=true)
private Manager manager;
// 无参数的构造器
public Employee()
{
}
// 初始化全部成员变量的构造器
public Employee(String title , double salary)
{
this.title = title;
this.salary = salary;
}
// title的setter和getter方法
public void setTitle(String title)
{
this.title = title;
}
public String getTitle()
{
return this.title;
}
// salary的setter和getter方法
public void setSalary(double salary)
{
this.salary = salary;
}
public double getSalary()
{
return this.salary;
}
// customers的setter和getter方法
public void setCustomers(Set<Customer> customers)
{
this.customers = customers;
}
public Set<Customer> getCustomers()
{
return this.customers;
}
// manager的setter和getter方法
public void setManager(Manager manager)
{
this.manager = manager;
}
public Manager getManager()
{
return this.manager;
}
}
4 Customer
package org.crazyit.app.domain;
import javax.persistence.*;
// 顾客类继承了Person类
@Entity
@Table(name="customer_inf")
public class Customer extends Person
{
// 顾客的评论信息
private String comments;
// 定义和该顾客保持关联的Employee关联实体
@ManyToOne(cascade=CascadeType.ALL
,targetEntity=Employee.class)
@JoinColumn(name="employee_id", nullable=true)
private Employee employee;
// 无参数的构造器
public Customer()
{
}
// 初始化comments成员变量的构造器
public Customer(String comments)
{
this.comments = comments;
}
// comments的setter和getter方法
public void setComments(String comments)
{
this.comments = comments;
}
public String getComments()
{
return this.comments;
}
// employee的setter和getter方法
public void setEmployee(Employee employee)
{
this.employee = employee;
}
public Employee getEmployee()
{
return this.employee;
}
}
5 Manager
package org.crazyit.app.domain;
import javax.persistence.*;
import java.util.Set;
import java.util.HashSet;
// 经理类继承员工类
@Entity
@Table(name="manager_inf")
public class Manager extends Employee
{
// 定义经理管辖部门的属性
private String department;
// 定义和该经理保持关联的Employee关联实体
@OneToMany(cascade=CascadeType.ALL
, mappedBy="manager" , targetEntity=Employee.class)
private Set<Employee> employees
= new HashSet<>();
// 无参数的构造器
public Manager()
{
}
// 初始化全部成员变量的构造器
public Manager(String department)
{
this.department = department;
}
// department的setter和getter方法
public void setDepartment(String department)
{
this.department = department;
}
public String getDepartment()
{
return this.department;
}
// employees的setter和getter方法
public void setEmployees(Set<Employee> employees)
{
this.employees = employees;
}
public Set<Employee> getEmployees()
{
return this.employees;
}
}
三 测试
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.*;
import org.crazyit.app.domain.*;
public class PersonManager
{
public static void main(String[] args)
{
PersonManager mgr = new PersonManager();
mgr.createAndStorePerson();
HibernateUtil.sessionFactory.close();
}
private void createAndStorePerson()
{
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
// 创建一个普通员工
Employee zhu = new Employee();
// 设置员工的基本属性
zhu.setName("老朱");
zhu.setTitle("项目组长");
zhu.setGender('男');
zhu.setSalary(4500);
// 设置员工的组件属性
zhu.setAddress(new Address("广州","523034","中国"));
// 创建第二个员工
Employee zhang = new Employee();
// 设置该员工的基本属性
zhang.setName("张美丽");
zhang.setTitle("项目分析");
zhang.setGender('女');
zhang.setSalary(5500);
// 设置该员工的组件属性
zhang.setAddress(new Address("广州","523034","中国"));
// 创建一个经理对象
Manager grace = new Manager();
// 设置经理对象的基本属性
grace.setName("Grace");
grace.setTitle("项目经理");
grace.setGender('女');
grace.setSalary(12000);
// 设置经理的组件属性
grace.setAddress(new Address("加州" , "523034" , "美国"));
// 设置经理的管辖部门属性
grace.setDepartment("研发部");
// 设置第二个员工和grace之间的关联关系
zhang.setManager(grace);
// 创建一个Customer对象
Customer he = new Customer();
// 设置Customer对象的基本属性
he.setName("小贺");
he.setGender('男');
// 设置Customer对象的组件属性
he.setAddress(new Address("湖南" , "233034" , "中国"));
he.setComments("喜欢购物");
// 建立Customer对象和grace对象的关联关系
he.setEmployee(grace);
// 创建一个普通Person对象
Person lee = new Person();
// 设置Person对象的基本属性
lee.setName("crazyit.org");
lee.setGender('男');
// 设置Person对象的组件属性
lee.setAddress(new Address("天河" , "434333" , "中国"));
// 持久化所有实体。
session.save(lee);
session.save(grace);
session.persist(zhu);
session.persist(zhang);
session.save(he);
tx.commit();
HibernateUtil.closeSession();
}
}
四 运行
Hibernate:
insert
into
person_inf
(address_country, address_detail, address_zip, gender, name)
values
(?, ?, ?, ?, ?)
Hibernate:
insert
into
person_inf
(address_country, address_detail, address_zip, gender, name)
values
(?, ?, ?, ?, ?)
Hibernate:
insert
into
employee_inf
(manager_id, salary, title, person_id)
values
(?, ?, ?, ?)
Hibernate:
insert
into
manager_inf
(department, person_id)
values
(?, ?)
Hibernate:
insert
into
person_inf
(address_country, address_detail, address_zip, gender, name)
values
(?, ?, ?, ?, ?)
Hibernate:
insert
into
employee_inf
(manager_id, salary, title, person_id)
values
(?, ?, ?, ?)
Hibernate:
insert
into
person_inf
(address_country, address_detail, address_zip, gender, name)
values
(?, ?, ?, ?, ?)
Hibernate:
insert
into
employee_inf
(manager_id, salary, title, person_id)
values
(?, ?, ?, ?)
Hibernate:
insert
into
person_inf
(address_country, address_detail, address_zip, gender, name)
values
(?, ?, ?, ?, ?)
Hibernate:
insert
into
customer_inf
(comments, employee_id, person_id)
values
(?, ?, ?)