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,一经查实,立即删除!

相关文章

三言两语

人生中总是在选择。每当做一件事我们都应该问问我们的内心&#xff0c;或多或少我们都能理解一点人生的真谛。 最近时间很充裕&#xff0c;也就想了好多事情。首先我想明白的第一件事就是做任何事就要勇敢的去面对、去追求。喜欢一个女孩子大概有8年了吧&#xff01;这期间我们…

8086逻辑移位指令SHL和SHR

SHL逻辑左移指令 SHL OPRD M;把操作数OPRD左移M位,M为位移次数,为1或为CL(位移超过1次用CL表示) ;每移动一位右边用0补足一位,移出的最高位进入CF(最后移出的一位写入CF) MOV AL,00010011B ;13H 00010011B SHL AL,1 ;把AL左移1位,移出的最高位0进入CF,右边0补足1位…

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,…

JavaScript 模拟装饰者模式

/*** 抽象coffee父类&#xff0c;其实可以不用的*/ function Coffee () {} Coffee.prototype.cost function() {throw 实现这个方法; }; /*** 黑咖啡&#xff0c;其实可以不用继承的&#xff1b;*/ function BlackCoffee () {} // BlackCoffee.prototype new Coffee(); // Bl…

8086算术移位指令SAL和SAR

SAL算术左移指令同逻辑左移指令进行相同动作,机器指令一样,只是为了方便记忆而提供的两个助记符 SAR算术右移指令 SAR OPRD,M ;该指令使操作数右移M位,每移动1位左边的符号保持不变,移出的最低位进入CF mov al,26H ;00100110B 右移1位 00010011B sar al,1 ;26H/2H13H mov a…

const 和readonly

原文:http://www.cnblogs.com/royenhome/archive/2010/05/22/1741592.html 关于 const和readonly修饰符之间的区别,要牵涉到C#中两种不同的常量类型: 静态常量(compile-time constants) 和动态常量(runtime constants) 静态常量是指编译器在编译时候会对常量进行解析,并将常量的…

Objective - C 小谈:UIPickerView 和 UIDatePicker的基本使用

1.UIPickerView 1.1. UIPickerView的常见属性 // 数据源(用来告诉UIPickerView有多少列多少行) property(nonatomic,assign) id<UIPickerViewDataSource> dataSource;// 代理(用来告诉UIPickerView每1列的每1行显示什么内容,监听UIPickerView的选择) property(nonatomic,…

8086移位指令

8086有如下3条一般移位指令 SAR OPRD,M ;算术右移 对无符号数和有符号数而言右移1位相当于原数除以2 SHR OPRD,M ;逻辑右移 对无符号数右移1位相当于原数除以2 SHL OPRD,M/SAL OPRD,M ;逻辑/算术左移(两个助记符只有一个机器指令,进行相同的动作)左移1位相当于原数*2

ADO连接ACCESS数据库

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

MySQLdb autocommit的坑

今天写的一个小功能&#xff0c;里面要用MySQLdb更新数据库&#xff0c;语句如下 sql "update %s.account_operation set status1 where username%s" % (allResDBInfos[db], username)变量替换后&#xff0c;是下面的样子 update suspects.account_operation set st…

8086段寄存器

8086有四个段寄存器CS,DS,SS,ES 任意时刻CPU执行CS:IP指向的指令,CS为代码段寄存器(IP为指令指针寄存器) 任意时刻SS:SP指向栈的栈顶单元,SS为栈段寄存器 我们寻找数据需要知道数据在内存的位置用DS寻址 DS为数据段寄存器 ES为附加段寄存器可作为目的地址的段地址比如ES:DI…

用jquery给元素绑定事件,一些内部细节

按看段代码&#xff1a; 1 $(.test).on(click, function() { 2 console.log(hello); 3 $(this).removeClass(test); 4 }); 就算是remove掉class test&#xff0c;照样可以点&#xff0c;事件绑定的是这个对象。 转载于:https://www.cnblogs.com/lqj12138/p/4384596.html

8086数据寄存器

8086CPU有四个16位数据寄存器可分成8个8位寄存器 AX(AH,AL)|BX(BH,BL)|CX(CH,CL)|DX(DH,DL) 数据寄存器主要用来保存操作数和保存运算结果等 AX 常用作累加器(accumulator)用来保存临时数据比如MOV AX,DATA将数据段地址送入AX ;MUL BL,DIV BX用来保存乘除法的结果 BX 基(Ba…

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

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

《哪来的天才?练习中的平凡与伟大》

这是一本堪称论述所有伟大成就来源的书中最让我觉得激动人心、非常棒的一本书。 什么成就了一个那些所谓的天才&#xff1f;刻意练习&#xff01;伟大的成就不是因为所谓天生的基因&#xff0c;也不是所谓简单的埋头苦干。而是需要长时间有针对性的刻意提高自己某个方面能力的艰…

8086变址和指针寄存器

SI和DI称为变址寄存器,在字符串操作中SI作为源指针,DI作为目的指针(ES:DI<--DS:SI) ;用作存储器指针时可用于寻址 DS:[SI],DS:[BXDI]BP和SP称为指针寄存器,BP称为基址针,SP为堆栈指针 ;BP也可作为存储器指针DS:[bpsi],如果没有段前缀那么BP最为堆栈基址[BP]寻址的是堆栈内存…

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

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

省赛之路第一天

今天是清明假期第一天&#xff0c;原定的到洛阳玩也成为了虚无缥缈的东东了吧&#xff0c;cb这位还有说的太对了&#xff0c;no game&#xff0c;no girlfriend&#xff0c;no holiday&#xff0c;only maching&#xff01;这都不是什么大事&#xff0c;毕竟自认为还是个肯吃苦…

8086标志寄存器FLAG

8086CPU提供一个特殊的寄存器称为标志寄存器,里面包含9个标志,用来反映处理器的状态和运算结果的某些特征。FLAG是按位起作用的

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、安装 以…