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.pswp.cn/news/375196.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/375196.shtml
英文地址,請注明出處:http://en.pswp.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、安裝 以…