时间:2017年07月11日星期二
说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com
教学源码:无
学习源码:https://github.com/zccodere/s...
第一章:类级别注解
1-1 本章简介
本章简介
Hibernate注解简介
JPA与Hibernate的关系
Hibernate注解分类
@Entity
@Table
@Embeddable
schema与catalog
Hibernate注解简介
使用注解的目的:为了简化繁琐的ORM映射文件(*.hbm)的配置
JPA与Hibernate的关系
什么是JPA
全称Java Persistence API
JPA注解是JavaEE的规范和标准
JPA和Hibernate的关系:
JPA是标准接口
Hibernate是实现,但是其功能是JPA的超集
Hibernate如何实现与JPA的关系
通过hibernate-annotation
hibernate-entitymanager
hibernate-core三个组件来实现
一般在实际开发中,优先考虑使用JPA注解
这样更有利于程序的移植和扩展
Hibernate注解的分类
类级别注解
属性级别注解
映射关系注解
类级别注解
@Entity:表示一个实体,一个实体对应数据库一张表
@Table:配置表的属性
@Embeddable:表示当前类是一个嵌入类
1-2 准备工作
回顾hibernate.cfg.xml
创建一个名为hibernateca的maven项目,并添加相关依赖。POM文件如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myimooc</groupId>
<artifactId>hibernateca</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hibernateca</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.4.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
在src/main/ resources目录下,创建hibernate.cfg.xml文件
<!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.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">
<![CDATA[
jdbc:mysql://localhost:3306/hibernatemtm?useUnicode=true&characterEncoding=utf8
]]>
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 指定映射文件的路径 -->
<mapping class="com.myimooc.hibernateca.entity.Students"/>
</session-factory>
</hibernate-configuration>
1-3 @Entity注解
@Entity
@Entity:映射实体类
@Entity(name=”tableName”)
name:可选,对应数据库中的一个表。若表名与实体类名相同,则可以省略
注意:使用@Entity时必须指定实体类的主键属性
代码演示
1.编写Students实体类
package com.myimooc.hibernateca.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* 学生实体类
* @author ZhangCheng on 2017-07-12
*
*/
//JPA注解
@Entity(name="t_students")
public class Students {
/** 学号 */
@Id
private Integer sid;
/** 姓名 */
private String sname;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday
+ ", major=" + major + "]";
}
public Students() {
super();
}
public Students(Integer sid, String sname, String gender, Date birthday, String major) {
super();
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
this.address = address;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
2.配置映射
<!-- 指定映射文件的路径 -->
<mapping class="com.myimooc.hibernateca.entity.Students"/>
3.编写StudentTest测试类
package com.myimooc.hibernateca.entity;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;
/**
* 单元测试类
* @author ZhangCheng on 2017-07-12
*
*/
public class StudentsTest {
@Test
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
@SuppressWarnings("unused")
SessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry);
SchemaExport export = new SchemaExport(config);
export.create(true, true);
}
}
1-4 @Table注解
@Table
@Table(name=””,catalog=””,schema=””)
@Entity配置使用,只能标注在实体的class定义处,表示实体对应的数据库表的信息
name:可选,映射表的名称,默认表名和实体名称一致,只有在不一致的情况下才需要指定表名
catalog:可选,表示目录Catalog名称,默认为Catalog(“”)
schema:可选,表示模式Schema名称,默认为Schema(“”)
schema与catalog示意图
schema与catalog
从实现的角度来看,各种数据库系统对Catalog和Schema的支持和实现方式千差万别的
供应商的支持和实现
代码演示,修改Student类如下
package com.myimooc.hibernateca.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* 学生实体类
* @author ZhangCheng on 2017-07-12
*
*/
//JPA注解
//@Entity(name="t_students")
@Entity
@Table(name="t_students",schema="hibernatemtm")
public class Students {
/** 学号 */
@Id
private Integer sid;
/** 姓名 */
private String sname;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday
+ ", major=" + major + "]";
}
public Students() {
super();
}
public Students(Integer sid, String sname, String gender, Date birthday, String major) {
super();
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
1-5 @Embeddable注解
@Embeddable
@Embeddable表示一个非Entity类可以嵌入到另一个Entity类中作为属性而存在
代码演示
1.编写Address类
package com.myimooc.hibernateca.entity;
import javax.persistence.Embeddable;
/**
* 地址类(嵌入类)
* @author ZhangCheng on 2017-07-12
*
*/
// 表示是一个嵌入类,这个类的对象在另一个实体类中充当属性
@Embeddable
public class Address {
/** 邮编 */
private String postCode;
/** 地址 */
private String address;
/** 联系电话 */
private String phone;
@Override
public String toString() {
return "Address [postCode=" + postCode + ", address=" + address + ", phone=" + phone + "]";
}
public Address() {
}
public Address(String postCode, String address, String phone) {
this.postCode = postCode;
this.address = address;
this.phone = phone;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
2.修改Student类如下
package com.myimooc.hibernateca.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* 学生实体类
* @author ZhangCheng on 2017-07-12
*
*/
//JPA注解
//@Entity(name="t_students")
@Entity
@Table(name="t_students",schema="hibernatemtm")
public class Students {
/** 学号 */
@Id
private Integer sid;
/** 姓名 */
private String sname;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
/** 地址 */
private Address address;
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday
+ ", major=" + major + "]";
}
public Students() {
super();
}
public Students(Integer sid, String sname, String gender, Date birthday, String major,Address address) {
super();
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
第二章:属性级别注解
2-1 本章简介
Hibernate属性级别注解
添加方式:写在属性字段方面 或 写在属性的get访问器的上面
@Id
-@SequenceGenerator
@GeneratedValue
@Column
@Embedded
@EmbeddedId
-@Lob
-@Version
-@Basic
@Transient
2-2 @Id注解
@Id
@Id:必须,定义了映射到数据库表的主键的属性,
一个实体类可以有一个或者多个属性被映射为主键,
可置于主键属性或者get方法前
注意:如果有多个属性定义为主键属性,
该实体类必须实现serializable接口
拷贝hibernateca项目,重命名为hibernateaa,POM与Hibernate配置文件均相同
2-3 @GeneratedValue注解(一)
@GeneratedValue
@GeneratedValue(strategy=GenerationType,generator=””)
可选,用户定义主键生成策略
strategy表示主键生成策略,取值有
GenerationType.AUTO:根据底层数据库自动选择(默认)
GenerationType.INDENTITY:根据数据库的Identity字段生成
GenerationType.SEQUENCE:使用Sequence来决定主键的取值
GenerationType.TABLE:使用指定表来决定主键取值,结合@TableGenerator使用
使用示例
2-4 @GeneratedValue注解(二)
代码演示
1.修改Students类
package com.myimooc.hibernateaa.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.GenericGenerator;
/**
* 学生实体类
* @author ZhangCheng on 2017-07-12
*
*/
@SuppressWarnings("unused")
@Entity
@Table(name="t_students",schema="hibernatemtm")
public class Students {
/** 学号 */
/* 方式一:使用自动生成主键
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer sid;
*/
/* 方式二:使用手工赋值方式生成主键
@Id
@GeneratedValue(generator="sid")
@GenericGenerator(name="sid",strategy="assigned")//
@Column(length=8)
private String sid;
*/
/* 方式三:使用复合主键 */
@EmbeddedId
private StudentsPK pk;
/** 姓名 */
private String sname;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
/** 薪水 */
@Transient // 表示该属性不会被ORM映射到表里的字段
private double salary;
/** 地址 */
@Embedded
private Address address;
@Override
public String toString() {
return "Students [pk=" + pk + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday + ", major="
+ major + ", salary=" + salary + ", address=" + address + "]";
}
public Students() {
super();
}
public Students(StudentsPK pk, String sname, String gender, Date birthday, String major,Address address) {
super();
this.pk = pk;
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
this.address = address;
}
public Students(StudentsPK pk, String sname, String gender, Date birthday, String major, double salary,
Address address) {
super();
this.pk = pk;
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
this.salary = salary;
this.address = address;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public StudentsPK getPk() {
return pk;
}
public void setPk(StudentsPK pk) {
this.pk = pk;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
2-5 @GeneratedValue注解(三)
代码演示
1.修改StudentsTest类
package com.myimooc.hibernateaa.entity;
import java.util.Date;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 单元测试类
* @author ZhangCheng on 2017-07-12
*
*/
@SuppressWarnings("unused")
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
// SchemaExport export = new SchemaExport(config);
// export.create(true, true);
}
@Test
public void addStudents(){
// 创建会话
Session session = sessionFactory.getCurrentSession();
// 创建事务
Transaction tx = session.beginTransaction();
// 创建一个学生对象
Address address = new Address("700005","湖北武当山","18991167346");
// Students s = new Students("S0000002","张三丰","男",new Date(),"太极拳",address);
//
// session.save(s);
tx.commit();
}
@Test
public void addStudentsByPk(){
// 创建会话
Session session = sessionFactory.getCurrentSession();
// 创建事务
Transaction tx = session.beginTransaction();
// 创建一个学生对象
Address address = new Address("700005","湖北武当山","18991167346");
// 创建学生主键对象
StudentsPK pk = new StudentsPK();
pk.setId("123456789012345678");
pk.setSid("1235241231");
Students s = new Students(pk,"张三丰","男",new Date(),"太极拳",address);
session.save(s);
tx.commit();
}
}
2-6 @Column注解
@Column
@Column:可将属性映射到列,使用该注解来覆盖默认值
@Column描述了数据库表中该字段的详细定义
这对于根据JPA注解生成数据库表结构的工具非常有作用
常用属性
name:可选,表示数据库表中该字段的名称,默认与属性名称一致
nullable:可选,表示该字段是否允许为null,默认为true
unique:可选,表示该字段是否是唯一标识,默认为false
length:可选,表示该字段的大小,仅对String类型的字段有效,默认为255
(如果是主键不能使用默认值)
insertable:可选,表示在ORM框架执行插入操作时,该字段是否应出现INSERT语句中,默认为true
updateable:可选,表示在ORM框架执行更新操作时,该字段是否应该出现在UPDATE语句中,默认为true
对于一经创建就不可以更改的字段,该属性非常有用,如对于birthday字段
2-7 @Embedded注解
@Embedded
@Embedded是注释属性的,表示该属性的类是嵌入类
注意:同时嵌入类也必须标注@Embeddable注解
2-8 @EmbeddedId注解
@EmbeddedId
@EmbeddedId使用嵌入式主键类实现复合主键
注意:嵌入式主键类
必须实现Serializable接口
必须有默认的public无参数的构造方法
必须覆盖equals和hashCode方法
代码演示
1.编写StudentsPK类
package com.myimooc.hibernateaa.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* 学生主键类
* @author ZhangCheng on 2017-07-12
*
*/
@Embeddable
public class StudentsPK implements Serializable{
private static final long serialVersionUID = 1L;
/** 省份证号码 */
@Column(length=18)
private String id;
/** 学号 */
@Column(length=10)
private String sid;
public StudentsPK() {
}
@Override
public String toString() {
return "StudentsPK [id=" + id + ", sid=" + sid + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((sid == null) ? 0 : sid.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StudentsPK other = (StudentsPK) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (sid == null) {
if (other.sid != null)
return false;
} else if (!sid.equals(other.sid))
return false;
return true;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
}
2.修改Students类
package com.myimooc.hibernateaa.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.GenericGenerator;
/**
* 学生实体类
* @author ZhangCheng on 2017-07-12
*
*/
@SuppressWarnings("unused")
@Entity
@Table(name="t_students",schema="hibernatemtm")
public class Students {
/** 学号 */
/* 方式一:使用自动生成主键
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer sid;
*/
/* 方式二:使用手工赋值方式生成主键
@Id
@GeneratedValue(generator="sid")
@GenericGenerator(name="sid",strategy="assigned")//
@Column(length=8)
private String sid;
*/
/* 方式三:使用复合主键 */
@EmbeddedId
private StudentsPK pk;
/** 姓名 */
private String sname;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
/** 薪水 */
@Transient // 表示该属性不会被ORM映射到表里的字段
private double salary;
/** 地址 */
@Embedded
private Address address;
@Override
public String toString() {
return "Students [pk=" + pk + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday + ", major="
+ major + ", salary=" + salary + ", address=" + address + "]";
}
public Students() {
super();
}
public Students(StudentsPK pk, String sname, String gender, Date birthday, String major,Address address) {
super();
this.pk = pk;
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
this.address = address;
}
public Students(StudentsPK pk, String sname, String gender, Date birthday, String major, double salary,
Address address) {
super();
this.pk = pk;
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
this.salary = salary;
this.address = address;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public StudentsPK getPk() {
return pk;
}
public void setPk(StudentsPK pk) {
this.pk = pk;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
3.修改StudentsTest类
package com.myimooc.hibernateaa.entity;
import java.util.Date;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 单元测试类
* @author ZhangCheng on 2017-07-12
*
*/
@SuppressWarnings("unused")
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
// SchemaExport export = new SchemaExport(config);
// export.create(true, true);
}
@Test
public void addStudents(){
// 创建会话
Session session = sessionFactory.getCurrentSession();
// 创建事务
Transaction tx = session.beginTransaction();
// 创建一个学生对象
Address address = new Address("700005","湖北武当山","18991167346");
// Students s = new Students("S0000002","张三丰","男",new Date(),"太极拳",address);
//
// session.save(s);
tx.commit();
}
@Test
public void addStudentsByPk(){
// 创建会话
Session session = sessionFactory.getCurrentSession();
// 创建事务
Transaction tx = session.beginTransaction();
// 创建一个学生对象
Address address = new Address("700005","湖北武当山","18991167346");
// 创建学生主键对象
StudentsPK pk = new StudentsPK();
pk.setId("123456789012345678");
pk.setSid("1235241231");
Students s = new Students(pk,"张三丰","男",new Date(),"太极拳",address);
session.save(s);
tx.commit();
}
}
2-9 @Transient注解
@Transient
可选,表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性,如果一个属性并非数据库表的字段映射,就务必将其表示为@Transient,否则ORM框架默认其注解为@Basic
第三章:关联映射注解
3-1 本章简介
简介
一对一单向外键关联
一对一双向外键关联
一对一单向外键联合主键
多对一单向外键关联
一对多单向外键关联
一对多双向外键关联
多对多单向外键关联
多对多双向外键关联
3-2 实体之间的关系
实体之间的映射关系
一对一:一个公民对应一个身份证号码
一对多(多对一):一个公民有多个银行账号
多对多:一个学生有多个老师,一个老师有多个学生
3-3 一对一单向外键关联(一)
一对一单向外键
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name=”pid”,unique=true)
注意:保存时应该先保存外键对象,再保存主表对象
拷贝hibernateca项目,重命名为hibernatera,POM与Hibernate配置文件均相同
代码演示
1.编写Students类
package com.myimooc.hibernatera.onetoonefk;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
/**
* 一对一单向外键关联
* 学生实体类
* @author ZhangCheng on 2017-07-12
*
*/
@Entity
public class Students {
/** 学号 */
@Id
@GeneratedValue
private Integer sid;
/** 身份证类 */
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="pid",unique=true)
private IdCard card;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday
+ ", major=" + major + "]";
}
public Students() {
}
public Students(IdCard card, String gender, Date birthday, String major) {
super();
this.card = card;
this.gender = gender;
this.birthday = birthday;
this.major = major;
}
public Students(IdCard card,Integer sid, String gender, Date birthday, String major) {
this.card = card;
this.sid = sid;
this.gender = gender;
this.birthday = birthday;
this.major = major;
}
public IdCard getCard() {
return card;
}
public void setCard(IdCard card) {
this.card = card;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
2.编写IdCard类
package com.myimooc.hibernatera.onetoonefk;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
/**
* 一对一单向外键关联
* 身份证实体类
* @author ZhangCheng on 2017-07-12
*
*/
@Entity
public class IdCard {
@Id
@GeneratedValue(generator = "pid")
@GenericGenerator(name="pid",strategy="assigned")
@Column(length=18)
/** 身份证号码 */
private String pid;
/** 学生的姓名 */
private String sname;
public IdCard() {
}
public IdCard(String pid, String sname) {
this.pid = pid;
this.sname = sname;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
}
3.修改Hibernate配置文件
<!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.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">
<![CDATA[
jdbc:mysql://localhost:3306/hibernatemtm?useUnicode=true&characterEncoding=utf8
]]>
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<!-- 一对一单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetoonefk.Students"/>
<mapping class="com.myimooc.hibernatera.onetoonefk.IdCard"/>
-->
<!-- 一对一双向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetoonebfk.Students"/>
<mapping class="com.myimooc.hibernatera.onetoonebfk.IdCard"/>
-->
<!-- 多对一单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.manytoonefk.Students"/>
<mapping class="com.myimooc.hibernatera.manytoonefk.ClassRoom"/>
-->
<!-- 一对多单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetomanyfk.Students"/>
<mapping class="com.myimooc.hibernatera.onetomanyfk.ClassRoom"/>
-->
<!-- 一对多双向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetomanybfk.Students"/>
<mapping class="com.myimooc.hibernatera.onetomanybfk.ClassRoom"/>
-->
<!-- 多对多单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.manytomanyfk.Students"/>
<mapping class="com.myimooc.hibernatera.manytomanyfk.Teachers"/>
-->
<!-- 多对多双向外键关联 -->
<mapping class="com.myimooc.hibernatera.manytomanybfk.Students"/>
<mapping class="com.myimooc.hibernatera.manytomanybfk.Teachers"/>
</session-factory>
</hibernate-configuration>
4.编写StudentsTest类
package com.myimooc.hibernatera.onetoonefk;
import java.util.Date;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 一对一双单外键关联
* 单元测试类
* @author ZhangCheng on 2017-07-12
*
*/
@SuppressWarnings("unused")
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
// SchemaExport export = new SchemaExport(config);
//
// export.create(true, true);
}
}
3-4 一对一单向外键关联(二)
代码演示
1.修改StudentsTest类
package com.myimooc.hibernatera.onetoonefk;
import java.util.Date;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 一对一双单外键关联
* 单元测试类
* @author ZhangCheng on 2017-07-12
*
*/
@SuppressWarnings("unused")
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
// SchemaExport export = new SchemaExport(config);
//
// export.create(true, true);
}
/**
* 一对一单向外键关联保存测试
*/
@Test
public void addStudents(){
Session session = sessionFactory.getCurrentSession();
// 生成一个身份证对象
IdCard card = new IdCard("123456789012345678","张无忌");
Transaction tx = session.beginTransaction();
// 生成学生对象
Students s = new Students(card, "男", new Date(), "太极拳");
// 先保存身份证类的对象
session.save(card);
session.save(s);
tx.commit();
}
}
3-5 一对一双向外键关联
一对一双向外键
主控方的配置同一对一单向外键关联相同
@OneToOne(mappedBy=”card”)//被控方
双向关联,必须设置mappedBy属性。因为双向关联只能交给一方去控制
不可能在双方都设置外键保存关联关系,否则双方都无法保存
代码演示
1.编写Students类
package com.myimooc.hibernatera.onetoonebfk;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
/**
* 一对一双向外键关联
* 学生实体类
* @author ZhangCheng on 2017-07-12
*
*/
@Entity
public class Students {
/** 学号 */
@Id
@GeneratedValue
private Integer sid;
/** 身份证类 */
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="pid",unique=true)
private IdCard card;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday
+ ", major=" + major + "]";
}
public Students() {
}
public Students(IdCard card, String gender, Date birthday, String major) {
super();
this.card = card;
this.gender = gender;
this.birthday = birthday;
this.major = major;
}
public Students(IdCard card,Integer sid, String gender, Date birthday, String major) {
this.card = card;
this.sid = sid;
this.gender = gender;
this.birthday = birthday;
this.major = major;
}
public IdCard getCard() {
return card;
}
public void setCard(IdCard card) {
this.card = card;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
2.编写IdCard类
package com.myimooc.hibernatera.onetoonebfk;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import org.hibernate.annotations.GenericGenerator;
/**
* 一对一双向外键关联
* 身份证实体类
* @author ZhangCheng on 2017-07-12
*
*/
@Entity
public class IdCard {
@Id
@GeneratedValue(generator = "pid")
@GenericGenerator(name="pid",strategy="assigned")
@Column(length=18)
/** 身份证号码 */
private String pid;
/** 学生的姓名 */
private String sname;
/** 学生的引用 */
@OneToOne(mappedBy="card")
private Students stu;
public Students getStu() {
return stu;
}
public void setStu(Students stu) {
this.stu = stu;
}
public IdCard() {
}
public IdCard(String pid, String sname) {
this.pid = pid;
this.sname = sname;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
}
3.修改hibernate配置文件
<!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.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">
<![CDATA[
jdbc:mysql://localhost:3306/hibernatemtm?useUnicode=true&characterEncoding=utf8
]]>
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<!-- 一对一单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetoonefk.Students"/>
<mapping class="com.myimooc.hibernatera.onetoonefk.IdCard"/>
-->
<!-- 一对一双向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetoonebfk.Students"/>
<mapping class="com.myimooc.hibernatera.onetoonebfk.IdCard"/>
-->
<!-- 多对一单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.manytoonefk.Students"/>
<mapping class="com.myimooc.hibernatera.manytoonefk.ClassRoom"/>
-->
<!-- 一对多单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetomanyfk.Students"/>
<mapping class="com.myimooc.hibernatera.onetomanyfk.ClassRoom"/>
-->
<!-- 一对多双向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetomanybfk.Students"/>
<mapping class="com.myimooc.hibernatera.onetomanybfk.ClassRoom"/>
-->
<!-- 多对多单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.manytomanyfk.Students"/>
<mapping class="com.myimooc.hibernatera.manytomanyfk.Teachers"/>
-->
<!-- 多对多双向外键关联 -->
<mapping class="com.myimooc.hibernatera.manytomanybfk.Students"/>
<mapping class="com.myimooc.hibernatera.manytomanybfk.Teachers"/>
</session-factory>
</hibernate-configuration>
4.编写StudentsTest类
package com.myimooc.hibernatera.onetoonebfk;
import java.util.Date;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 一对一双向外键关联
* 单元测试类
* @author ZhangCheng on 2017-07-12
*
*/
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
//@Test
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
SchemaExport export = new SchemaExport(config);
export.create(true, true);
}
/**
* 一对一双向外键关联保存测试
*/
@Test
public void addStudents(){
Session session = sessionFactory.getCurrentSession();
// 生成一个身份证对象
IdCard card = new IdCard("123456789012345678","张无忌");
Transaction tx = session.beginTransaction();
// 生成学生对象
Students s = new Students(card, "男", new Date(), "太极拳");
// 先保存身份证类的对象
session.save(card);
session.save(s);
tx.commit();
}
}
3-6 一对一单向外键联合主键
一对一双向外键联合主键
创建主键类
主键类必须实现serializable接口,重写hashCode()和equals()方法
主键类:@Embeddable
实体类:@EmbeddedId
3-7 多对一单向外键关联(一)
多对一单向外键
多方持有一方的引用,比如:多个学生对应一个班级(多对一)
在多方添加以下注解
@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
@JoinColumn(name=”cid”,referencedColumnName=”CID”)
代码演示
1.编写Students类
package com.myimooc.hibernatera.manytoonefk;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
/**
* 多对一单向外键关联
* 学生实体类(多方)
* @author ZhangCheng on 2017-07-13
*
*/
@Entity
public class Students {
/** 学号 */
@Id
@GeneratedValue
private Integer sid;
/** 学生姓名 */
private String sname;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
// 多方持有一方的引用
@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)// 配置级联关系和抓取策略
@JoinColumn(name="cid",referencedColumnName="CID") // 指定外键
private ClassRoom classRoom;
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday
+ ", major=" + major + "]";
}
public Students() {
}
public Students(String sname, String gender, Date birthday, String major) {
super();
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public ClassRoom getClassRoom() {
return classRoom;
}
public void setClassRoom(ClassRoom classRoom) {
this.classRoom = classRoom;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
2.编写ClassRoom类
package com.myimooc.hibernatera.manytoonefk;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
/**
* 多对一单向外键关联
* 班级实体类(一方)
* @author ZhangCheng on 2017-07-13
*
*/
@Entity
public class ClassRoom {
/** 班级编号 */
@Id
@GeneratedValue(generator="cid")
@GenericGenerator(name="cid",strategy="assigned")
@Column(length=4)
private String cid;
/** 班级名字 */
private String cname;
public ClassRoom() {
}
public ClassRoom(String cid, String cname) {
this.cid = cid;
this.cname = cname;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
@Override
public String toString() {
return "ClassRoom [cid=" + cid + ", cname=" + cname + "]";
}
}
3.修改hibernate配置文件
<!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.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">
<![CDATA[
jdbc:mysql://localhost:3306/hibernatemtm?useUnicode=true&characterEncoding=utf8
]]>
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<!-- 一对一单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetoonefk.Students"/>
<mapping class="com.myimooc.hibernatera.onetoonefk.IdCard"/>
-->
<!-- 一对一双向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetoonebfk.Students"/>
<mapping class="com.myimooc.hibernatera.onetoonebfk.IdCard"/>
-->
<!-- 多对一单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.manytoonefk.Students"/>
<mapping class="com.myimooc.hibernatera.manytoonefk.ClassRoom"/>
-->
<!-- 一对多单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetomanyfk.Students"/>
<mapping class="com.myimooc.hibernatera.onetomanyfk.ClassRoom"/>
-->
<!-- 一对多双向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.onetomanybfk.Students"/>
<mapping class="com.myimooc.hibernatera.onetomanybfk.ClassRoom"/>
-->
<!-- 多对多单向外键关联 -->
<!--
<mapping class="com.myimooc.hibernatera.manytomanyfk.Students"/>
<mapping class="com.myimooc.hibernatera.manytomanyfk.Teachers"/>
-->
<!-- 多对多双向外键关联 -->
<mapping class="com.myimooc.hibernatera.manytomanybfk.Students"/>
<mapping class="com.myimooc.hibernatera.manytomanybfk.Teachers"/>
</session-factory>
</hibernate-configuration>
4.编写StudentsTest类
package com.myimooc.hibernatera.manytoonefk;
import java.util.Date;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 多对一单向外键关联
* 单元测试类
* @author ZhangCheng on 2017-07-13
*
*/
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
//@Test
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
SchemaExport export = new SchemaExport(config);
export.create(true, true);
}
}
3-8 多对一单向外键关联(二)
代码演示
1.修改StudentsTest类
package com.myimooc.hibernatera.manytoonefk;
import java.util.Date;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 多对一单向外键关联
* 单元测试类
* @author ZhangCheng on 2017-07-13
*
*/
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
//@Test
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
SchemaExport export = new SchemaExport(config);
export.create(true, true);
}
@Test
public void addStudents(){
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
// 创建班级对象
ClassRoom c1 = new ClassRoom("C001","软件工程");
ClassRoom c2 = new ClassRoom("C002","网络工程");
// 创建学生对象
Students s1 = new Students("张三","男", new Date(), "计算机");
Students s2 = new Students("李四","男", new Date(), "计算机");
Students s3 = new Students("王五","女", new Date(), "计算机");
Students s4 = new Students("赵六","女", new Date(), "计算机");
s1.setClassRoom(c1);
s2.setClassRoom(c1);
s3.setClassRoom(c2);
s4.setClassRoom(c2);
// 先保存班级
session.save(c1);
session.save(c2);
session.save(s1);
session.save(s2);
session.save(s3);
session.save(s4);
tx.commit();
}
}
3-9 一对多单向外键关联
一对多单向外键
一方持有多方的集合,一个班级有多个学生(一对多)
在一方添加以下注解
@OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
@JoinColumn(name=”cid”)
抓取策略总结
多对一时候
多方设置EAGER:表示积极加载
一方设置LAZY:表示懒加载
代码演示
1.编写Students类
package com.myimooc.hibernatera.onetomanyfk;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* 一对多单向外键关联
* 学生实体类(多方)
* @author ZhangCheng on 2017-07-13
*
*/
@Entity
public class Students {
/** 学号 */
@Id
@GeneratedValue
private Integer sid;
/** 学生姓名 */
private String sname;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday
+ ", major=" + major + "]";
}
public Students() {
}
public Students(String sname, String gender, Date birthday, String major) {
super();
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
2.编写ClassRoom类
package com.myimooc.hibernatera.onetomanyfk;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import org.hibernate.annotations.GenericGenerator;
/**
* 一对多单向外键关联
* 班级实体类(一方)
* @author ZhangCheng on 2017-07-13
*
*/
@Entity
public class ClassRoom {
/** 班级编号 */
@Id
@GeneratedValue(generator="cid")
@GenericGenerator(name="cid",strategy="assigned")
@Column(length=4)
private String cid;
/** 班级名字 */
private String cname;
// 一方持有多方的集合
@OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
@JoinColumn(name="cid")
private Set<Students> stus;
public ClassRoom() {
}
public ClassRoom(String cid, String cname) {
this.cid = cid;
this.cname = cname;
}
public Set<Students> getStus() {
return stus;
}
public void setStus(Set<Students> stus) {
this.stus = stus;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
@Override
public String toString() {
return "ClassRoom [cid=" + cid + ", cname=" + cname + "]";
}
}
3.修改hibernate配置文件
同上
4.编写StudentsTest类
package com.myimooc.hibernatera.onetomanyfk;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 一对多单向外键关联
* 单元测试类
* @author ZhangCheng on 2017-07-13
*
*/
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
//@Test
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
SchemaExport export = new SchemaExport(config);
export.create(true, true);
}
@Test
public void addStudents(){
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
// 创建班级对象
ClassRoom c1 = new ClassRoom("C001","软件工程");
ClassRoom c2 = new ClassRoom("C002","网络工程");
// 创建学生对象
Students s1 = new Students("张三","男", new Date(), "计算机");
Students s2 = new Students("李四","男", new Date(), "计算机");
Students s3 = new Students("王五","女", new Date(), "计算机");
Students s4 = new Students("赵六","女", new Date(), "计算机");
// 创建两个集合
Set<Students> set1 = new HashSet<Students>();
set1.add(s1);
set1.add(s2);
Set<Students> set2 = new HashSet<Students>();
set2.add(s3);
set2.add(s4);
c1.setStus(set1);
c2.setStus(set2);
// 先保存学生
session.save(s1);
session.save(s2);
session.save(s3);
session.save(s4);
session.save(c1);
session.save(c2);
tx.commit();
}
}
3-10 一对多双向外键关联
一对多(多对一)双向外键
多方:多方持有一方的引用
在多方添加以下注解
@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
@JoinColumn(name=”cid”)
一方:一方持有多方的集合
在一方添加以下注解
@OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
@JoinColumn(name=”cid”)
代码演示
1.编写Students类
package com.myimooc.hibernatera.onetomanybfk;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
/**
* 一对多双向外键关联
* 学生实体类(多方)
* @author ZhangCheng on 2017-07-13
*
*/
@Entity
public class Students {
/** 学号 */
@Id
@GeneratedValue
private Integer sid;
/** 学生姓名 */
private String sname;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
// 多方持有一方的引用
@ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)// 配置级联关系和抓取策略
@JoinColumn(name="cid") // 指定外键
private ClassRoom classRoom;
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday
+ ", major=" + major + "]";
}
public Students() {
}
public Students(String sname, String gender, Date birthday, String major) {
super();
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
2.编写ClassRoom类
package com.myimooc.hibernatera.onetomanybfk;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import org.hibernate.annotations.GenericGenerator;
/**
* 一对多双向外键关联
* 班级实体类(一方)
* @author ZhangCheng on 2017-07-13
*
*/
@Entity
public class ClassRoom {
/** 班级编号 */
@Id
@GeneratedValue(generator="cid")
@GenericGenerator(name="cid",strategy="assigned")
@Column(length=4)
private String cid;
/** 班级名字 */
private String cname;
// 一方持有多方的集合
@OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY)
@JoinColumn(name="cid")
private Set<Students> stus;
public ClassRoom() {
}
public ClassRoom(String cid, String cname) {
this.cid = cid;
this.cname = cname;
}
public Set<Students> getStus() {
return stus;
}
public void setStus(Set<Students> stus) {
this.stus = stus;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
@Override
public String toString() {
return "ClassRoom [cid=" + cid + ", cname=" + cname + "]";
}
}
3.修改hibernate配置文件
同上
4.编写StudentsTest类
package com.myimooc.hibernatera.onetomanybfk;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 一对多双向外键关联
* 单元测试类
* @author ZhangCheng on 2017-07-13
*
*/
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
//@Test
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
SchemaExport export = new SchemaExport(config);
export.create(true, true);
}
@Test
public void addStudents(){
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
// 创建班级对象
ClassRoom c1 = new ClassRoom("C001","软件工程");
ClassRoom c2 = new ClassRoom("C002","网络工程");
// 创建学生对象
Students s1 = new Students("张三","男", new Date(), "计算机");
Students s2 = new Students("李四","男", new Date(), "计算机");
Students s3 = new Students("王五","女", new Date(), "计算机");
Students s4 = new Students("赵六","女", new Date(), "计算机");
// 创建两个集合
Set<Students> set1 = new HashSet<Students>();
set1.add(s1);
set1.add(s2);
Set<Students> set2 = new HashSet<Students>();
set2.add(s3);
set2.add(s4);
c1.setStus(set1);
c2.setStus(set2);
// 先保存学生
session.save(s1);
session.save(s2);
session.save(s3);
session.save(s4);
session.save(c1);
session.save(c2);
tx.commit();
}
}
3-11 多对多单向外键关联(一)
多对多单向外键
学生和教师构成多对多的关联关系
其中一个多方持有另一个多方的集合对象(学生持有教师的集合)
创建中间表
// 学生类中添加以下注解
@ManyToMany
@JoinTable(
name=”teachers_students”,
joinColumns = {@JoinColumn(name=”sid”)},
inverseJoinColumns={@JoinColumn(name=”tid”)})
代码演示
1.编写Students类
package com.myimooc.hibernatera.manytomanyfk;
import java.util.Date;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
/**
* 多对多单向外键关联
* 学生实体类(多方)
* @author ZhangCheng on 2017-07-13
*
*/
@Entity
public class Students {
/** 学号 */
@Id
@GeneratedValue
private Integer sid;
/** 学生姓名 */
private String sname;
/** 性别 */
private String gender;
/** 出生日期 */
private Date birthday;
/** 专业 */
private String major;
// 学生持有教师的集合
@ManyToMany
@JoinTable(
name="teachers_students",
joinColumns={@JoinColumn(name="sid")},
inverseJoinColumns={@JoinColumn(name="tid")}
)
private Set<Teachers> teachers;
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday
+ ", major=" + major + "]";
}
public Students() {
}
public Students(String sname, String gender, Date birthday, String major) {
super();
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.major = major;
}
public Set<Teachers> getTeachers() {
return teachers;
}
public void setTeachers(Set<Teachers> teachers) {
this.teachers = teachers;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
2.编写Teachers类
package com.myimooc.hibernatera.manytomanyfk;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
/**
* 多对多单向外键关联
* 教师实体类(多方)
* @author ZhangCheng on 2017-07-13
*
*/
@Entity
public class Teachers {
/** 教师编号 */
@Id
@GeneratedValue(generator="tid")
@GenericGenerator(name="tid",strategy="assigned")
@Column(length=4)
private String tid;
/** 教师姓名 */
private String tname;
public Teachers(String tid, String tname) {
this.tid = tid;
this.tname = tname;
}
public Teachers() {
}
@Override
public String toString() {
return "Teachers [tid=" + tid + ", tname=" + tname + "]";
}
public String getTid() {
return tid;
}
public void setTid(String tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
}
3.修改hibernate配置文件
同上
4.编写StudentsTest类
package com.myimooc.hibernatera.manytomanyfk;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 多对多单向外键关联
* 单元测试类
* @author ZhangCheng on 2017-07-13
*
*/
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
//@Test
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
SchemaExport export = new SchemaExport(config);
export.create(true, true);
}
}
3-12 多对多单向外键关联(二)
代码演示
1.修改StudentsTest类
package com.myimooc.hibernatera.manytomanyfk;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
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.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.junit.Test;
/**
* 多对多单向外键关联
* 单元测试类
* @author ZhangCheng on 2017-07-13
*
*/
public class StudentsTest {
private SessionFactory sessionFactory = null;
@Before
//@Test
public void schemaExportTest(){
// 创建hibernate配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder()
.applySettings(config.getProperties()).buildServiceRegistry();
// 生成sessionFactory
sessionFactory = config.buildSessionFactory(ServiceRegistry);
SchemaExport export = new SchemaExport(config);
export.create(true, true);
}
@Test
public void addStudents(){
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
// 创建教师对象
Teachers t1 = new Teachers("T001","张老师");
Teachers t2 = new Teachers("T002","李老师");
Teachers t3 = new Teachers("T003","陈老师");
Teachers t4 = new Teachers("T004","刘老师");
// 创建学生对象
Students s1 = new Students("张三","男",new Date(),"计算机");
Students s2 = new Students("李四","男",new Date(),"计算机");
Students s3 = new Students("王五","女",new Date(),"计算机");
Students s4 = new Students("赵六","女",new Date(),"计算机");
// 创建教师集合
Set<Teachers> set1 = new HashSet<Teachers>();
set1.add(t1);
set1.add(t2);
Set<Teachers> set2 = new HashSet<Teachers>();
set2.add(t3);
set2.add(t4);
Set<Teachers> set3 = new HashSet<Teachers>();
set3.add(t1);
set3.add(t3);
set3.add(t4);
Set<Teachers> set4 = new HashSet<Teachers>();
set4.add(t2);
set4.add(t3);
set4.add(t4);
// 设置学生教师
s1.setTeachers(set1);
s2.setTeachers(set2);
s3.setTeachers(set3);
s4.setTeachers(set4);
// 保存教师信息
session.save(t1);
session.save(t2);
session.save(t3);
session.save(t4);
// 保存学生信息
session.save(s1);
session.save(s2);
session.save(s3);
session.save(s4);
tx.commit();
}
}
3-13 多对多双向外键关联
多对多双向外键
双方持有对方的集合对象,其中一方设置
// 教师类
@ManyToMany(mappedBy=”teachers”)
// 学生类中添加以下注解
@ManyToMany
@JoinTable(
name=”teachers_students”,
joinColumns = {@JoinColumn(name=”sid”)},
inverseJoinColumns={@JoinColumn(name=”tid”)})
代码演示
1.编写Students类
// 学生持有教师的集合
@ManyToMany
@JoinTable(
name="teachers_students",
joinColumns={@JoinColumn(name="sid")},
inverseJoinColumns={@JoinColumn(name="tid")}
)
private Set<Teachers> teachers;
2.编写Teachers类
// 教师持有学生的集合
@ManyToMany(mappedBy="teachers")
private Set<Students> students;
3.修改hibernate配置文件
同上
4.编写StudentsTest类
同多对多单向外键关联测试类
第四章:课程总结
4-1 课程总结
类级别注解
@Entity
@Table
@Embeddable
属性级别注解
@Id
@GeneratedValue
@Column
@Embedded
@EmbeddedId
@Transient
映射关系注解
@OneToOne:一对一单向外键
@OneToOne(mappedBy=”xxx”):一对一双向外键关联
@Embeddable和@EmbeddedId:一对一单向外键联合主键
@ManyToOne和@JoinColumn:多对一单向外键关联
@OneToMany和@JoinColumn:一对多单向外键关联
@ManyToOne和@OneToMany 和@JoinColumn:一对多双向外键关联
@ManyToMany和@JoinColumn:多对多单向外键关联
@ManyToMany(mappedBy=”xxx”)和@JoinTable:多对多双向外键关联
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。