SlideShare a Scribd company logo
1 of 49
Hibernate 
O/R MAPPING TOOL. 
Trung Tâm Công Nghệ Phần Mềm Tp.Hồ Chí 
Minh 
4/9/04 
Kỹ sư Nguyễn Hữu Phước
Nội dung trình bày 
● Khái quát về Hibernate. 
● Sử dụng Hibernate. 
● Các công cụ hữu ích khi dùng Hibernate. 
● Hibernate vs. JDO. 
● Các Persistence Framework khác. 
● Tóm tắt. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Giới thiệu về Hibernate 
● Vấn đề:Trong lập trình hướng đối tượng, 
các lập trình viên thao tác trên các đối 
tượng. Do đó họ thường phải tự mình tạo ra 
và quản lý một lớp để lưu trữ và khôi phục 
lại các đối tượng từ cơ sở dữ liệu. 
● Hibernate ra đời để giải quyết phần nào vấn 
đề này. Hibernate cung cấp cho các lập 
trình viên Java một O/R persistence 
framework khá mạnh và dễ sử dụng. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Kiến trúc tổng quát của 
Hibernate 
Chương trình 
ứng dụng Java 
Các đối tượng Persistence 
Hibernate 
hibernate.properties XML mapping 
Cơ sở 
dữ liệu 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Kiến trúc tổng quát của 
Hibernate 
Các đối tượng Transient 
Session Factory 
Chương trình 
ứng dụng Java 
Các đối 
tượng 
Persistence 
Session 
Cơ sở dữ liệu 
Nguyễn Hữu Phước Hibernate-O/R mapping tool 
JBDC JNDI JTA 
Cấu trúc Runtime của Hibernate theo hướng chương trình ứng dụng 
quản lý JDBC connection và transaction.
Kiến trúc tổng quát của 
Hibernate 
Các đối tượng Transient 
Session Factory 
Chương trình 
ứng dụng Java 
Các đối 
tượng 
Persistence 
Session 
JBDC JNDI JTA 
Cơ sở dữ liệu 
Cấu trúc Runtime của Hibernate theo hướng chương trình 
ứng dụng không quản lý JDBC connection và transaction và 
để cho Hibernate lo mọi thứ. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool 
Transaction 
Transaction Factory 
ConnectionProvide 
r
Các đặc điểm của Hibernate 
● Là một công cụ để ánh xạ các đối tượng 
trong ứng dụng Java với cơ sở dữ liệu 
quan hệ. 
● Không dựa trên một tiêu chuẩn nào cả. 
● JMX integration:Hibernate có thể được 
quản lý thông qua JMX với standard 
Mbean. Nhưng hầu hết các bản hiện thực 
J2EE server hiện nay chưa hỗ trợ JMX 
nên Hibernate có thể sử dụng một số cơ 
chế khác. 
● Hỗ trợ JCA:Hibernate có thể được cấu 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Quá trình phát triển JAVA 
applications với Hibernate 
● Dùng các câu lệnh SQL tạo ra các bảng trong cơ sở 
dữ liệu để lưu trữ các đối tượng persistence. 
● Tạo các Java Bean để đại diện cho đối tượng trong 
chương trình ứng dụng. 
● Tạo ra tập tin ánh xạ để báo cho Hibernate biết 
thuộc tính nào của Java Bean tương ứng với trường 
nào trong bảng của CSDL. 
● Tạo ra tập tin hibernate.properties để cấu hình 
JDBC connection. 
● Sử dụng Hibernate API. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Simple Association(One-to- 
●Định nghĩa: Khi mOộtn lớep) có chứa một tham 
khảo đến một hiện hữu của lớp kia thông 
qua khoá chính. 
● Kịch bản: Bar Foo.getBar();//returns corressponding Bar instance 
● Hibernate mapping: 
● Table schema: 
<class name=”Foo” table=”foo”> 
.................. 
<one-to-one name=”bar” class=”Bar”/> 
</class> 
Bar 
id 
Foo 
id 
● Quan hệ 2 chiều: Quan hệ này có thể 2 
chiều Nguyễn Hữu Phước Hibernate-O/R mapping tool
Simple Reference(Many-to- 
●Định nghĩa: GiốngO nhnưe t)rường hợp one-to-one 
nhưng ở đây không dùng chung khoá 
chính mà thông qua khoá ngoại. 
● Kịch bản: Bar Foo.getBar() // returns corresponding Bar instance 
● Hibernate mapping: 
● Table schema: 
<class name="Foo" table="foo"> 
... 
<many-to-one name="bar" class="Bar" 
column="bar_id"/> 
</class> 
Bar 
id 
Foo 
id bar_id 
● Quan hệ 2 chiều: Quan hệ này có thể 2 
Nguyễnc Hhữuiề Puhước Hibernate-O/R mapping tool
Basic Collection(One-to- 
●Định nghĩa: Khi Mmộat nlớyp )có chứa một tham 
khảo đến một tập các hiện hữu của lớp kia. 
● Kịch bản: Set Foo.getBars();//returns a collection of Bar instances 
● Hibernate mapping: 
● Table schema: 
<class name=”Foo” table=”foo”> 
........................... 
<set role=”bars” table=”bar”> 
<key column=”foo_id”/> 
<one-to-many class=”Bar”/> 
</set> 
</class> 
Foo 
id 
Bar 
id foo_id 
● Quan hệ 2 chiều: Quan hệ này có thể 2 
chiều 
<class name=”Foo” table=”foo”> 
.................. 
<many-to-one name=”foo” class=”Foo” 
/> 
</class> 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Collection(Many-to-Many) 
● Định nghĩa: Khi một hiện hữu lớp A có chứa 
một tham khảo đến một tập các hiện hữu 
của lớp B và B cũng có thể có nhiều A .(A,B 
là lớp first-rank). 
● Kịch bản: Set Foo.getBars();//returns a collection of Bar instances 
● Hibernate mapping: 
● Table Foo 
schema: 
Bar 
foo_ba 
id 
id 
foo_idr bar_id 
● Quan hệ 2 chiều: 
<class name=”Foo” table=”foo”> 
........................... 
<set role=”bars” table=”foo_bar”> 
<key column=”foo_id”/> 
<many-to-many column=”bar_id” class=” 
Bar”/> 
</set> 
</class> 
<class name=”Foo” table=”foo”> 
.................. 
<set role="foos" table="foo_bar"> 
<key column="bar_id"/> 
<many-to-many column="foo_id" 
class="Foo"/> 
</set> 
</class> 
NguyễQn uHaữun hệ này có Hthibểer n2at ec-Oh/iRề muapping tool
Collection(Raw Data) 
● Định nghĩa: Khi một hiện hữu lớp A có chứa 
một tham khảo đến một tập các hiện hữu 
của lớp B.A là first-rank và B là second-rank. 
● Kịch bản: Set Foo.getPeople();//returns a collection of String 
instances 
● Hibernate mapping: 
● Table schema: 
<class name=”Foo” table=”foo”> 
........................... 
<set role=”people” table=”Person”> 
<key column=”foo_id”/> 
<element column=”name” type=”string”/> 
</set> 
</class> 
Foo 
id 
Perso 
foo_idn nam 
e 
● Quan hệ 2 chiều: Không có quan hệ hai 
Nguyễn Hcữhu iều. Hibernate-O/R mapping tool
Sorted Collections 
● Hibernate hỗ trợ 2 bản hiện thực cho java. 
util.Collections là java.util.SortedMap va java. 
util.SortedSet 
● Thuộc tính sort có thể là unsorted,natural 
hay tên của class hiện thực java.util. 
Comparator. 
<set name="aliases" table="person_aliases" sort="natural"> 
<key column="person"/> 
<element column="name" type="string"/> 
</set> 
<map name="holidays" sort="my.custom.HolidayComparator" 
lazy="true"> 
<key column="year_id"/> 
<index column="hol_name" type="string"/> 
<element column="hol_date type="date"/> 
</map> 
Sorted collections 
giống như java.util. 
TreeSet hay java. 
util.TreeMap 
Nguyễn Hữu Hibernate-O/R mapping tool
Sorted Collections 
● Có thể sử dụng thuộc tính order-by của các 
phép ánh xạ set,bag,map để bảo CSDL tự 
động sắp xếp các phần tử của một tập hợp. 
● Việc sắp xếp xảy ra khi truy vấn chứ không 
phải trong bộ nhớ. 
● Sorted association có thể dùng filter() 
<set name="aliases" table="person_aliases" order-by="name asc" 
> 
<key column="person"/> 
<element column="name" type="string"/> 
</set> 
<map name="holidays" order-by="hol_date, hol_name" lazy="true" 
> 
<key column="year_id"/> 
<index column="hol_name" type="string"/> 
<element column="hol_date type="date"/> 
</map> 
Lưu ý:Thuộc tính order-by là 
của SQL chứ không phải của 
HQL 
Nguyễn Hữu Hibernate-O/R mapping tool
Top-level Collections 
● Định nghĩa: Top-level collections là các tập 
hợp mà nó nằm bên ngoài tầm vực từng lớp 
nhưng được sử dụng trong các lớp ở các tập 
tin ánh xạ. 
● Kịch bản: Set Foo.getNames();//returns a collection of String 
instances 
● Hibernate Foo 
mapping: 
Perso 
id person_i 
id n nam 
● Table schema: 
d 
● Quan hệ 2 chiều: 
<set role="names" table="person"> 
<key column="id" type="string"> 
<generator class="uuid.hex"/> 
</key> 
<element column="name" type="string"/> 
</set> 
<class name="Foo" table="foo"> 
... 
<collection name="names" column="person_id" 
role="names"/> 
</class> 
e 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Map 
● Định nghĩa: Map là một danh sách của các 
cặp tên-giá trị. 
● Kịch bản: 
Map Foo.getAges();//returns a collection of String name-value pairs 
● Hibernate mapping: 
● Table schema: 
<class name="Foo" table="foo"> 
... 
<map role="ages"> 
<key column="id"/> 
<index column="name" type="string"/> 
<element column="age" type="string"/> 
</map> 
</class> 
Foo 
Ages 
id age 
id nam 
e 
● Quan hệ 2 chiều: 
Quan hệ hai chiều không có ý nghĩa đối với map. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Entity Map 
● Định nghĩa: Entity map là một map mà khoá 
của nó là một thực thể chứ không phải là 
một thuộc tính đơn. 
● Kịch bản: 
Map Foo.getAges();//returns a collection of Person-String instances 
● Hibernate mapping: 
● Table schema: 
<class name="Foo" table="foo"> 
... 
<map role="ages"> 
<key column="id"/> 
<index-many-to-many column="person_id" class="Person"/> 
<element column="age" type="string"/> 
</map> 
</class> 
<class name="Person" table="person"> 
... 
<property name="name" column="name" type="string"/> 
</class> 
Foo 
Ages 
id id person_id 
age 
Person 
id nam 
e 
● Quan hệ 2 chiều: 
Quan hệ hai chiều không có ý nghĩa đối với entity 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
●Định nghĩa: MộSt usubbcclalasss lsà emsột first-rank class 
mà nó mở rộng từ một first-rank class khác 
theo đúng tiêu chuẩn thừa kế trong mô hình 
hướng đối tượng 
● Kịch bản: 
<class name="Foo" table="foo" discriminator-value="F"> 
public class Bar extends Foo;//Bar is ... 
a subclass of Foo 
<discriminator column="class"/> 
● Hibernate mapping: 
... 
<subclass name="subclass.Bar" discriminator-value="B"> 
● Table schema: 
<property name="name" column="name" type="string"/> 
Foo 
</subclass> 
id descriminator name 
</class> 
(Lưu ý ở đây có cách hiện thực khác Foo-Bar độc lập) 
● Quan hệ 2 chiều:Quan hệ kế thừa là chỉ có một 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Foo 
id name 
Joined Subclass 
● Định nghĩa: Joined subclass là các subclass 
mà chúng được ánh xạ thành mỗi bảng một 
subclass tốt hơn là một bảng cho toàn bộ cây 
thừa kế. 
● Kịch bản: 
<class name="Foo" table="foo"> 
public class Bar extends Foo;//Bar is ... 
a subclass of Foo 
<property name="name" column="name" type="string" 
● Hibernate mapping: 
<joined-subclass name="subclass.Bar" table="bar"> 
<key column="foo_id"/> 
● Table schema: 
<property name="age" column="age" type="string"/> 
Bar 
</joined-subclass> 
foo_id age 
</class> 
(Lưu ý ở đây có cách hiện thực khác Foo-Bar độc lập) 
● Quan hệ 2 chiều:Quan hệ kế thừa là chỉ có một 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Components 
● Định nghĩa: Một component là một Java class 
mà nó chính là một số cột nhất định trong bảng 
của một class khác. 
● Kịch bản: 
FooSecond Foo.getSecond();// returns enclosed second-rank instance 
● Hibernate mapping: 
● Table schema: 
<class name="Foo" table="foo"> 
... 
<component name="second" class="FooSecond"> 
<property name="firstName"/> 
<property name="lastName"/> 
</component> 
</class> 
Foo 
id firstName lastName 
● Quan hệ 2 chiều:Chỉ có quan hệ một chiều. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Collections of Components 
● Định nghĩa: Tập hợp các component là có thể 
xảy ra nhất là khi làm việc với một top-level 
collection phức tạp. 
● Kịch bản: 
Set Foo.getSeconds();// returns a collection of FooSecond instances 
● Hibernate mapping: 
● Table schema: 
<set role="seconds"> 
<key column="id" type="string"> 
<generator class="uuid.hex"/> 
</key> 
<composite-element class="FooSecond"> 
<property name="firstName"/> 
<property name="lastName"/> 
</composite-element> 
</set> 
<class name="Foo" table="foo"> 
... 
<collection name="seconds" column="seconds_id" role=" 
seconds"/> 
</class> 
Seconds 
id firstName lastName 
Foo 
id seconds_id 
● Quan hệ 2 chiều: 
NCguhyễỉn cHóữu Pqhuướacn hệ mHộibetr ncahte-iOề/Ru m. apping tool
Composite Identifier 
● Định nghĩa:Một lớp có composite identifier là 
lớp mà khoá chính nó bao gồm nhiều cột. 
● Kịch bản: Foo có id kiểu Person. Person bao 
gồm name kiểu String và address kiểu 
Address. 
Person Foo.getId();// PK is multi-column mapped 
● Hibernate mapping: 
● Table schema: 
<class name="Foo" table="foo"> 
<composite-id name="id" class="Person"> 
<key-property name="name" type="string" column="name" 
/> 
<key-many-to-one name="address" class="Address" 
column="addr_id"/> 
</composite-id> 
<property name="age" column="age" type="string"/> 
</class> 
<class name="Address" table="address"> 
... 
</class> 
Address 
id 
Foo 
name addr_id age 
● Quan hệ 2 chiều: 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Composite Index 
● Định nghĩa:Composite Index cung cấp để giải 
quyết trường hợp khoá của Map có nhiều cột. 
● Kịch bản: Foo chứa Map của tuổi.Khóa của Map này có kiểu Person. 
Person bao gồm name kiểu String và address kiểu Address. 
Map Foo.getAges();// Foo contains a map of ages, keyed by Person 
● Hibernate mapping: 
● Table schema: 
<class name="Foo" table="foo"> 
... 
<map role="ages"> <key column="id"/> 
<composite-index class="Person"> 
<key-property name="name" type="string" column="name"/> 
<key-many-to-one name="address" class="Address" 
column="addr_id"/> 
</composite-index> 
<element column="age" type="string"/> 
</map> 
</class> 
<class name="Address" table="address"> ...</class> 
Address 
id 
Ages 
name addr_id id age 
Foo 
id 
● Quan hệ 2 chiều: 
NQguuyễan Hnữ uh Pệhư 2ớc chiều Hkibherônanteg-O /cR óm anppginhg tĩoaol.
Dynabean Component 
● Định nghĩa:<dynabean > giống với 
<component>. Thuận lợi của ánh xạ này là cho 
phép xác định các thuộc tính thật sự của bean 
lúc triển khai bằng cách thay đổi tập tin ánh xạ 
● Hibernate mapping: 
<dynabean name="second" dynaclass="Seconds"> 
<property name="firstName" column="FirstName"/> 
<property name="lastName" column="Lastname"/> 
</dynabean> 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Ternary Associations 
● Định nghĩa:Ternary association là một mối liên 
hệ có 3 lớp tham gia. 
● Kịch bản: Bar BarSnafu.getBar() // Retrieve Bar from BarSnafu 
Snafu BarSnafu.getSnafu() // Retrieve Snafu from BarSnafu 
Set Foo.getBarSnafus() // Retrieve set of BarSnafus from Foo 
● Hibernate mapping: 
● Table schema: 
<class name="Foo" table="foo"> 
... 
<set role="barsnafus" table="foo_bar_snafu"> 
<key column="foo_id"/> 
<composite-element class="BarSnafu"> 
<many-to-one name="bar" class="Bar" column="bar_id"/> 
<many-to-one name="snafu" class="Snafu" column="snafu_id" 
/> 
</composite-element> 
</set> 
</class> 
... 
Bar 
id 
Snaf 
u id 
Foo_Bar_Snafu 
foo_id bar_id snafu_id 
Foo 
id 
● Quan hệ 2 chiều: 
Quan hệ 2 chiều không có nghĩa. Nguyễn Hữu Phước Hibernate-O/R mapping tool
Heterogeneous Associations 
● Hibernate cung cấp các phần tử <many-to-any> 
và <index-many-to-any> dùng để ánh xạ 
các heterogenous association. Chúng hoạt 
động giống như <any> 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Lazy Initialization 
● Định nghĩa:Các tập hợp (collections) có được 
khởi động kiểu lazy tức là trạng thái của chúng 
chỉ được cập nhật khi chương trình ứng dụng 
cần đến. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
HQL:Hibernate Query 
●Case sesitivity: LKhaônngg uphaâgn ebiệt hoa thường 
trừ tên lớp và các thuộc tính. 
● Mệnh đề from: 
○ from pet.Cat: trả về tất cả các đối tượng của pet. 
Cat. 
○ Bí danh: from pet.Cat as cat hay from pet.Cat cat 
gán bí danh cat cho các đối tượng pet.Cat. 
○ Có thể sử dụng nhiều lớp ở mệnh đề from và kết 
quả trả về là tích Đề các hay cross join. 
○ Để phù hợp với qui tắc đặc tên biến trong Java nên 
Nguyễn Hđữặuc P hbưíớ cdanh bắHti bđeầrnuate b-Oằ/Rn mga kppíi ntgự to tohl ường.
HQL:Hibernate Query 
●Association andL Jaoinnsg:uage 
○ inner join,left outer join,right outer join,full join. 
○ Inner join,left outer join,right outer join viết tắt join,left join, 
right join. 
○ fetch join. 
● Mệnh đề select: Chọn đối tượng và các thuộc 
tính nào của đối tượng được trả về trong tập 
kết quả. 
○ Hàm elements: select elements(cat.kittens) from cat.Cat cat 
trả về tất cả các kitten của cat. 
○ Câu truy vấn có thể trả về các thuộc tính của bất kỳ kiểu dữ 
liệu gì như các thuộc tính của kiểu thành phần, các đối 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
HQL:Hibernate Query 
●Aggregate functLioansn:guage 
○ min(..),max(..),avg(..),sum(..),count(*),count(..),count(distinct 
..),count(all ..). 
○ Từ khoá distinct và all. 
○ Các tập hợp có thể là đối số của các hàm trên. 
● Polymorphism(Tính đa hình): 
○ Có thể đặt tên lớp hay tên interface trong mệnh đề from khi 
đó kết quả trả về là tất cả các hiện hữu của các lớp 
persistent mà nó mở rộng lớp này hay hện thực interface 
này. 
○ Ví dụ: Xét câu truy vấn from animal.Cat thì trả về các đối 
tượng thuộc lớp animal.Cat và cả các đối tượng thuộc lớp 
Nguyễn Hcoữun Pahnưiớmc al.DomeHsibtiecrnCaatet-O/R mapping tool
HQL:Hibernate Query 
●Mệnh đề whereL: anguage 
○ Hạn chế danh sách các hiện hữu trả về bằng một biểu thức 
điều kiện 
○ Lưu ý “=” dùng cho cả thuộc tính và đối tượng. 
○ Thuộc tính đặc biệt id,class. 
● Expressions: 
Parentheses ( ) indicate grouping 
in, between, is null 
JDBC IN parameters ? 
named parameters :name, :start_date, :x1 
SQL literals 'foo', 69, '1970-01-01 10:00:01.0' 
Java public static final constants eg.Color. 
TABBY 
mathematical operators +, -, *, / 
binary comparison operators =, >=, <=, <>, !=, like 
logical operations and, or, not 
string concatenation || 
SQL scalar functions like upper() and lower() 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
HQL:Hibernate Query 
●Mệnh đề Order LBay:nguage 
○ Sắp xếp thứ tự danh sách trả về theo bất kỳ thuộc tính nào 
của class hay component. 
○ Các từ khoá desc,asc 
○ Ví dụ 
from eg.DomesticCat cat 
order by cat.name asc, cat.weight desc, cat.birthdate 
● Mệnh đề Group By: 
○ elements,indices 
○ Having 
○ Lưu ý : group by và order by không chứa biểu thức 
số học. Aggregative functions đượcphép dùng trong 
Nguyễn Hmữuệ Pnhhư ớđcề havinHgib evrnàa toe-rOd/Re mr abpypi.ng tool
HQL:Hibernate Query 
●Subqueries: Language 
○ Hỗ trợ subqueries kể cả correlated subqueries. 
○ Subqueries phải được đặt trong cặp dấu (). 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Các công cụ 
● Hibernate project's tools: 
○ Schema Generation:SchemaExport,hdm2ddl 
○ Code Generation:CodeGenerator,hdm2java 
○ Mapping File Generation:MapGenerator, 
hdm2class 
● Third party tools: 
○ Middlegen: Sinh ra tập tin ánh xạ từ cấu trúc 
của một CSDL có sẵn. 
○ AndroMDA:Sinh ra mã nguồn cho các 
persistent class từ mô hình UMLvà các ký 
Nguyễn Hữuh Pihệưuớ cXML/XMHibI ecrnủatae- Ori/êR nmgap pmingìn toho.l
Schema Generation 
● Mục đích: Sinh ra DDL từ tập tin ánh xạ. 
● Công cụ:SchemaExport. 
● Thực thi: 
○ java -cp hibernate_classpaths net.sf.hibernate.tool.hbm2ddl.SchemaExport 
options mapping_files 
○ Ngay cả trong mã nguồn. 
○ Dùng Ant để update schema. 
● Đặc điểm: 
○ Đảm bảo tính toàn vẹn tham khảo(khoá chính, khoá ngoại) cho 
các thực thể và các bảng tập hợp. 
○ Tạo ra các bảng và các sequence, index cho các khoá. 
● Customize Schema: 
○ length,not-null,sql-type,unique,index,unique-key. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Code Generation 
● Mục đích: Sinh ra bộ khung của bản hiện 
thực các lớp từ tập tin ánh xạ. 
● Công cụ:CodeGenerator. 
● Thực thi: 
○ java -cp hibernate_classpaths net.sf.hibernate.tool.hbm2java.CodeGenerator options 
mapping_files 
● Tập tin config. 
● Meta tag:Dùng để cung cấp thêm thông tin 
cho .hbm.xml và hbm2java 
● Basic finder generator: 
○ Trường nào cần sinh finder.Dùng meta tag trong property tag. 
Nguyễn ○HTữuạ oP htậưpớ ctin config cHhiob ehrbnmate2-jOav/Ra mvàa pdpùinngg t–ocool nfig.
Mapping File Generation 
● Mục đích: Sinh ra bộ khung tập tin ánh xạ từ 
các lớp persistent đã được biên dịch. 
● Công cụ:MapGenerator. 
● Thực thi: 
○ java -cp hibernate_and_your_class_classpaths net.sf.hibernate.tool.class2hbm.MapGenerator optionsand 
classnames 
● Không thể sinh ra tập tin ánh xạ đầy đủ mà 
không cần thêm thông tin từ người sử dụng. 
● Loại bỏ các class không phải là Hibernate 
persistable. 
● Các luật để xác định kiểu ở CSDL cho một 
Nguyễnth Huữuộ Pchư ớtícnh Hibernate-O/R mapping tool
Hibernate Persistable Class 
● Không phải là một kiểu định nghĩa trước. 
● Không phải là một array. 
● Không phải là một interface. 
● Không phải là một lớp lồng bên trong một lớp 
khác. 
● Phải có phương thức khởi tạo(constructor) 
mặc định tức là phương thức khởi tạo không 
có tham số hình thức. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Xác định kiểu CSDL cho thuộc 
●Hibernate.basic()-->t ímnộht cột có kiểu tương 
ứng. 
● net.sf.hibernate.tye.Type và PersistentEnum-- 
> Một cột trong DB. 
● Kiểu dãy (array) thì Hibernate array được sử 
dụng. 
● Kểu java.util.List, java.util.Map, java.util.Se các 
--> Kiểu tương ứng của Hibernate. 
MapGenerator không xử lý bên trong. 
● Là lớp bất kỳ-->Có superclass, many-to-one 
được sử dụng, thuộc tính của nó là 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
IMPROVING PERFORMANCE 
● Proxies for lazy initialization 
● Xử lý mức cache. 
● Quản lý session cache. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Xử lý mức Cache 
● Hibernate sử dụng Apache Turine JCS cho 
factory-level caching. 
● Mapping: Sử dụng <jcs-cache> 
<jcs-cache usage="read-write|nonstrict-read-write|read-only"/> 
● read-only cache: Nếu chương trình chỉ đọc mà 
không thay đổi các đối tượng trên cache. 
● read-write cache: Chương trình thỉnh thoảng cập 
nhật thông tin. 
● nonstrict-read-write cache: Chương trình cần cập 
nhật dữ liệu và việc cô lập phiên làm việc không 
Nguyễnc Hầữnu Pđhặướt cra. Hibernate-O/R mapping tool
Quản lý Session Cache 
● Một đối tượng được cache ở session cache 
khi: 
○ Truyền một đối tượng cho save(),update(),saveOrUpdate() 
○ Truy xuất một đối tượng thông qua load(),find(),filter(),iterate(). 
● Khi flush() được gọi thì trạng thái của đối 
tượng sẽ đồng bộ với CSDL. 
● Quản lý session cache: 
○ Phương thức evict(): xoá đối tượng hay tập đối tượng khỏi session 
cache. 
○ Session.contains(): Một đối tượng có nằm trong session cache 
không. 
○ JVM-level JCS cache trong SessionFactory. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Thao tác trên đối tượng 
● Khởi động(Initialization) 
● Tạo/nạp các đối tượng(Creating/loading) 
● Cập nhật/Xoá các đối tượng 
(Updating/Deleting) 
● Cập nhật các đối tượng của session khác. 
● Lọc kết quả truy vấn. 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Khởi động 
//Loading the configuration 
// Looks for mapping files in same classpath location 
Configuration cfg = new Configuration(). addClass( eg. 
Vertex. class ). addClass( eg. Edge. class); 
// This binds you to a database configuration 
SessionFactory sessions = cfg. buildSessionFactory (); 
// obtain a JDBC connection and instantiate a new 
Session 
Session sess = sessions. openSession (); 
// start a new transaction (optional) 
Transaction tx = sess. beginTransaction(); 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Tạo/nạp các đối tượng 
● Tạo đối tượng: 
○ Customer cuss= new Customer(); 
○ ..... 
○ Long id=(Long)sess.save(cuss); 
● Nạp đối tượng: 
○ Customer cuss = (Customer)sess.load(Customer. 
class,id); 
○ Set cusses=sess.find(...); 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Cập nhật/Xoá các đối tượng 
● Cập nhật đối tượng: 
○ Customer cuss=(Customer)sess.load(Customer. 
class,id); 
○ cuss.set(..); 
○ sess.flush(); 
● Xoá đối tượng: 
○ sess.delete(cuss); 
○ sess.delete(Câu HQL); 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
hibernate.properties 
hibernate.connection.username SYSDBA 
hibernate.connection.password masterkey 
hibernate.connection.url jdbc:firebirdsql:localhost: 
/example/a.gdb 
hibernate.connection.driver_class org.firebirdsql.jdbc. 
FBDriver 
hibernate.dialect net.sf.hibernate.dialect. 
InterbaseDialect 
Nguyễn Hữu Phước Hibernate-O/R mapping tool
Hibernate vs. JDO 
Hibernate 
● Chỉ một nhà cung 
cấp. 
● Mã nguồn mở. 
● HQL tiện dụng. 
● Sử dụng quá trình 
build chuẩn 
JDO 
● Tuân thủ chuẩn JCP 
● Phần mềm thương mại 
(có một số là dự án mã 
nguồn mở Speedo 
nhưng còn giai đoạn 
đầu) 
● Chỉnh sửa các tập tin 
class(Thêm một bước 
khi biên dịch) 
● Hỗ trợ cả các lưu trữ 
không là CSDL quan hệ 
Nguyễn Hữu Phước Hibernate-O/R mapping tool

