摘要:时间年月日星期二说明本文部分内容均来自慕课网。文件如下在目录下,创建文件指定映射文件的路径注解映射实体类可选,对应数据库中的一个表。
时间:2017年07月11日星期二
说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com
教学源码:无
学习源码:https://github.com/zccodere/s...
本章简介
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文件如下
4.0.0 com.myimooc hibernateca 0.0.1-SNAPSHOT jar hibernateca http://maven.apache.org UTF-8 UTF-8 org.hibernate hibernate-core 4.2.4.Final mysql mysql-connector-java 5.1.38 junit junit 4.10 test org.apache.maven.plugins maven-compiler-plugin 1.8
在src/main/ resources目录下,创建hibernate.cfg.xml文件
1-3 @Entity注解org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver root root true update
@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.配置映射
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 @Transient2-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配置文件
org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver root root true update thread
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配置文件
org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver root root true update thread
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 实体类:@EmbeddedId3-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配置文件
org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver root root true update thread
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 Setstus; public ClassRoom() { } public ClassRoom(String cid, String cname) { this.cid = cid; this.cname = cname; } public Set getStus() { return stus; } public void setStus(Set 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(); /
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/67370.html
摘要:小时学会学习总结时间年月日星期六说明本文部分内容均来自慕课网。慕课网教学示例源码暂无。数据库操作下第六章事务管理事务管理只有查询的时候不加事务,其它任何操作都要加事务。第七章课程回顾课程回顾总结介绍安装配置的使用数据库操作 《2小时学会SpringBoot》学习总结 时间:2017年2月18日星期六说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学示...
摘要:入门篇学习总结时间年月日星期三说明本文部分内容均来自慕课网。主要的功能是日志记录,性能统计,安全控制,事务处理,异常处理等等。 《Spring入门篇》学习总结 时间:2017年1月18日星期三说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学示例源码:https://github.com/zccodere/s...个人学习源码:https://git...
摘要:时间年月日星期二说明本文部分内容均来自慕课网。项目一个项目代表一个正在构建的组件比如一个文件,当构建启动后,会基于实例化一个类,并且能够通过变量使其隐式可用。任务动作定义了一个最小的工作单元。 时间:2017年05月16日星期二说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学示例源码:无个人学习源码:https://github.com/zccod...
摘要:时间年月日星期二说明本文部分内容均来自慕课网。返回对象不同返回持久化实体类对象返回代理对象。与缓存的关系不同只缓存,但不使用缓存查询缓存除外会使用缓存。 时间:2017年07月11日星期二说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学源码:无学习源码:无 第一章:概述 1-1 概述 课程内容 了解缓存 掌握Hibernate一级缓存的使用 掌握H...
时间:2017年07月11日星期二说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com教学源码:无学习源码:https://github.com/zccodere/s... 第一章:应用场景 1-1 多对多的应用场景 案例分析:企业项目开发过程中 一个项目可由多个员工参与开发 一个员工可同时参与开发多个项目 示意图 showImg(https://segmentfau...
阅读 1102·2023-04-26 00:12
阅读 3186·2021-11-17 09:33
阅读 1018·2021-09-04 16:45
阅读 1146·2021-09-02 15:40
阅读 2055·2019-08-30 15:56
阅读 2878·2019-08-30 15:53
阅读 3477·2019-08-30 11:23
阅读 1892·2019-08-29 13:54