Hibernate 基础配置及常用功能(二)

本章主要是描述几种经典映射关系,顺带比较Hibernate4.x和Hibernate5.x之间的区别。

一、建立测试工程目录

有关实体类之间的相互映射关系,Hibernate官方文档其实描述的非常详细,这里只提供几种常见映射。(推荐4.3.11版本的 hibernate-release-4.3.11.Final\documentation\manual)

二、编写映射关系

(1)one2one单表内嵌映射:

package model.family;import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;@Entity
public class Husband {private int id;private String husbandName;private Wife wife;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getHusbandName() {return husbandName;}public void setHusbandName(String husbandName) {this.husbandName = husbandName;}// 两个实体对象共用一张数据表,提高查询速度
    @Embeddedpublic Wife getWife() {return wife;}public void setWife(Wife wife) {this.wife = wife;}}
Husband.java
package model.family;//不用添加任何注解,持久化过程通过主表完成
public class Wife {private String wifeName;public String getWifeName() {return wifeName;}public void setWifeName(String wifeName) {this.wifeName = wifeName;}
}
Wife.java

(2)one2one外键映射:

package model.userinfo;import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Transient;@Entity
public class User {private int id;private String username;private String password;private String confirm;private Information info;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}/** 延迟加载,级联操作。 * 删除开启了级联的一方,被级联的一方也会被删除* 注意:如果session的操作是通过hibernate控制,延迟加载不会出问题。如果是通过手工开启实物,操作不当延迟加载可能抛出懒加载异常*/@OneToOne(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)public Information getInfo() {return info;}public void setInfo(Information info) {this.info = info;}// 本字段不参与持久化过程
    @Transientpublic String getConfirm() {return confirm;}public void setConfirm(String confirm) {this.confirm = confirm;}
}
User.java
package model.userinfo;import java.util.Date;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;//注解也可以直接配置在字段上,但是不推荐。据说原因是可能破坏oop封装。但是我觉得有时这样配置可以让代码显得更加整洁,特别是在Spring中。
@Entity
public class Information {@Id@GeneratedValueprivate int id;@OneToOneprivate User user;@Temporal(TemporalType.DATE)private Date resgisterDate;private String address;public int getId() {return id;}public void setId(int id) {this.id = id;}public User getUser() {return user;}public void setUser(User user) {this.user = user;}public Date getResgisterDate() {return resgisterDate;}public void setResgisterDate(Date resgisterDate) {this.resgisterDate = resgisterDate;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}}
Information.java

(3)many2many多表映射:

场景描述:学校里有多个老师,每个老师教授多个学生,每个学生每一门课程会有一个得分。

 package model.school;import java.util.HashSet;