More Related Content

What's hot

Using MongoDB as a high performance graph database
Using MongoDB as a high performance graph databaseUsing MongoDB as a high performance graph database
Using MongoDB as a high performance graph databaseChris Clarke
 
Introduction to Reactive programming
Introduction to Reactive programmingIntroduction to Reactive programming
Introduction to Reactive programmingDwi Randy Herdinanto
 
HBaseConEast2016: How yarn timeline service v.2 unlocks 360 degree platform i...
HBaseConEast2016: How yarn timeline service v.2 unlocks 360 degree platform i...HBaseConEast2016: How yarn timeline service v.2 unlocks 360 degree platform i...
HBaseConEast2016: How yarn timeline service v.2 unlocks 360 degree platform i...Michael Stack
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcachedJurriaan Persyn
 
Concurrent Programming Using the Disruptor
Concurrent Programming Using the DisruptorConcurrent Programming Using the Disruptor
Concurrent Programming Using the DisruptorTrisha Gee
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 
Introduction to graphQL
Introduction to graphQLIntroduction to graphQL
Introduction to graphQLMuhilvarnan V
 
Scala API - Azure Event Hub Integration
Scala API - Azure Event Hub IntegrationScala API - Azure Event Hub Integration
Scala API - Azure Event Hub IntegrationBraja Krishna Das
 
