刚刚学习完hibernate持久化框架,在这里记录一下学习的过程:一共分为一下几种关系映射:
1、单实体映射
2、继承关系映射(三种)
3、一对一关系映射
4、一对多关系映射
5、多对多关系映射
这篇文章只写了前两种方式,后面三种会在下一个里面详细的写;
注意,以下代码在使用注解方式时,我都把@Column这个注解省略了,因为我的列名和属性名都是相同的;如果不一样的话,需要加上这个注解;注解的具体写法在单实体映射中有体现;
- 单实体映射:基于xml
1、导入相关jar包
2、创建实体类Customer,以及实体类相关的配置文件(Customer.hbm.xml)
实体类相关代码:
package com.hibernate.entity;
public class Customer {
private int id;
private String name;
private int age;
private String descripe;
public String getDescripe() {
return descripe;
}
public void setDescripe(String descripe) {
this.descripe = descripe;
}
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Customer() {}
}
配置文件:
class中的name是实体类的名称,table是数据库表的名称,id是主键,有且只有一个,property是其他的属性,可以有多个;
其中,id中的generator子元素用来指定OID生成器,increment 采用 Hibernate 数值递增的方式;identity 采用数据库提供的自增长方式;
assigned 主键由应用逻辑产生。
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.entity">
<class name="Customer" table="customer">
<id name="id" type="int" >
<column name="id"></column>
<generator class="increment"></generator>
</id>
<property name="descripe" type="java.lang.String" column="descripe"></property>
<property name="age" type="int" column="age"></property>
<property name="name" type="java.lang.String" column="name"></property>
</class>
</hibernate-mapping>
3、创建hibernate工具类:所有的持久化框架都有这个工具类
package com.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
//持久化相关的接口;:对接口的实现
private static SessionFactory sessionFactory;
static {
final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
.configure().build();
try {
sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
}catch(Exception e) {
e.printStackTrace();
sessionFactory=null;
StandardServiceRegistryBuilder.destroy(registry);
}
}
public static SessionFactory getSessionFactory() {
// TODO Auto-generated method stub
return sessionFactory;
}
public static void closeSessionFactory() {
sessionFactory.close();
}
}
4、创建配置文件:连接到数据库,并且基于xml和注解在其中的配置不同
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/customer</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!--基于xml的配置 -->
<mapping resource="com/hibernate/entity/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5、最后进行测试
package com.hibernate.ui;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.hibernate.entity.Customer;
import com.hibernate.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
Customer customer=new Customer();
customer.setId(1);
customer.setDescripe("可乐加冰");
customer.setAge(22);
customer.setName("可乐加冰");
//增
session.save(customer);
//查(id=2)的数据
Customer customer2=session.get(Customer.class, new Integer(2))
//改
customer2.setName("可乐不加冰");
//删
sission.delete(customer);
tx.commit();
session.close();
HibernateUtil.closeSessionFactory();
}
}
完成!
- 单实体映射:基于注解
1、导入相关jar包
2、创建实体类,直接在实体类里面使用注解
package com.hibernate.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/*声明是一个实体类*/
/*为实体类指定对应的数据库表*/
@Entity
@Table(name="customer")
public class Customer {
//声明实体类的OID属性
//声明OID的生成策略
//使用hibernate提供的生成策略
@Id
@GeneratedValue(generator="increment_generator")
@GenericGenerator(name="increment_generator", strategy="increment")
private int id;
//当列名和属性名相同时,可以省略这个注解
@Column(name="name")
private String name;
private int age;
private String descripe;
public String getDescripe() {
return descripe;
}
public void setDescripe(String descripe) {
this.descripe = descripe;
}
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3、创建hibernate工具类:所有的持久化框架都有这个工具类
package com.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
//持久化相关的接口;:对接口的实现
private static SessionFactory sessionFactory;
static {
final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
.configure().build();
try {
sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
}catch(Exception e) {
e.printStackTrace();
sessionFactory=null;
StandardServiceRegistryBuilder.destroy(registry);
}
}
public static SessionFactory getSessionFactory() {
// TODO Auto-generated method stub
return sessionFactory;
}
public static void closeSessionFactory() {
sessionFactory.close();
}
}
4、创建配置文件:连接到数据库,并且基于xml和注解在其中的配置不同
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/customer</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 基于注解的配置 -->
<mapping class="com.hibernate.entity.Customer"/>
</session-factory>
</hibernate-configuration>
5、最后进行测试
package com.hibernate.ui;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.hibernate.entity.Customer;
import com.hibernate.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Customer customer=new Customer();
customer.setId(1);
customer.setDescripe("可乐加冰");
customer.setAge(23);
customer.setName("可乐加冰");
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
//增
session.save(customer);
//查
// Customer customer2=session.get(Customer.class, new Inter)
//改
// customer2.setName("yy");
//删
// sission.delete(customer2);
tx.commit();
session.close();
HibernateUtil.closeSessionFactory();
}
}
- 继承关系映射:每个具体类对应一张表(基于xml)
员工有按日结工资和按小时结工资:
1、导入相关jar包
2、编写实体类:一个父类和两个子类,并且两个具体的子类都有配置文件
父类
package com.hibernate.entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.hibernate.annotations.GenericGenerator;
public class Employee {
private int id;
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;
}
public Employee() {}
}
子类:hourlyEmployee
package com.hibernate.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
public class HourlyEmployee extends Employee {
private Double rate;
public Double getRate() {
return rate;
}
public void setRate(Double rate) {
this.rate = rate;
}
}
子类的配置文件:hourlyEmployee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.entity">
<class name="HourlyEmployee" table="hourlyEmployee">
<id name="id" column="id">
<generator class="increment"></generator>
</id>
<property name="name" column="name"></property>
<property name="rate" column="rate"></property>
</class>
</hibernate-mapping>
子类:salariedEmployee
package com.hibernate.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
public class SalariedEmployee extends Employee{
private Double salary;
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
子类的配置文件:salariedEmployee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.entity">
<class name="SalariedEmployee" table="salariedEmployee">
<id name="id" column="id">
<generator class="increment"></generator>
</id>
<property name="name" column="name"></property>
<property name="salary" column="salary"></property>
</class>
</hibernate-mapping>
3、编写hibernate:HibernateUtil工具类
package com.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
//持久化相关的接口;:对接口的实现
private static SessionFactory sessionFactory;
static {
final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
.configure().build();
try {
sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
}catch(Exception e) {
e.printStackTrace();
sessionFactory=null;
StandardServiceRegistryBuilder.destroy(registry);
}
}
public static SessionFactory getSessionFactory() {
// TODO Auto-generated method stub
return sessionFactory;
}
public static void closeSessionFactory() {
sessionFactory.close();
}
}
4、创建配置文件:连接到数据库(hibernate.cfg.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 用xml进行配置的话,是下面两行代码 -->
<mapping resource="com/hibernate/entity/HourlyEmployee.hbm.xml"/>
<mapping resource="com/hibernate/entity/SalariedEmployee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5、编写测试类
package com.hibernate.ui;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.HourlyEmployee;
import com.hibernate.entity.SalariedEmployee;
import com.hibernate.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
/*
*
*继承关系映射
* 基于注解和基于xml实现的两个类之间的继承关系的第一种方法:
* 每个具体的类对应一张表,来完成继承关系(Table per concrete class)
* Table per concrete class
* Table per class hierarchy
* Table per class
*
* */
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
HourlyEmployee he=new HourlyEmployee();
he.setId(1);
he.setName("可乐");
he.setRate(700.0);
SalariedEmployee se=new SalariedEmployee();
se.setId(1);
se.setName("加冰");
se.setSalary(5000.0);
//增
session.save(he);
session.save(se);
tx.commit();
session.close();
HibernateUtil.closeSessionFactory();
}
}
- 继承关系映射:每个具体类对应一张表(基于注解)
1、导入jar包
2、编写实体类,以及在实体类中进行配置
继承父类的一些属性,但不用父类作为映射实体时使用注解:@MappedSuperclass。
父类:
package com.hibernate.entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.hibernate.annotations.GenericGenerator;
@MappedSuperclass
public class Employee {
@Id
@GeneratedValue(generator="increment_generator")
@GenericGenerator(name="increment_generator",strategy="increment")
private int id;
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;
}
public Employee() {}
}
子类:hourlyEmployee
package com.hibernate.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name="hourlyemployee")
public class HourlyEmployee extends Employee {
private Double rate;
public Double getRate() {
return rate;
public void setRate(Double rate) {
this.rate = rate;
}
}
子类:SalariedEmployee
package com.hibernate.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name="salariedemployee")
public class SalariedEmployee extends Employee{
private Double salary;
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
3、编写hibernate工具类
package com.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
//持久化相关的接口;:对接口的实现
private static SessionFactory sessionFactory;
static {
final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
.configure().build();
try {
sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
}catch(Exception e) {
e.printStackTrace();
sessionFactory=null;
StandardServiceRegistryBuilder.destroy(registry);
}
}
public static SessionFactory getSessionFactory() {
// TODO Auto-generated method stub
return sessionFactory;
}
public static void closeSessionFactory() {
sessionFactory.close();
}
}
4、编写配置文件:hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 基于注解的配置 -->
<mapping class="com.hibernate.entity.HourlyEmployee"/>
<mapping class="com.hibernate.entity.SalariedEmployee"/>
<mapping class="com.hibernate.entity.Employee"/>
</session-factory>
</hibernate-configuration>
5、编写测试文件进行测试
package com.hibernate.ui;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.HourlyEmployee;
import com.hibernate.entity.SalariedEmployee;
import com.hibernate.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
/*
*
* 继承关系映射
* 基于注解和基于xml实现的两个类之间的继承关系的第一种方法:
* 每个具体的类对应一张表,来完成继承关系(Table per concrete class)
* Table per concrete class
* Table per class hierarchy
* Table per class
*
* */
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
HourlyEmployee he=new HourlyEmployee();
he.setId(1);
he.setName("cola");
he.setRate(700.0);
SalariedEmployee se=new SalariedEmployee();
se.setId(1);
se.setName("coll");
se.setSalary(5000.0);
//增
session.save(he);
session.save(se);
tx.commit();
session.close();
HibernateUtil.closeSessionFactory();
}
}
- 继承关系映射:父类对应一张表(基于xml)
1、导入jar包
2、编写实体类以及实体类的配置文件
父类:
package com.hibernate.entity;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
public class Employee {
private int id;
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;
}
public Employee() {}
}
父类的配置文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.entity">
<!-- 如果employee这个类的本身也需要被持久化,可以在class元素中设置discriminator-value属性的值 -->
<class name="Employee" table="employeen">
<id name="id">
<generator class="increment"></generator>
</id>
<!-- 必须紧跟id元素:用于指定表中区分子类类型的字段-->
<discriminator column="employee_type"></discriminator>
<property name="name"></property>
<!-- subclass元素中的name 属性:子类类名;
discriminator-value 属性:子类中区分类型字段的取值;
property子元素:映射子类属性。 -->
<subclass name="HourlyEmployee" discriminator-value="HE">
<property name="rate"></property>
</subclass>
<subclass name="SalariedEmployee" discriminator-value="SE">
<property name="salary"></property>
</subclass>
</class>
</hibernate-mapping>
子类:hourlyEmployee
package com.hibernate.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
public class HourlyEmployee extends Employee {
private Double rate;
public Double getRate() {
return rate;
}
public void setRate(Double rate) {
this.rate = rate;
}
}
子类:salariedEmployee
package com.hibernate.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
public class SalariedEmployee extends Employee{
private Double salary;
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
3、编写hibernate工具类
package com.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HiernateUtil {
//持久化相关的接口;:对接口的实现
private static SessionFactory sessionFactory;
static {
final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
.configure().build();
try {
sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
}catch(Exception e) {
e.printStackTrace();
sessionFactory=null;
StandardServiceRegistryBuilder.destroy(registry);
}
}
public static SessionFactory getSessionFactory() {
// TODO Auto-generated method stub
return sessionFactory;
}
public static void closeSessionFactory() {
sessionFactory.close();
}
}
4、编写配置文件:hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 用xml进行配置 -->
<mapping resource="com/hibernate/entity/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5、编写测试文件进行测试
package com.hibernate.ui;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.HourlyEmployee;
import com.hibernate.entity.SalariedEmployee;
import com.hibernate.util.HiernateUtil;
public class Test {
public static void main(String[] args) {
/*
*
*继承关系映射
* 基于xml实现的两个类之间的继承关系的第二种方法:
* 使用父类对应一个表来完成关系映射(Table per class hierarchy)
* 通过父类去映射一个表
* 使用的数据库是一个表
* Table per concrete class
* Table per class hierarchy
* Table per class
*
* */
Session session=HiernateUtil.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
HourlyEmployee he=new HourlyEmployee();
he.setId(1);
he.setName("cola");
he.setRate(700.0);
SalariedEmployee se=new SalariedEmployee();
se.setId(1);
se.setName("cool");
se.setSalary(5000.0);
//增
session.save(he);
session.save(se);
tx.commit();
session.close();
HiernateUtil.closeSessionFactory();
}
}
- 继承关系映射:父类对应一张表(基于注解)
1、导入jar包
2、编写实体类
父类:
package com.hibernate.entity;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="employeen")
/*指定策略*/
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
/*指定区分的字段名*/
@DiscriminatorColumn(name="employee_type")
public class Employee {
@Id
@GeneratedValue(generator="increment_generator")
@GenericGenerator(name="increment_generator",strategy="increment")
private int id;
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;
}
public Employee() {}
}
子类:hourlyEmployee
package com.hibernate.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@DiscriminatorValue(value="HE")
public class HourlyEmployee extends Employee {
private Double rate;
public Double getRate() {
return rate;
}
public void setRate(Double rate) {
this.rate = rate;
}
}
子类:salariedEmployee
package com.hibernate.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@DiscriminatorValue(value="SE")
public class SalariedEmployee extends Employee{
private Double salary;
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
3、编写hibernate工具类
package com.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HiernateUtil {
//持久化相关的接口;:对接口的实现
private static SessionFactory sessionFactory;
static {
final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
.configure().build();
try {
sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
}catch(Exception e) {
e.printStackTrace();
sessionFactory=null;
StandardServiceRegistryBuilder.destroy(registry);
}
}
public static SessionFactory getSessionFactory() {
// TODO Auto-generated method stub
return sessionFactory;
}
public static void closeSessionFactory() {
sessionFactory.close();
}
}
4、编写配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 基于注解的配置 -->
<mapping class="com.hibernate.entity.HourlyEmployee"/>
<mapping class="com.hibernate.entity.SalariedEmployee"/>
<mapping class="com.hibernate.entity.Employee"/>
</session-factory>
</hibernate-configuration>
5、编写测试类文件
package com.hibernate.ui;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.HourlyEmployee;
import com.hibernate.entity.SalariedEmployee;
import com.hibernate.util.HiernateUtil;
public class Test {
public static void main(String[] args) {
/*
* 继承关系映射
* 基于注解和基于xml实现的两个类之间的继承关系的第二种方法:
* 使用父类对应一个表来完成关系映射(Table per class hierarchy)
* 通过父类去映射一个表
* 使用的数据库是一个表
* Table per concrete class
* Table per class hierarchy
* Table per class
*
* */
Session session=HiernateUtil.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
HourlyEmployee he=new HourlyEmployee();
he.setId(1);
he.setName("cola");
he.setRate(700.0);
SalariedEmployee se=new SalariedEmployee();
se.setId(1);
se.setName("coll");
se.setSalary(5000.0);
//增
session.save(he);
session.save(se);
tx.commit();
session.close();
HiernateUtil.closeSessionFactory();
}
}
- 继承关系映射:每个类对应一张表(基于xml)
1、导入相关jar包
2、编写三个实体类和父类的映射文件
父类:
package com.hibernate.entity;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
public class Employee {
private int id;
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;
}
public Employee() {}
}
子类:hourlyEmployee
package com.hibernate.entity;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
public class HourlyEmployee extends Employee {
private Double rate;
public Double getRate() {
return rate;
}
public void setRate(Double rate) {
this.rate = rate;
}
}
子类:salariedEmployee
package com.hibernate.entity;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
public class SalariedEmployee extends Employee{
private Double salary;
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
父类映射文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernate.entity">
<class name="Employee" table="employee1">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<joined-subclass name="HourlyEmployee" table="hourlyemployee1">
<key column="employeeID"></key>
<property name="rate"></property>
</joined-subclass>
<joined-subclass name="SalariedEmployee" table="salariedemployee1">
<key column="employeeID"></key>
<property name="salary"></property>
</joined-subclass>
</class>
</hibernate-mapping>
3、编写hibernate工具类
package com.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HiernateUtil {
//持久化相关的接口;:对接口的实现
private static SessionFactory sessionFactory;
static {
final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
.configure().build();
try {
sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
}catch(Exception e) {
e.printStackTrace();
sessionFactory=null;
StandardServiceRegistryBuilder.destroy(registry);
}
}
public static SessionFactory getSessionFactory() {
// TODO Auto-generated method stub
return sessionFactory;
}
public static void closeSessionFactory() {
sessionFactory.close();
}
}
4、编写配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 用xml进行配置 -->
<mapping resource="com/hibernate/entity/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5、编写测试类
package com.hibernate.ui;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.HourlyEmployee;
import com.hibernate.entity.SalariedEmployee;
import com.hibernate.util.HiernateUtil;
public class Test {
public static void main(String[] args) {
/*
*
* 继承关系映射
* 基于xml实现的两个类之间的继承关系的第三种方法:
* 每个类对应一张表,来完成继承关系(com.hibernate.ui)
* Table per concrete class
* Table per class hierarchy
* Table per class
*
* */
Session session=HiernateUtil.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
HourlyEmployee he=new HourlyEmployee();
he.setId(1);
he.setName("cola");
he.setRate(700.0);
SalariedEmployee se=new SalariedEmployee();
se.setId(1);
se.setName("cool");
se.setSalary(5000.0);
//增
session.save(he);
session.save(se);
tx.commit();
session.close();
HiernateUtil.closeSessionFactory();
}
}
-
继承关系映射:每个类对应一张表(基于注解)
1、导入相关jar包
2、编写三个实体类和父类的映射文件
父类:
package com.hibernate.entity;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="employee1")
/*指定策略*/
@Inheritance(strategy=InheritanceType.JOINED)
public class Employee {
@Id
@GeneratedValue(generator="increment_generator")
@GenericGenerator(name="increment_generator",strategy="increment")
private int id;
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;
}
public Employee() {}
}
子类:hourlyEmployee
package com.hibernate.entity;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
@Entity
@Table(name="hourlyemployee1")
@PrimaryKeyJoinColumn(name="employeeID")
public class HourlyEmployee extends Employee {
private Double rate;
public Double getRate() {
return rate;
}
public void setRate(Double rate) {
this.rate = rate;
}
}
子类:salariedEmplyee
package com.hibernate.entity;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
@Entity
@Table(name="salariedemployee1")
@PrimaryKeyJoinColumn(name="employeeID")
public class SalariedEmployee extends Employee{
private Double salary;
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
3、编写hibernate工具类
package com.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HiernateUtil {
//持久化相关的接口;:对接口的实现
private static SessionFactory sessionFactory;
static {
final StandardServiceRegistry registry=new StandardServiceRegistryBuilder()
.configure().build();
try {
sessionFactory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
}catch(Exception e) {
e.printStackTrace();
sessionFactory=null;
StandardServiceRegistryBuilder.destroy(registry);
}
}
public static SessionFactory getSessionFactory() {
// TODO Auto-generated method stub
return sessionFactory;
}
public static void closeSessionFactory() {
sessionFactory.close();
}
}
4、编写配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 基于注解的配置 -->
<mapping class="com.hibernate.entity.HourlyEmployee"/>
<mapping class="com.hibernate.entity.SalariedEmployee"/>
<mapping class="com.hibernate.entity.Employee"/>
</session-factory>
</hibernate-configuration>
5、编写测试类
package com.hibernate.ui;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.HourlyEmployee;
import com.hibernate.entity.SalariedEmployee;
import com.hibernate.util.HiernateUtil;
public class Test {
public static void main(String[] args) {
/*
*
* 继承关系映射
* 基于注解l实现的两个类之间的继承关系的第三种方法:
* 每个类对应一张表,来完成继承关系(com.hibernate.ui)
* Table per concrete class
* Table per class hierarchy
* Table per class
*
* */
Session session=HiernateUtil.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
HourlyEmployee he=new HourlyEmployee();
he.setId(1);
he.setName("cola");
he.setRate(700.0);
SalariedEmployee se=new SalariedEmployee();
se.setId(1);
se.setName("cool");
se.setSalary(5000.0);
//增
session.save(he);
session.save(se);
tx.commit();
session.close();
HiernateUtil.closeSessionFactory();
}
}