import java.util.Set;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;@Entity
public class Teacher {private int id;private String tchName;private Set<Student> students = new HashSet<Student>();@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getTchName() {return tchName;}public void setTchName(String tchName) {this.tchName = tchName;}//老师和学生的对应表由学生一方负责维护@ManyToMany(mappedBy = "teachers")public Set<Student> getStudents() {return students;}public void setStudents(Set<Student> students) {this.students = students;}}
Teacher.java
package model.school;import java.util.HashSet;
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;
import javax.persistence.OneToMany;@Entity
public class Student {private int id;private String stuName;private Set<Teacher> teachers = new HashSet<Teacher>();private Set<Score> scores = new HashSet<Score>();@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getStuName() {return stuName;}public void setStuName(String stuName) {this.stuName = stuName;}/** many2many必须使用中间表,配置中间表的表明和列名*/@ManyToMany@JoinTable(name = "student_teacher", joinColumns = { @JoinColumn(name = "studentId") }, inverseJoinColumns = {@JoinColumn(name = "teacherId") })public Set<Teacher> getTeachers() {return teachers;}public void setTeachers(Set<Teacher> teachers) {this.teachers = teachers;}// 学生同分数之间的关系同样交给多的一方负责维护@OneToMany(mappedBy = "student")public Set<Score> getScores() {return scores;}public void setScores(Set<Score> scores) {this.scores = scores;}}
Student.java
package model.school;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;@Entity
public class Score {private int id;private int courseScore;private Teacher teacher;private Student student;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public int getCourseScore() {return courseScore;}public void setCourseScore(int courseScore) {this.courseScore = courseScore;}@ManyToOnepublic Teacher getTeacher() {return teacher;}public void setTeacher(Teacher teacher) {this.teacher = teacher;}@ManyToOnepublic Student getStudent() {return student;}public void setStudent(Student student) {this.student = student;}}
Score.java

按照以上的映射关系生成数据表以后会注意到,其实老师和学生之间的关系表纯粹多余,分数表已经维护了双方的关系。重新优化他们之间的映射关系:

package model.school;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;@Entity
public class Teacher {private int id;private String tchName;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getTchName() {return tchName;}public void setTchName(String tchName) {this.tchName = tchName;}}
Teacher.java
package model.school;import java.util.HashSet;
import java.util.Set;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;@Entity
public class Student {private int id;private String stuName;private Set<Score> scores = new HashSet<Score>();@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getStuName() {return stuName;}public void setStuName(String stuName) {this.stuName = stuName;}@OneToMany(mappedBy = "student")public Set<Score> getScores() {return scores;}public void setScores(Set<Score> scores) {this.scores = scores;}}
Student.java
package model.school;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;@Entity
public class Score {private int id;private int courseScore;private Teacher teacher;private Student student;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public int getCourseScore() {return courseScore;}public void setCourseScore(int courseScore) {this.courseScore = courseScore;}@ManyToOnepublic Teacher getTeacher() {return teacher;}public void setTeacher(Teacher teacher) {this.teacher = teacher;}@ManyToOnepublic Student getStudent() {return student;}public void setStudent(Student student) {this.student = student;}}
Score.java

由此可见,即使是一个相对复杂的映射关系也可以通过优化得到一个相对简单的数据模型。

(4)many2one和one2many单表树形映射:

场景描述:地图,一个国家包含多个省份,每个省份又包含多个城市...

package model.tree;import java.util.HashSet;
import java.util.Set;import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;@Entity
@Table(name = "_tree")
public class Tree {private int id;private String name;private Tree parent;private Set<Tree> children = new HashSet<Tree>();@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}@Column(name = "t_name", unique = true)public String getName() {return name;}public void setName(String name) {this.name = name;}@ManyToOnepublic Tree getParent() {return parent;}public void setParent(Tree parent) {this.parent = parent;}//删除根节点,与它相关的所有子节点全部删除@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)public Set<Tree> getChildren() {return children;}public void setChildren(Set<Tree> children) {this.children = children;}
}
Tree.java

注意:以上4种映射关系在4.3.11版本中正常。但在5.0.6版本中id字段被系统强制指定为了@GeneratedValue(strategy=GenerationType.TABLE)的方式。我曾经尝试手工指定生成策略为auto或者identity均无效。如果是通过xml的方式配置是正常的,目前我还不清楚是什么原因导致的上述异常。这个问题造成了下面的映射关系目前只能在4.x版本中正常使用:

(5)one2one主键映射

package model.personaddr;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;@Entity
public class Person {private int id;private String name;private Address address;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}// 两张表通过主键关联@OneToOne(optional = true)@PrimaryKeyJoinColumnpublic Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}
}
Person.java
package model.personaddr;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;@Entity
public class Address {private int id;private String local;private Person person;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getLocal() {return local;}public void setLocal(String local) {this.local = local;}@OneToOne(mappedBy = "address")public Person getPerson() {return person;}public void setPerson(Person person) {this.person = person;}}
Address.java

ps:好在主键映射在实际使用中并不常见。


 

最后按照惯例,提供整个项目的完整目录结构和IDE版本信息

转载于:https://www.cnblogs.com/learnhow/p/5120948.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/375196.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

YTU 2903: A--A Repeating Characters