Spring Boot Actuator
Spring Boot ActuatorSpring Boot Actuator
Spring Boot ActuatorRowell Belen
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentationOleksii Usyk
 
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...Edureka!
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisDvir Volk
 
About elasticsearch
About elasticsearchAbout elasticsearch
About elasticsearchMinsoo Jun
 

What's hot (20)

Rest api with node js and express
Rest api with node js and expressRest api with node js and express
Rest api with node js and express
 
Using MongoDB as a high performance graph database
Using MongoDB as a high performance graph databaseUsing MongoDB as a high performance graph database
Using MongoDB as a high performance graph database
 
Introduction to Reactive programming
Introduction to Reactive programmingIntroduction to Reactive programming
Introduction to Reactive programming
 
Apache Kafka at LinkedIn
Apache Kafka at LinkedInApache Kafka at LinkedIn
Apache Kafka at LinkedIn
 
HBaseConEast2016: How yarn timeline service v.2 unlocks 360 degree platform i...
HBaseConEast2016: How yarn timeline service v.2 unlocks 360 degree platform i...HBaseConEast2016: How yarn timeline service v.2 unlocks 360 degree platform i...
HBaseConEast2016: How yarn timeline service v.2 unlocks 360 degree platform i...
 
GraphQL-ify your APIs
GraphQL-ify your APIsGraphQL-ify your APIs
GraphQL-ify your APIs
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcached
 