2903: A--A Repeating Characters 时间限制: 1 Sec 内存限制: 128 MB提交: 50 解决: 30题目描述 For this problem,you will write a program that takes a string of characters,S,and creates a new string of characters,T,with each character repeated R times.That is,…

ADO连接ACCESS数据库

首先在StdAfx.h中加入 建立连接&#xff1a;(在xxApp文件中) 1 声明变量 2 建立连接 (1) AfxOleInit 初始化 OLE 为应用程序的支持。 BOOL AFXAPI AfxOleInit( ); 返回值 非零&#xff0c;如果成功;0&#xff0c;如果初始化失败&#xff0c;可能&#xff0c;因为安装该 OLE 系…

使用搜索栏过滤collectionView(按照首字母)

1.解析json数据NSDictionary *citiesDic [CoreJSONSerialization coreJSONSerialization:"cities"];NSDictionary *infor [citiesDic objectForKey:"infor"];NSArray *listItems [infor objectForKey:"listItems"]; 2.存储数据 for (NSDicti…

R软件中 文本分析安装包 Rjava 和 Rwordseg 傻瓜式安装方法四部曲

这两天&#xff0c;由于要做一个文本分析的内容&#xff0c;所以搜索了一天R语言中的可以做文本分析的加载包&#xff0c;但是在安装包的过程&#xff0c;真是被虐千百遍&#xff0c;总是安装不成功。特此专门写一篇博文&#xff0c;把整个心塞史畅快的释放一下。 ------------…

Windows下安装Python数据库模块--MySQLdb

## 1、下载MySQLdb [去官网](http://pypi.python.org/pypi/MySQL-python/) 下载对应的编译好的版本&#xff08;现在官网最新版本为1.2.5&#xff09;&#xff1a; MySQL-python-1.2.5.win32-py2.7.exe 得到1MB的安装文件 MySQL-python-1.2.5.win32-py2.7.exe ## 2、安装 以…

Java 理解CPU缓存(CPU Cache)

从Java视角理解系统结构连载, 关注我的微博(链接)了解最新动态 众所周知, CPU是计算机的大脑, 它负责执行程序的指令; 内存负责存数据, 包括程序自身数据. 同样大家都知道, 内存比CPU慢很多. 其实在30年前, CPU的频率和内存总线的频率在同一个级别, 访问内存只比访问CPU寄存器慢…

Homebrew OS X 不可或缺的套件管理器

Homebrew OS X 不可或缺的套件管理器,可以说Homebrew就是mac下的apt-get、yum. 1.安装homebrew brew的安装很简单&#xff0c;使用一条ruby命令即可&#xff0c;Mac系统上已经默认安装了ruby。 ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install…

【BZOJ】【1003】【ZJOI2006】物流运输trans

最短路/DP 这题数据规模并不大&#xff01;&#xff01;这是重点……… 所以直接暴力DP就好了&#xff1a;f[i]表示前 i 天的最小花费&#xff0c;则有$f[i]min\{f[j]cost[j1][i]k\} (0\leq j \leq i-1)$其中cost数组表示第L天到第R天只用一种运输方案连续运$R-L1$天的最小代价…

[傅里叶变换及其应用学习笔记] 二十四. 级联,脉冲响应

我们上节课学习了 在离散有限维空间中&#xff0c;任何线性系统都是通过矩阵间的相乘得到的在连续无限维空间中&#xff0c;任何线性系统都是通过对核函数的积分得到的脉冲响应&#xff08;impulse response&#xff09; 级联线性系统&#xff08;Cascading linear system&…

团队开发——用户需求调研报告

用户需求调研报告 项目名称&#xff1a; 躲避小球 项目编号&#xff1a;001 调研主题&#xff1a; 用户需求 访谈时间&#xff1a;2015.4.10 调研地点&#xff1a; 石家庄铁道大学图书馆 访谈部门&#xff1a; 三个人行 参与人员&#xff1a; 林彦汝 1. 访谈目的 1、让用…

设计模式(十五):解释器模式

一、定义 在设定环境中&#xff0c;定义一种规则或者语法&#xff0c;通过解释器来解释规则或者语法的含义. 二、实例&#xff1a;将 二十一 —> 21 2.1 设定我们的环境 Context public class Context{public string Input { get; set; }public int Output { get; se…

MySQL 5.7.10 免安装配置

# 配置环境&#xff1a;windows 64bit # 安装版本&#xff1a;mysql-5.7.10-win32&#xff08;zip archive版本&#xff09; 1. ZIP Archive版是免安装的&#xff0c;只需把mysql-5.7.10-win32.zip解压到安装目录即可。 2. 在D:\Program Files\mysql-5.7.10-win32文件夹下新建配…

fortran语法笔记

1&#xff0c;数据类型&#xff0c;fortran支持整形&#xff0c;real型&#xff0c;logical型&#xff0c;char型&#xff0c;复数型。整形分为为长整形和短整形定义长整形的方法 同时声明多个变量的话可以用逗号隔开。 加两个冒号的话可以直接在声明的时候赋值。 fortran是唯一…

BSA基础数据维护

平台 BSA基础数据维护 。扇区五个字段的内容 本来值为0&#xff0c;经过107上计算解析&#xff0c;得出正常的数值。然后106上报&#xff08;200050&#xff09;&#xff0c;得到回复&#xff08;200051&#xff09;。 查看回复数据&#xff0c;是否有错误。比如提示104 基站拼…

API函数MessageBox的参数与返回值

Win32汇编函数的参数,参数类型,返回值都是一个dword类型(4字节) 返回值永远放在EAX中,如超过4个字节则返回一个数据的指针(指向返回值存放的缓冲区地址).data titleS db helloworld,0 messageS db hello,welcome to win32,0.code start:invoke MessageBox,NULL,offset message…

The initialize list of C++ Class

性能问题之外&#xff0c;有些时场合初始化列表是不可或缺的&#xff0c;以下几种情况时必须使用初始化列表 常量成员&#xff0c;因为常量只能初始化不能赋值&#xff0c;所以必须放在初始化列表里面 Error1(constchar* constmsg) :data(msg) { //data msg; } 引用类型&…

PYTHON--定期监测服务器端口,并将结果写入MYSQL

定时监测服务器端口&#xff0c;然后将结果入写数据库。 监测用NC命令&#xff0c;入库就用PYTHON的MYSQL模块 再调一个基于函数的多线程。。。 妥妥的。。 是网上两个功能的合成。。 俺不生产代码&#xff0c;俺只是BAIDU的搬运工&#xff01; #!/usr/bin/env python import m…

MS_DOS头部 IMAGE_DOS_HEADER

MS_DOS头部 IMAGE_DOS_HEADER STRUCT{00H WORD e_magic ;DOS可执行文件标记字符串MZ(4D 5A)3CH DWORD e_1fanew ;指向PE文件头} IMAGE_DOS_HEADER ENDS用十六进制编辑器打开一个EXE文件 如QQ.EXEe_magic5A 4D e_1fanew00000100H---->此地址指向PE头文件

计算机原理学习(6)-- x86-32 CPU和内存管理之分页管理

前言 上一篇我们了解了x86-16 CPU计算机的内存访问方式&#xff0c;寻址方式&#xff0c;以及基于MS-DOS的应用程序的内存布局。这一篇会主要介绍32位处理器的内存访问&#xff0c;内存管理以及应用程序的内存布局。虽然目前64位CPU已经非常普及了&#xff0c;不过相对于32位的…

socket通信简介

前言 我们深谙信息交流的价值&#xff0c;那网络中进程之间如何通信&#xff0c;如我们每天打开浏览器浏览网页时&#xff0c;浏览器的进程怎么与web服务器通信的&#xff1f;当你用QQ聊天时&#xff0c;QQ进程怎么与服务器或你好友所在的QQ进程通信&#xff1f;这些都得靠sock…