Concurrent Programming Using the Disruptor
Concurrent Programming Using the DisruptorConcurrent Programming Using the Disruptor
Concurrent Programming Using the Disruptor
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Introduction to graphQL
Introduction to graphQLIntroduction to graphQL
Introduction to graphQL
 
Scala API - Azure Event Hub Integration
Scala API - Azure Event Hub IntegrationScala API - Azure Event Hub Integration
Scala API - Azure Event Hub Integration
 
Spring Boot Actuator
Spring Boot ActuatorSpring Boot Actuator
Spring Boot Actuator
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorial
 
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
Spring Interview Questions and Answers | Spring Tutorial | Spring Framework T...
 
Why JSON API?
Why JSON API?Why JSON API?
Why JSON API?
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
About elasticsearch
About elasticsearchAbout elasticsearch
About elasticsearch
 

Viewers also liked

Linq n hibernate net-tier
Linq n hibernate net-tierLinq n hibernate net-tier
Linq n hibernate net-tierNguyen Tran
 
Supporting Students' Learning in an Open World
Supporting Students' Learning in an Open WorldSupporting Students' Learning in an Open World
Supporting Students' Learning in an Open WorldLiz Masterman
 
Shot types ppt
Shot types pptShot types ppt
Shot types pptecsmedia
 
Corredores Digitais - 26å Conferência Anprotec
Corredores Digitais - 26å Conferência AnprotecCorredores Digitais - 26å Conferência Anprotec
Corredores Digitais - 26å Conferência AnprotecKarine Pinheiro
 
Reflections on the evolving landscape of OER use
Reflections on the evolving landscape of OER use Reflections on the evolving landscape of OER use
Reflections on the evolving landscape of OER use Liz Masterman
 
Sosiaalinen media osaksi opetusta
Sosiaalinen media osaksi opetustaSosiaalinen media osaksi opetusta
Sosiaalinen media osaksi opetustaHannu Kuusela
 
виктор ефимов «Unicode в perl и как перевести на него систему» (yapc russia ...
виктор ефимов «Unicode в perl и как перевести на него систему» (yapc  russia ...виктор ефимов «Unicode в perl и как перевести на него систему» (yapc  russia ...
виктор ефимов «Unicode в perl и как перевести на него систему» (yapc russia ...Nikolay Mishin
 
Nwill 2013 Whither ILL? Wither ILL: The Changing Nature of Resource Sharing i...
Nwill 2013 Whither ILL? Wither ILL: The Changing Nature of Resource Sharing i...Nwill 2013 Whither ILL? Wither ILL: The Changing Nature of Resource Sharing i...
Nwill 2013 Whither ILL? Wither ILL: The Changing Nature of Resource Sharing i...Michael Levine-Clark
 
Bot how to find them 2014_27_03
Bot how to find them 2014_27_03Bot how to find them 2014_27_03
Bot how to find them 2014_27_03IABmembership
 
Ali hokes Shots
Ali hokes ShotsAli hokes Shots
Ali hokes Shotsecsmedia
 
ATIVIDADES DO LIVRO :MISTÉRIO NO GALINHEIRO
ATIVIDADES DO LIVRO :MISTÉRIO NO GALINHEIROATIVIDADES DO LIVRO :MISTÉRIO NO GALINHEIRO
ATIVIDADES DO LIVRO :MISTÉRIO NO GALINHEIRODiego Mendes
 
Camera shots
Camera shots Camera shots
Camera shots ecsmedia
 
Pre production work jordan
Pre production work jordanPre production work jordan
Pre production work jordanecsmedia
 
BALWOIS 2010
BALWOIS 2010BALWOIS 2010
BALWOIS 2010D Kannan
 

Viewers also liked (20)

Linq n hibernate net-tier
Linq n hibernate net-tierLinq n hibernate net-tier
Linq n hibernate net-tier
 
Supporting Students' Learning in an Open World
Supporting Students' Learning in an Open WorldSupporting Students' Learning in an Open World
Supporting Students' Learning in an Open World
 
Shot types ppt
Shot types pptShot types ppt
Shot types ppt
 
Corredores Digitais - 26å Conferência Anprotec
Corredores Digitais - 26å Conferência AnprotecCorredores Digitais - 26å Conferência Anprotec
Corredores Digitais - 26å Conferência Anprotec
 
Reflections on the evolving landscape of OER use
Reflections on the evolving landscape of OER use Reflections on the evolving landscape of OER use
Reflections on the evolving landscape of OER use
 
Sosiaalinen media osaksi opetusta
Sosiaalinen media osaksi opetustaSosiaalinen media osaksi opetusta
Sosiaalinen media osaksi opetusta
 
Record label research
Record label researchRecord label research
Record label research
 
Record label research
Record label researchRecord label research
Record label research
 
виктор ефимов «Unicode в perl и как перевести на него систему» (yapc russia ...
виктор ефимов «Unicode в perl и как перевести на него систему» (yapc  russia ...виктор ефимов «Unicode в perl и как перевести на него систему» (yapc  russia ...
виктор ефимов «Unicode в perl и как перевести на него систему» (yapc russia ...
 
Nwill 2013 Whither ILL? Wither ILL: The Changing Nature of Resource Sharing i...
Nwill 2013 Whither ILL? Wither ILL: The Changing Nature of Resource Sharing i...Nwill 2013 Whither ILL? Wither ILL: The Changing Nature of Resource Sharing i...
Nwill 2013 Whither ILL? Wither ILL: The Changing Nature of Resource Sharing i...
 
Bot how to find them 2014_27_03
Bot how to find them 2014_27_03Bot how to find them 2014_27_03
Bot how to find them 2014_27_03
 
Chapter 1 Overview
Chapter 1   OverviewChapter 1   Overview
Chapter 1 Overview
 
The Numb3rs of OzTV
The Numb3rs of OzTVThe Numb3rs of OzTV
The Numb3rs of OzTV
 
что я делал последние 5 лет
что я делал последние 5 летчто я делал последние 5 лет
что я делал последние 5 лет
 
Resume 08-13-2015s
Resume 08-13-2015sResume 08-13-2015s
Resume 08-13-2015s
 
Ali hokes Shots
Ali hokes ShotsAli hokes Shots
Ali hokes Shots
 
ATIVIDADES DO LIVRO :MISTÉRIO NO GALINHEIRO
ATIVIDADES DO LIVRO :MISTÉRIO NO GALINHEIROATIVIDADES DO LIVRO :MISTÉRIO NO GALINHEIRO
ATIVIDADES DO LIVRO :MISTÉRIO NO GALINHEIRO
 
Camera shots
Camera shots Camera shots
Camera shots
 
Pre production work jordan
Pre production work jordanPre production work jordan
Pre production work jordan
 
BALWOIS 2010
BALWOIS 2010BALWOIS 2010
BALWOIS 2010
 

Similar to Hiberbate Framework

Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate FrameworkPhuoc Nguyen
 
Cấu hình Hibernate
Cấu hình HibernateCấu hình Hibernate
Cấu hình HibernateMinh Quang
 
Lập trình hướng đối tượng trong PHP
Lập trình hướng đối tượng trong PHPLập trình hướng đối tượng trong PHP
Lập trình hướng đối tượng trong PHPJino Hoàng
 
Lập trình hướng đối tượng trong PHP
 Lập trình hướng đối tượng trong PHP Lập trình hướng đối tượng trong PHP
Lập trình hướng đối tượng trong PHPNETKO Solution
 
Speaker dang minh tuan javascript for php developer
Speaker dang minh tuan   javascript for php developerSpeaker dang minh tuan   javascript for php developer
Speaker dang minh tuan javascript for php developerAiTi Education
 
Javascript for php developer
Javascript for php developerJavascript for php developer
Javascript for php developerDang Tuan
 
Print_to_OOP.pdf
Print_to_OOP.pdfPrint_to_OOP.pdf
Print_to_OOP.pdfcLong52
 

Similar to Hiberbate Framework (8)

Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Cấu hình Hibernate
Cấu hình HibernateCấu hình Hibernate
Cấu hình Hibernate
 
Lập trình hướng đối tượng trong PHP
Lập trình hướng đối tượng trong PHPLập trình hướng đối tượng trong PHP
Lập trình hướng đối tượng trong PHP
 
Bai02 java introduction
Bai02 java introductionBai02 java introduction
Bai02 java introduction
 
Lập trình hướng đối tượng trong PHP
 Lập trình hướng đối tượng trong PHP Lập trình hướng đối tượng trong PHP
Lập trình hướng đối tượng trong PHP
 
Speaker dang minh tuan javascript for php developer
Speaker dang minh tuan   javascript for php developerSpeaker dang minh tuan   javascript for php developer
Speaker dang minh tuan javascript for php developer
 
Javascript for php developer
Javascript for php developerJavascript for php developer
Javascript for php developer
 
Print_to_OOP.pdf
Print_to_OOP.pdfPrint_to_OOP.pdf
Print_to_OOP.pdf
 

More from Phuoc Nguyen

Android location sensor programming
Android location sensor programmingAndroid location sensor programming
Android location sensor programmingPhuoc Nguyen
 
Android Nâng cao-Bài 6-Multi theme-adb tool-jUnit
Android Nâng cao-Bài 6-Multi theme-adb tool-jUnitAndroid Nâng cao-Bài 6-Multi theme-adb tool-jUnit
Android Nâng cao-Bài 6-Multi theme-adb tool-jUnitPhuoc Nguyen
 
Android Nâng cao-Bài 9-Debug in Android Application Development
Android Nâng cao-Bài 9-Debug in Android Application Development Android Nâng cao-Bài 9-Debug in Android Application Development
Android Nâng cao-Bài 9-Debug in Android Application Development Phuoc Nguyen
 
Android Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML ParsingAndroid Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML ParsingPhuoc Nguyen
 
Android Nâng cao-Bài 5:Notification Multiresolution Multilanguage
Android Nâng cao-Bài 5:Notification Multiresolution MultilanguageAndroid Nâng cao-Bài 5:Notification Multiresolution Multilanguage
Android Nâng cao-Bài 5:Notification Multiresolution MultilanguagePhuoc Nguyen
 
Android Nâng cao-Bài 4: Content Provider
Android Nâng cao-Bài 4: Content ProviderAndroid Nâng cao-Bài 4: Content Provider
Android Nâng cao-Bài 4: Content ProviderPhuoc Nguyen
 
Android Nâng cao-Bài 3: Broadcast Receiver
Android Nâng cao-Bài 3: Broadcast ReceiverAndroid Nâng cao-Bài 3: Broadcast Receiver
Android Nâng cao-Bài 3: Broadcast ReceiverPhuoc Nguyen
 
Webservice performance testing with SoapUI
Webservice performance testing with SoapUIWebservice performance testing with SoapUI
Webservice performance testing with SoapUIPhuoc Nguyen
 
Web application security test tools
Web application security test toolsWeb application security test tools
Web application security test toolsPhuoc Nguyen
 
A successful project sharing
A successful project sharingA successful project sharing
A successful project sharingPhuoc Nguyen
 
Buồn vui nghề IT (Pros & cons of IT Career)
Buồn vui nghề IT (Pros & cons of IT Career)Buồn vui nghề IT (Pros & cons of IT Career)
Buồn vui nghề IT (Pros & cons of IT Career)Phuoc Nguyen
 

More from Phuoc Nguyen (12)

Lanh dao va TPP
Lanh dao va TPPLanh dao va TPP
Lanh dao va TPP
 
Android location sensor programming
Android location sensor programmingAndroid location sensor programming
Android location sensor programming
 
Android Nâng cao-Bài 6-Multi theme-adb tool-jUnit
Android Nâng cao-Bài 6-Multi theme-adb tool-jUnitAndroid Nâng cao-Bài 6-Multi theme-adb tool-jUnit
Android Nâng cao-Bài 6-Multi theme-adb tool-jUnit
 
Android Nâng cao-Bài 9-Debug in Android Application Development
Android Nâng cao-Bài 9-Debug in Android Application Development Android Nâng cao-Bài 9-Debug in Android Application Development
Android Nâng cao-Bài 9-Debug in Android Application Development
 
Android Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML ParsingAndroid Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML Parsing
 
Android Nâng cao-Bài 5:Notification Multiresolution Multilanguage
Android Nâng cao-Bài 5:Notification Multiresolution MultilanguageAndroid Nâng cao-Bài 5:Notification Multiresolution Multilanguage
Android Nâng cao-Bài 5:Notification Multiresolution Multilanguage
 
Android Nâng cao-Bài 4: Content Provider
Android Nâng cao-Bài 4: Content ProviderAndroid Nâng cao-Bài 4: Content Provider
Android Nâng cao-Bài 4: Content Provider
 
Android Nâng cao-Bài 3: Broadcast Receiver
Android Nâng cao-Bài 3: Broadcast ReceiverAndroid Nâng cao-Bài 3: Broadcast Receiver
Android Nâng cao-Bài 3: Broadcast Receiver
 
Webservice performance testing with SoapUI
Webservice performance testing with SoapUIWebservice performance testing with SoapUI
Webservice performance testing with SoapUI
 
Web application security test tools
Web application security test toolsWeb application security test tools
Web application security test tools
 
A successful project sharing
A successful project sharingA successful project sharing
A successful project sharing
 
Buồn vui nghề IT (Pros & cons of IT Career)
Buồn vui nghề IT (Pros & cons of IT Career)Buồn vui nghề IT (Pros & cons of IT Career)
Buồn vui nghề IT (Pros & cons of IT Career)
 

Hiberbate Framework

  • 1. Hibernate O/R MAPPING TOOL. Trung Tâm Công Nghệ Phần Mềm Tp.Hồ Chí Minh 4/9/04 Kỹ sư Nguyễn Hữu Phước
  • 2. Nội dung trình bày ● Khái quát về Hibernate. ● Sử dụng Hibernate. ● Các công cụ hữu ích khi dùng Hibernate. ● Hibernate vs. JDO. ● Các Persistence Framework khác. ● Tóm tắt. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 3. Giới thiệu về Hibernate ● Vấn đề:Trong lập trình hướng đối tượng, các lập trình viên thao tác trên các đối tượng. Do đó họ thường phải tự mình tạo ra và quản lý một lớp để lưu trữ và khôi phục lại các đối tượng từ cơ sở dữ liệu. ● Hibernate ra đời để giải quyết phần nào vấn đề này. Hibernate cung cấp cho các lập trình viên Java một O/R persistence framework khá mạnh và dễ sử dụng. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 4. Kiến trúc tổng quát của Hibernate Chương trình ứng dụng Java Các đối tượng Persistence Hibernate hibernate.properties XML mapping Cơ sở dữ liệu Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 5. Kiến trúc tổng quát của Hibernate Các đối tượng Transient Session Factory Chương trình ứng dụng Java Các đối tượng Persistence Session Cơ sở dữ liệu Nguyễn Hữu Phước Hibernate-O/R mapping tool JBDC JNDI JTA Cấu trúc Runtime của Hibernate theo hướng chương trình ứng dụng quản lý JDBC connection và transaction.
  • 6. Kiến trúc tổng quát của Hibernate Các đối tượng Transient Session Factory Chương trình ứng dụng Java Các đối tượng Persistence Session JBDC JNDI JTA Cơ sở dữ liệu Cấu trúc Runtime của Hibernate theo hướng chương trình ứng dụng không quản lý JDBC connection và transaction và để cho Hibernate lo mọi thứ. Nguyễn Hữu Phước Hibernate-O/R mapping tool Transaction Transaction Factory ConnectionProvide r
  • 7. Các đặc điểm của Hibernate ● Là một công cụ để ánh xạ các đối tượng trong ứng dụng Java với cơ sở dữ liệu quan hệ. ● Không dựa trên một tiêu chuẩn nào cả. ● JMX integration:Hibernate có thể được quản lý thông qua JMX với standard Mbean. Nhưng hầu hết các bản hiện thực J2EE server hiện nay chưa hỗ trợ JMX nên Hibernate có thể sử dụng một số cơ chế khác. ● Hỗ trợ JCA:Hibernate có thể được cấu Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 8. Quá trình phát triển JAVA applications với Hibernate ● Dùng các câu lệnh SQL tạo ra các bảng trong cơ sở dữ liệu để lưu trữ các đối tượng persistence. ● Tạo các Java Bean để đại diện cho đối tượng trong chương trình ứng dụng. ● Tạo ra tập tin ánh xạ để báo cho Hibernate biết thuộc tính nào của Java Bean tương ứng với trường nào trong bảng của CSDL. ● Tạo ra tập tin hibernate.properties để cấu hình JDBC connection. ● Sử dụng Hibernate API. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 9. Simple Association(One-to- ●Định nghĩa: Khi mOộtn lớep) có chứa một tham khảo đến một hiện hữu của lớp kia thông qua khoá chính. ● Kịch bản: Bar Foo.getBar();//returns corressponding Bar instance ● Hibernate mapping: ● Table schema: <class name=”Foo” table=”foo”> .................. <one-to-one name=”bar” class=”Bar”/> </class> Bar id Foo id ● Quan hệ 2 chiều: Quan hệ này có thể 2 chiều Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 10. Simple Reference(Many-to- ●Định nghĩa: GiốngO nhnưe t)rường hợp one-to-one nhưng ở đây không dùng chung khoá chính mà thông qua khoá ngoại. ● Kịch bản: Bar Foo.getBar() // returns corresponding Bar instance ● Hibernate mapping: ● Table schema: <class name="Foo" table="foo"> ... <many-to-one name="bar" class="Bar" column="bar_id"/> </class> Bar id Foo id bar_id ● Quan hệ 2 chiều: Quan hệ này có thể 2 Nguyễnc Hhữuiề Puhước Hibernate-O/R mapping tool
  • 11. Basic Collection(One-to- ●Định nghĩa: Khi Mmộat nlớyp )có chứa một tham khảo đến một tập các hiện hữu của lớp kia. ● Kịch bản: Set Foo.getBars();//returns a collection of Bar instances ● Hibernate mapping: ● Table schema: <class name=”Foo” table=”foo”> ........................... <set role=”bars” table=”bar”> <key column=”foo_id”/> <one-to-many class=”Bar”/> </set> </class> Foo id Bar id foo_id ● Quan hệ 2 chiều: Quan hệ này có thể 2 chiều <class name=”Foo” table=”foo”> .................. <many-to-one name=”foo” class=”Foo” /> </class> Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 12. Collection(Many-to-Many) ● Định nghĩa: Khi một hiện hữu lớp A có chứa một tham khảo đến một tập các hiện hữu của lớp B và B cũng có thể có nhiều A .(A,B là lớp first-rank). ● Kịch bản: Set Foo.getBars();//returns a collection of Bar instances ● Hibernate mapping: ● Table Foo schema: Bar foo_ba id id foo_idr bar_id ● Quan hệ 2 chiều: <class name=”Foo” table=”foo”> ........................... <set role=”bars” table=”foo_bar”> <key column=”foo_id”/> <many-to-many column=”bar_id” class=” Bar”/> </set> </class> <class name=”Foo” table=”foo”> .................. <set role="foos" table="foo_bar"> <key column="bar_id"/> <many-to-many column="foo_id" class="Foo"/> </set> </class> NguyễQn uHaữun hệ này có Hthibểer n2at ec-Oh/iRề muapping tool
  • 13. Collection(Raw Data) ● Định nghĩa: Khi một hiện hữu lớp A có chứa một tham khảo đến một tập các hiện hữu của lớp B.A là first-rank và B là second-rank. ● Kịch bản: Set Foo.getPeople();//returns a collection of String instances ● Hibernate mapping: ● Table schema: <class name=”Foo” table=”foo”> ........................... <set role=”people” table=”Person”> <key column=”foo_id”/> <element column=”name” type=”string”/> </set> </class> Foo id Perso foo_idn nam e ● Quan hệ 2 chiều: Không có quan hệ hai Nguyễn Hcữhu iều. Hibernate-O/R mapping tool
  • 14. Sorted Collections ● Hibernate hỗ trợ 2 bản hiện thực cho java. util.Collections là java.util.SortedMap va java. util.SortedSet ● Thuộc tính sort có thể là unsorted,natural hay tên của class hiện thực java.util. Comparator. <set name="aliases" table="person_aliases" sort="natural"> <key column="person"/> <element column="name" type="string"/> </set> <map name="holidays" sort="my.custom.HolidayComparator" lazy="true"> <key column="year_id"/> <index column="hol_name" type="string"/> <element column="hol_date type="date"/> </map> Sorted collections giống như java.util. TreeSet hay java. util.TreeMap Nguyễn Hữu Hibernate-O/R mapping tool
  • 15. Sorted Collections ● Có thể sử dụng thuộc tính order-by của các phép ánh xạ set,bag,map để bảo CSDL tự động sắp xếp các phần tử của một tập hợp. ● Việc sắp xếp xảy ra khi truy vấn chứ không phải trong bộ nhớ. ● Sorted association có thể dùng filter() <set name="aliases" table="person_aliases" order-by="name asc" > <key column="person"/> <element column="name" type="string"/> </set> <map name="holidays" order-by="hol_date, hol_name" lazy="true" > <key column="year_id"/> <index column="hol_name" type="string"/> <element column="hol_date type="date"/> </map> Lưu ý:Thuộc tính order-by là của SQL chứ không phải của HQL Nguyễn Hữu Hibernate-O/R mapping tool
  • 16. Top-level Collections ● Định nghĩa: Top-level collections là các tập hợp mà nó nằm bên ngoài tầm vực từng lớp nhưng được sử dụng trong các lớp ở các tập tin ánh xạ. ● Kịch bản: Set Foo.getNames();//returns a collection of String instances ● Hibernate Foo mapping: Perso id person_i id n nam ● Table schema: d ● Quan hệ 2 chiều: <set role="names" table="person"> <key column="id" type="string"> <generator class="uuid.hex"/> </key> <element column="name" type="string"/> </set> <class name="Foo" table="foo"> ... <collection name="names" column="person_id" role="names"/> </class> e Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 17. Map ● Định nghĩa: Map là một danh sách của các cặp tên-giá trị. ● Kịch bản: Map Foo.getAges();//returns a collection of String name-value pairs ● Hibernate mapping: ● Table schema: <class name="Foo" table="foo"> ... <map role="ages"> <key column="id"/> <index column="name" type="string"/> <element column="age" type="string"/> </map> </class> Foo Ages id age id nam e ● Quan hệ 2 chiều: Quan hệ hai chiều không có ý nghĩa đối với map. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 18. Entity Map ● Định nghĩa: Entity map là một map mà khoá của nó là một thực thể chứ không phải là một thuộc tính đơn. ● Kịch bản: Map Foo.getAges();//returns a collection of Person-String instances ● Hibernate mapping: ● Table schema: <class name="Foo" table="foo"> ... <map role="ages"> <key column="id"/> <index-many-to-many column="person_id" class="Person"/> <element column="age" type="string"/> </map> </class> <class name="Person" table="person"> ... <property name="name" column="name" type="string"/> </class> Foo Ages id id person_id age Person id nam e ● Quan hệ 2 chiều: Quan hệ hai chiều không có ý nghĩa đối với entity Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 19. ●Định nghĩa: MộSt usubbcclalasss lsà emsột first-rank class mà nó mở rộng từ một first-rank class khác theo đúng tiêu chuẩn thừa kế trong mô hình hướng đối tượng ● Kịch bản: <class name="Foo" table="foo" discriminator-value="F"> public class Bar extends Foo;//Bar is ... a subclass of Foo <discriminator column="class"/> ● Hibernate mapping: ... <subclass name="subclass.Bar" discriminator-value="B"> ● Table schema: <property name="name" column="name" type="string"/> Foo </subclass> id descriminator name </class> (Lưu ý ở đây có cách hiện thực khác Foo-Bar độc lập) ● Quan hệ 2 chiều:Quan hệ kế thừa là chỉ có một Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 20. Foo id name Joined Subclass ● Định nghĩa: Joined subclass là các subclass mà chúng được ánh xạ thành mỗi bảng một subclass tốt hơn là một bảng cho toàn bộ cây thừa kế. ● Kịch bản: <class name="Foo" table="foo"> public class Bar extends Foo;//Bar is ... a subclass of Foo <property name="name" column="name" type="string" ● Hibernate mapping: <joined-subclass name="subclass.Bar" table="bar"> <key column="foo_id"/> ● Table schema: <property name="age" column="age" type="string"/> Bar </joined-subclass> foo_id age </class> (Lưu ý ở đây có cách hiện thực khác Foo-Bar độc lập) ● Quan hệ 2 chiều:Quan hệ kế thừa là chỉ có một Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 21. Components ● Định nghĩa: Một component là một Java class mà nó chính là một số cột nhất định trong bảng của một class khác. ● Kịch bản: FooSecond Foo.getSecond();// returns enclosed second-rank instance ● Hibernate mapping: ● Table schema: <class name="Foo" table="foo"> ... <component name="second" class="FooSecond"> <property name="firstName"/> <property name="lastName"/> </component> </class> Foo id firstName lastName ● Quan hệ 2 chiều:Chỉ có quan hệ một chiều. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 22. Collections of Components ● Định nghĩa: Tập hợp các component là có thể xảy ra nhất là khi làm việc với một top-level collection phức tạp. ● Kịch bản: Set Foo.getSeconds();// returns a collection of FooSecond instances ● Hibernate mapping: ● Table schema: <set role="seconds"> <key column="id" type="string"> <generator class="uuid.hex"/> </key> <composite-element class="FooSecond"> <property name="firstName"/> <property name="lastName"/> </composite-element> </set> <class name="Foo" table="foo"> ... <collection name="seconds" column="seconds_id" role=" seconds"/> </class> Seconds id firstName lastName Foo id seconds_id ● Quan hệ 2 chiều: NCguhyễỉn cHóữu Pqhuướacn hệ mHộibetr ncahte-iOề/Ru m. apping tool
  • 23. Composite Identifier ● Định nghĩa:Một lớp có composite identifier là lớp mà khoá chính nó bao gồm nhiều cột. ● Kịch bản: Foo có id kiểu Person. Person bao gồm name kiểu String và address kiểu Address. Person Foo.getId();// PK is multi-column mapped ● Hibernate mapping: ● Table schema: <class name="Foo" table="foo"> <composite-id name="id" class="Person"> <key-property name="name" type="string" column="name" /> <key-many-to-one name="address" class="Address" column="addr_id"/> </composite-id> <property name="age" column="age" type="string"/> </class> <class name="Address" table="address"> ... </class> Address id Foo name addr_id age ● Quan hệ 2 chiều: Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 24. Composite Index ● Định nghĩa:Composite Index cung cấp để giải quyết trường hợp khoá của Map có nhiều cột. ● Kịch bản: Foo chứa Map của tuổi.Khóa của Map này có kiểu Person. Person bao gồm name kiểu String và address kiểu Address. Map Foo.getAges();// Foo contains a map of ages, keyed by Person ● Hibernate mapping: ● Table schema: <class name="Foo" table="foo"> ... <map role="ages"> <key column="id"/> <composite-index class="Person"> <key-property name="name" type="string" column="name"/> <key-many-to-one name="address" class="Address" column="addr_id"/> </composite-index> <element column="age" type="string"/> </map> </class> <class name="Address" table="address"> ...</class> Address id Ages name addr_id id age Foo id ● Quan hệ 2 chiều: NQguuyễan Hnữ uh Pệhư 2ớc chiều Hkibherônanteg-O /cR óm anppginhg tĩoaol.
  • 25. Dynabean Component ● Định nghĩa:<dynabean > giống với <component>. Thuận lợi của ánh xạ này là cho phép xác định các thuộc tính thật sự của bean lúc triển khai bằng cách thay đổi tập tin ánh xạ ● Hibernate mapping: <dynabean name="second" dynaclass="Seconds"> <property name="firstName" column="FirstName"/> <property name="lastName" column="Lastname"/> </dynabean> Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 26. Ternary Associations ● Định nghĩa:Ternary association là một mối liên hệ có 3 lớp tham gia. ● Kịch bản: Bar BarSnafu.getBar() // Retrieve Bar from BarSnafu Snafu BarSnafu.getSnafu() // Retrieve Snafu from BarSnafu Set Foo.getBarSnafus() // Retrieve set of BarSnafus from Foo ● Hibernate mapping: ● Table schema: <class name="Foo" table="foo"> ... <set role="barsnafus" table="foo_bar_snafu"> <key column="foo_id"/> <composite-element class="BarSnafu"> <many-to-one name="bar" class="Bar" column="bar_id"/> <many-to-one name="snafu" class="Snafu" column="snafu_id" /> </composite-element> </set> </class> ... Bar id Snaf u id Foo_Bar_Snafu foo_id bar_id snafu_id Foo id ● Quan hệ 2 chiều: Quan hệ 2 chiều không có nghĩa. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 27. Heterogeneous Associations ● Hibernate cung cấp các phần tử <many-to-any> và <index-many-to-any> dùng để ánh xạ các heterogenous association. Chúng hoạt động giống như <any> Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 28. Lazy Initialization ● Định nghĩa:Các tập hợp (collections) có được khởi động kiểu lazy tức là trạng thái của chúng chỉ được cập nhật khi chương trình ứng dụng cần đến. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 29. HQL:Hibernate Query ●Case sesitivity: LKhaônngg uphaâgn ebiệt hoa thường trừ tên lớp và các thuộc tính. ● Mệnh đề from: ○ from pet.Cat: trả về tất cả các đối tượng của pet. Cat. ○ Bí danh: from pet.Cat as cat hay from pet.Cat cat gán bí danh cat cho các đối tượng pet.Cat. ○ Có thể sử dụng nhiều lớp ở mệnh đề from và kết quả trả về là tích Đề các hay cross join. ○ Để phù hợp với qui tắc đặc tên biến trong Java nên Nguyễn Hđữặuc P hbưíớ cdanh bắHti bđeầrnuate b-Oằ/Rn mga kppíi ntgự to tohl ường.
  • 30. HQL:Hibernate Query ●Association andL Jaoinnsg:uage ○ inner join,left outer join,right outer join,full join. ○ Inner join,left outer join,right outer join viết tắt join,left join, right join. ○ fetch join. ● Mệnh đề select: Chọn đối tượng và các thuộc tính nào của đối tượng được trả về trong tập kết quả. ○ Hàm elements: select elements(cat.kittens) from cat.Cat cat trả về tất cả các kitten của cat. ○ Câu truy vấn có thể trả về các thuộc tính của bất kỳ kiểu dữ liệu gì như các thuộc tính của kiểu thành phần, các đối Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 31. HQL:Hibernate Query ●Aggregate functLioansn:guage ○ min(..),max(..),avg(..),sum(..),count(*),count(..),count(distinct ..),count(all ..). ○ Từ khoá distinct và all. ○ Các tập hợp có thể là đối số của các hàm trên. ● Polymorphism(Tính đa hình): ○ Có thể đặt tên lớp hay tên interface trong mệnh đề from khi đó kết quả trả về là tất cả các hiện hữu của các lớp persistent mà nó mở rộng lớp này hay hện thực interface này. ○ Ví dụ: Xét câu truy vấn from animal.Cat thì trả về các đối tượng thuộc lớp animal.Cat và cả các đối tượng thuộc lớp Nguyễn Hcoữun Pahnưiớmc al.DomeHsibtiecrnCaatet-O/R mapping tool
  • 32. HQL:Hibernate Query ●Mệnh đề whereL: anguage ○ Hạn chế danh sách các hiện hữu trả về bằng một biểu thức điều kiện ○ Lưu ý “=” dùng cho cả thuộc tính và đối tượng. ○ Thuộc tính đặc biệt id,class. ● Expressions: Parentheses ( ) indicate grouping in, between, is null JDBC IN parameters ? named parameters :name, :start_date, :x1 SQL literals 'foo', 69, '1970-01-01 10:00:01.0' Java public static final constants eg.Color. TABBY mathematical operators +, -, *, / binary comparison operators =, >=, <=, <>, !=, like logical operations and, or, not string concatenation || SQL scalar functions like upper() and lower() Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 33. HQL:Hibernate Query ●Mệnh đề Order LBay:nguage ○ Sắp xếp thứ tự danh sách trả về theo bất kỳ thuộc tính nào của class hay component. ○ Các từ khoá desc,asc ○ Ví dụ from eg.DomesticCat cat order by cat.name asc, cat.weight desc, cat.birthdate ● Mệnh đề Group By: ○ elements,indices ○ Having ○ Lưu ý : group by và order by không chứa biểu thức số học. Aggregative functions đượcphép dùng trong Nguyễn Hmữuệ Pnhhư ớđcề havinHgib evrnàa toe-rOd/Re mr abpypi.ng tool
  • 34. HQL:Hibernate Query ●Subqueries: Language ○ Hỗ trợ subqueries kể cả correlated subqueries. ○ Subqueries phải được đặt trong cặp dấu (). Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 35. Các công cụ ● Hibernate project's tools: ○ Schema Generation:SchemaExport,hdm2ddl ○ Code Generation:CodeGenerator,hdm2java ○ Mapping File Generation:MapGenerator, hdm2class ● Third party tools: ○ Middlegen: Sinh ra tập tin ánh xạ từ cấu trúc của một CSDL có sẵn. ○ AndroMDA:Sinh ra mã nguồn cho các persistent class từ mô hình UMLvà các ký Nguyễn Hữuh Pihệưuớ cXML/XMHibI ecrnủatae- Ori/êR nmgap pmingìn toho.l
  • 36. Schema Generation ● Mục đích: Sinh ra DDL từ tập tin ánh xạ. ● Công cụ:SchemaExport. ● Thực thi: ○ java -cp hibernate_classpaths net.sf.hibernate.tool.hbm2ddl.SchemaExport options mapping_files ○ Ngay cả trong mã nguồn. ○ Dùng Ant để update schema. ● Đặc điểm: ○ Đảm bảo tính toàn vẹn tham khảo(khoá chính, khoá ngoại) cho các thực thể và các bảng tập hợp. ○ Tạo ra các bảng và các sequence, index cho các khoá. ● Customize Schema: ○ length,not-null,sql-type,unique,index,unique-key. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 37. Code Generation ● Mục đích: Sinh ra bộ khung của bản hiện thực các lớp từ tập tin ánh xạ. ● Công cụ:CodeGenerator. ● Thực thi: ○ java -cp hibernate_classpaths net.sf.hibernate.tool.hbm2java.CodeGenerator options mapping_files ● Tập tin config. ● Meta tag:Dùng để cung cấp thêm thông tin cho .hbm.xml và hbm2java ● Basic finder generator: ○ Trường nào cần sinh finder.Dùng meta tag trong property tag. Nguyễn ○HTữuạ oP htậưpớ ctin config cHhiob ehrbnmate2-jOav/Ra mvàa pdpùinngg t–ocool nfig.
  • 38. Mapping File Generation ● Mục đích: Sinh ra bộ khung tập tin ánh xạ từ các lớp persistent đã được biên dịch. ● Công cụ:MapGenerator. ● Thực thi: ○ java -cp hibernate_and_your_class_classpaths net.sf.hibernate.tool.class2hbm.MapGenerator optionsand classnames ● Không thể sinh ra tập tin ánh xạ đầy đủ mà không cần thêm thông tin từ người sử dụng. ● Loại bỏ các class không phải là Hibernate persistable. ● Các luật để xác định kiểu ở CSDL cho một Nguyễnth Huữuộ Pchư ớtícnh Hibernate-O/R mapping tool
  • 39. Hibernate Persistable Class ● Không phải là một kiểu định nghĩa trước. ● Không phải là một array. ● Không phải là một interface. ● Không phải là một lớp lồng bên trong một lớp khác. ● Phải có phương thức khởi tạo(constructor) mặc định tức là phương thức khởi tạo không có tham số hình thức. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 40. Xác định kiểu CSDL cho thuộc ●Hibernate.basic()-->t ímnộht cột có kiểu tương ứng. ● net.sf.hibernate.tye.Type và PersistentEnum-- > Một cột trong DB. ● Kiểu dãy (array) thì Hibernate array được sử dụng. ● Kểu java.util.List, java.util.Map, java.util.Se các --> Kiểu tương ứng của Hibernate. MapGenerator không xử lý bên trong. ● Là lớp bất kỳ-->Có superclass, many-to-one được sử dụng, thuộc tính của nó là Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 41. IMPROVING PERFORMANCE ● Proxies for lazy initialization ● Xử lý mức cache. ● Quản lý session cache. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 42. Xử lý mức Cache ● Hibernate sử dụng Apache Turine JCS cho factory-level caching. ● Mapping: Sử dụng <jcs-cache> <jcs-cache usage="read-write|nonstrict-read-write|read-only"/> ● read-only cache: Nếu chương trình chỉ đọc mà không thay đổi các đối tượng trên cache. ● read-write cache: Chương trình thỉnh thoảng cập nhật thông tin. ● nonstrict-read-write cache: Chương trình cần cập nhật dữ liệu và việc cô lập phiên làm việc không Nguyễnc Hầữnu Pđhặướt cra. Hibernate-O/R mapping tool
  • 43. Quản lý Session Cache ● Một đối tượng được cache ở session cache khi: ○ Truyền một đối tượng cho save(),update(),saveOrUpdate() ○ Truy xuất một đối tượng thông qua load(),find(),filter(),iterate(). ● Khi flush() được gọi thì trạng thái của đối tượng sẽ đồng bộ với CSDL. ● Quản lý session cache: ○ Phương thức evict(): xoá đối tượng hay tập đối tượng khỏi session cache. ○ Session.contains(): Một đối tượng có nằm trong session cache không. ○ JVM-level JCS cache trong SessionFactory. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 44. Thao tác trên đối tượng ● Khởi động(Initialization) ● Tạo/nạp các đối tượng(Creating/loading) ● Cập nhật/Xoá các đối tượng (Updating/Deleting) ● Cập nhật các đối tượng của session khác. ● Lọc kết quả truy vấn. Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 45. Khởi động //Loading the configuration // Looks for mapping files in same classpath location Configuration cfg = new Configuration(). addClass( eg. Vertex. class ). addClass( eg. Edge. class); // This binds you to a database configuration SessionFactory sessions = cfg. buildSessionFactory (); // obtain a JDBC connection and instantiate a new Session Session sess = sessions. openSession (); // start a new transaction (optional) Transaction tx = sess. beginTransaction(); Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 46. Tạo/nạp các đối tượng ● Tạo đối tượng: ○ Customer cuss= new Customer(); ○ ..... ○ Long id=(Long)sess.save(cuss); ● Nạp đối tượng: ○ Customer cuss = (Customer)sess.load(Customer. class,id); ○ Set cusses=sess.find(...); Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 47. Cập nhật/Xoá các đối tượng ● Cập nhật đối tượng: ○ Customer cuss=(Customer)sess.load(Customer. class,id); ○ cuss.set(..); ○ sess.flush(); ● Xoá đối tượng: ○ sess.delete(cuss); ○ sess.delete(Câu HQL); Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 48. hibernate.properties hibernate.connection.username SYSDBA hibernate.connection.password masterkey hibernate.connection.url jdbc:firebirdsql:localhost: /example/a.gdb hibernate.connection.driver_class org.firebirdsql.jdbc. FBDriver hibernate.dialect net.sf.hibernate.dialect. InterbaseDialect Nguyễn Hữu Phước Hibernate-O/R mapping tool
  • 49. Hibernate vs. JDO Hibernate ● Chỉ một nhà cung cấp. ● Mã nguồn mở. ● HQL tiện dụng. ● Sử dụng quá trình build chuẩn JDO ● Tuân thủ chuẩn JCP ● Phần mềm thương mại (có một số là dự án mã nguồn mở Speedo nhưng còn giai đoạn đầu) ● Chỉnh sửa các tập tin class(Thêm một bước khi biên dịch) ● Hỗ trợ cả các lưu trữ không là CSDL quan hệ Nguyễn Hữu Phước Hibernate-O/R mapping tool