Bài giảng Phát triển Web với Java EE - Bài 7: Hibernate Mapping

Lấy thông tin học sinh

 Nguyên nhân lỗi:

• Cơ chế Lazy Initialization đang được bật (= true)

Truy vấn đối tượng HocSinh sẽ không kèm theo truy

vấn đối tượng Lop. (chỉ có thể truy vấn được mã lớp

mà không truy vấn được tên lớp).

 Truy vấn đối tượng cha sẽ không kèm theo truy vấn

đối tượng con.

12Lazy Initialization & fetch

 Trong Hibernate, Lazy Initialization giúp

• Tránh các câu truy vấn cơ sở dữ liệu không cần

thiết

• Gia tăng hiệu suất thực thi

• Lazy mặc định có giá trị là true

pdf 73 trang kimcuc 10120
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Phát triển Web với Java EE - Bài 7: Hibernate Mapping", để tải tài liệu gốc về máy hãy click vào nút Download ở trên

Tóm tắt nội dung tài liệu: Bài giảng Phát triển Web với Java EE - Bài 7: Hibernate Mapping

Bài giảng Phát triển Web với Java EE - Bài 7: Hibernate Mapping
Bài 7: Hibernate Mapping 
Nôi dung bài học 
 Many - to - One 
 One to One 
 One to Many 
 Many to Many 
2 
Mapping Many To One 
• Một học sinh thuộc về 1 lớp. 
• Một lớp có nhiều học sinh. 
3 
Học sinh 
- MaHocSinh: Int 
- TenHocSinh: Str 
- MaLop: Str 
Lớp 
- MaLop: String 
- TenLop: String 
1 * 
Many to one: LopPOJO 
4 
1 
2 
3 
4 
5 
6 
package pojo; 
public class LopPojo implements java.io.Serializable { 
 private String maLop; 
 private String tenLop; 
} 
//Các phương thức set, get, constructor 
Many to one: Lop.hbm.xml 
5 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
""> 
. 
Many to one: HocSinhPOJO 
6 
1 
2 
3 
4 
5 
6 
package pojo; 
public class HocSinhPojo implements java.io.Serializable { 
 private int maHocSinh; 
 private String tenHocSinh; 
 private LopPojo lop; 
 //Các phương thức get, set, constructor. 
} 
Many to one: HocSinh.hbm.xml 
7 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
 <property name="tenHocSinh" column="TenHocSinh" 
type="string"/> 
<many-to-one 
 name="lop” tên thuộc tính cần mapping 
 class="pojo.LopPojo" > Tên lớp cần mapping tới 
 Tên cột trong table HocSinh 
Lấy thông tin học sinh 
8 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
public class Main { 
 public static void main(String[] args) { 
 HocSinhPojo hs = null; 
 SessionFactory ssFac = MyHibernateUtil.getSessionFactory(); 
 Session ss = ssFac.openSession(); 
 ss.getTransaction().begin(); 
 try { 
 hs = (HocSinhPojo)ss.get(HocSinhPojo.class, 1); 
 System.out.println("Tên học sinh: " + hs.getTenHocSinh()); 
 System.out.println("Mã lớp: " + hs.getLop().getMaLop()); 
 System.out.println("Tên lớp: " + hs.getLop().getTenLop()); 
 } catch (HibernateException ex ) { 
 System.out.println(ex.getMessage()); 
 } 
 finally 
 { 
 ss.close(); 
 } 
 } 
} 
Thành công 
Lấy thông tin học sinh khi còn mở Session 
Lấy thông tin học sinh 
9 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
public class Main { 
 public static void main(String[] args) { 
 HocSinhPojo hs = null; 
 SessionFactory ssFac = MyHibernateUtil.getSessionFactory(); 
 Session ss = ssFac.openSession(); 
 ss.getTransaction().begin(); 
 try { 
 hs = (HocSinhPojo)ss.get(HocSinhPojo.class, 1); 
 } catch (HibernateException ex ) { 
 System.out.println(ex.getMessage()); 
 } 
 finally 
 { 
 ss.close(); 
 } 
 System.out.println("Tên học sinh: " + hs.getTenHocSinh()); 
 System.out.println("Mã lớp: " + hs.getLop().getMaLop()); 
 System.out.println("Tên lớp: " + hs.getLop().getTenLop()); 
 } 
} 
Lỗi 
Lấy thông tin học sinh sau khi đóng Session 
 chỉ lấy được tên và mã học sinh, không lấy được tên lớp. 
Lấy thông tin học sinh 
10 
Lỗi 
Lấy thông tin học sinh sau khi đóng Session 
 chỉ lấy được tên và mã học sinh, không lấy được tên lớp. 
Lấy thông tin học sinh 
11 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
public class Main { 
 public static void main(String[] args) { 
 HocSinhPojo hs = null; 
 SessionFactory ssFac = MyHibernateUtil.getSessionFactory(); 
 Session ss = ssFac.openSession(); 
 ss.getTransaction().begin(); 
 try { 
 hs = (HocSinhPojo)ss.get(HocSinhPojo.class, 1); 
 System.out.println("Tên lớp: " + hs.getLop().getTenLop()); 
 } catch (HibernateException ex ) { 
 System.out.println(ex.getMessage()); 
 } 
 finally 
 { 
 ss.close(); 
 } 
 System.out.println("Tên học sinh: " + hs.getTenHocSinh()); 
 System.out.println("Mã lớp: " + hs.getLop().getMaLop()); 
 } 
} 
Thành công 
Lấy thông tin học sinh 
 Nguyên nhân lỗi: 
• Cơ chế Lazy Initialization đang được bật (= true) 
 Truy vấn đối tượng HocSinh sẽ không kèm theo truy 
vấn đối tượng Lop. (chỉ có thể truy vấn được mã lớp 
mà không truy vấn được tên lớp). 
 Truy vấn đối tượng cha sẽ không kèm theo truy vấn 
đối tượng con. 
12 
Lazy Initialization & fetch 
 Trong Hibernate, Lazy Initialization giúp 
• Tránh các câu truy vấn cơ sở dữ liệu không cần 
thiết 
• Gia tăng hiệu suất thực thi 
• Lazy mặc định có giá trị là true 
13 
Cách 1 
 Sau khi có mã lớp, ta dùng làm lấy thông tin lớp theo 
mã lớp 
14 
LopDAO.layThongTinLop(int maLop); 
Cách 2 – Khai báo lazy = false trong 
Hocsinh.hbm.xml 
15 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
Cơ chế fetch 
 Lazy =“false” truy vấn lớp cha kèm theo truy vấn lớp con. 
• Fetch = “select” sử dụng select để truy vấn lớp con. 
sử dụng 2 câu truy vấn select để truy vấn cả lớp cha và 
con, cách này không hiệu quả vì phải truy xuất tới cơ sở 
dữ liệu 2 lần. 
• Fetch = “join” sử dụng phép kết để gọp truy vấn lớp cha 
và lớp con trong 1 truy vấn. hiệu suất cao hơn, sử 
dụng 1 câu truy vấn. 
16 
Cơ chế fetch – sử dụng select 
17 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
Hocsinh.hbm.xml 
Chú ý: mỗi khi sữa lại file cấu hình xml (cấu hình hibernate, cấu hình mapping,  
Phải clean and built lại project thì thay đổi mới có hiệu lực. 
Cơ chế fetch – sử dụng select 
18 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
Hocsinh.hbm.xml 
Chú ý: mỗi khi sữa lại file cấu hình xml (cấu hình hibernate, cấu hình 
mapping, ) 
Phải clean and built lại project thì thay đổi mới có hiệu lực. 
Cơ chế fetch – sử dụng select 
19 
Bản chất, các câu truy vấn HQL đều được chuyển về SQL, như hình dưới 
có 2 câu select được gọi.  truy xuất CSDL 2 lần 
2 câu truy vấn 
select được 
gọi. 
Cơ chế fetch – sử dụng join 
20 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
Hocsinh.hbm.xml 
Chú ý: mỗi khi sữa lại file cấu hình xml (cấu hình hibernate, cấu hình 
mapping, ) 
Phải clean and built lại project thì thay đổi mới có hiệu lực. 
Cơ chế fetch – sử dụng join 
21 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
public class Main { 
 public static void main(String[] args) { 
 HocSinhPojo hs = null; 
 SessionFactory ssFac = MyHibernateUtil.getSessionFactory(); 
 Session ss = ssFac.openSession(); 
 ss.getTransaction().begin(); 
 try { 
 String hql="select hs 
 from HocSinhPojo hs left join fetch hs.lop 
 where hs.maHocSinh=:maHocSinh"; 
 Query query=ss.createQuery(hql); 
 query.setInteger("maHocSinh", 1); 
 hs = (HocSinhPojo) query.uniqueResult(); 
 } catch (HibernateException ex) { 
 System.out.println(ex.getMessage()); 
 } finally { 
 ss.close(); 
 } 
 System.out.println("Tên họccsinh: " + hs.getTenHocSinh()); 
 System.out.println("Mã danh mục: " + hs.getLop().getMaLop()); 
 System.out.println("Tên danh mục: " + hs.getLop().getTenLop()); 
 } 
} 
Cơ chế fetch – sử dụng join 
22 
Có 1 câu select được gọi, có sử dụng phép Join  truy xuất CSDL 2 lần 
1 câu truy vấn 
select được 
gọi. 
Cascade 
23 
• Save – update 
• Delete 
Cascade – None cascade 
24 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
 <many-to-one name="lop" class="pojo.LopPojo" 
 lazy="false" fetch="join" cascade=“none"> 
Mặc định nếu không khai báo thì cascade=none 
Cascade – không dùng update-save 
25 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
public static void main(String[] args) { 
 HocSinhPojo hs = new HocSinhPojo(15, "Trần Văn Đạt", null); 
 LopPojo lop = new LopPojo("12E", "Lớp 12 chuyên Hóa"); 
 hs.setLop(lop); 
 if(HocSinhDAO.themHocSinh(hs)) 
 { 
 System.out.println("Thêm thành công!"); 
 } 
 else 
 System.out.println("Thêm th?t b?i!"); 
 } 
LỖI 
Lớp 12E không tồn tại trong cơ sở dữ liệu. 
Cascade – sử dụng update-save 
26 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
 <many-to-one name="lop" class="pojo.LopPojo" 
 lazy="false" fetch="join" cascade="save-update"> 
HocSinh.hbm.xml 
Cascade – sử dụng update-save 
27 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
public static void main(String[] args) { 
 HocSinhPojo hs = new HocSinhPojo(15, "Trần Văn Đạt", null); 
 LopPojo lop = new LopPojo("12E", "Lớp 12 chuyên Hóa"); 
 hs.setLop(lop); 
 if(HocSinhDAO.themHocSinh(hs)) 
 { 
 System.out.println("Thêm thành công!"); 
 } 
 else 
 System.out.println("Thêm thất bại!"); 
 } 
THÊM 
THÀNH 
CÔNG 
Cascade – không dùng delete 
28 
1 
2 
3 
4 
5 
6 
7 
8 
public class Main { 
 public static void main(String[] args) { 
 if(LopDAO.xoaLop("12E")) 
 System.out.println("Xóa thành công!"); 
 else 
 System.out.println("Xóa th?t b?i!"); 
 } 
} 
Không thể xóa lớp 12E lỗi tham chiếu khóa ngoại 
LỖI 
Cascade – sử dụng delete 
29 
CHÚ Ý 
Để dùng Cascade trong hibernate phải cho phép sử dụng cascade 
trong CSDL 
Cascade – sử dụng delete 
30 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
 <many-to-one name="lop" class="pojo.LopPojo" 
 lazy="false" fetch="join" cascade="save-update, delete"> 
Cascade – sử dụng delete 
31 
XÓA 
THÀNH 
CÔNG 
1 
2 
3 
4 
5 
6 
7 
8 
public class Main { 
 public static void main(String[] args) { 
 if(LopDAO.xoaLop("12E")) 
 System.out.println("Xóa thành công!"); 
 else 
 System.out.println("Xóa thất bại!"); 
 } 
} 
Mapping One To Many 
• Một học sinh thuộc về 1 lớp. 
• Một lớp có nhiều học sinh. 
32 
Học sinh 
- MaHocSinh: Int 
- TenHocSinh: Str 
- MaLop: Str 
Lớp 
- MaLop: String 
- TenLop: String 
1 * 
LopPOJO 
33 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
package pojo; 
import java.util.HashSet; 
import java.util.Set; 
public class LopPojo implements java.io.Serializable { 
 private String maLop; 
 private String tenLop; 
 private Set danhSachHocSinh = new HashSet(0); 
 // Các phương thức get, set, construction 
} 
Lop.hbm.xml 
34 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
HocSinhPOJO 
35 
1 
2 
3 
4 
5 
6 
package pojo; 
public class HocSinhPojo implements java.io.Serializable { 
 private int maHocSinh; 
 private String tenHocSinh; 
 private LopPojo lop; 
 //Các phương thức get, set, constructor. 
} 
HocSinh.hbm.xml 
36 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
 <property name="tenHocSinh" column="TenHocSinh" 
type="string"/> 
DAO: Lấy thông tin lớp học 
37 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
public static LopPojo layThongTinLop(String maLop) { 
 LopPojo lop = null; 
 SessionFactory ssFac = MyHibernateUtil.getSessionFactory(); 
 Session ss = ssFac.getCurrentSession(); 
 Transaction trans = ss.getTransaction(); 
 trans.begin(); 
 try { 
 lop = (LopPojo)ss.get(LopPojo.class, maLop); 
 trans.commit(); 
 } catch (HibernateException ex ) { 
 System.out.println(ex.getMessage()); 
 } 
 return lop; 
 } 
Lấy thông tin lớp học 
38 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
public class Main { 
 public static void main(String[] args) { 
 LopPojo lop = LopDAO.layThongTinLop("10A"); 
 System.out.println("Mã lớp: " + lop.getMaLop()); 
 System.out.println("Tên lớp: " + lop.getTenLop()); 
 System.out.println("--------------------------------"); 
 Iterator dsHocSinh = 
 lop.getDanhSachHocSinh().iterator(); 
 while(dsHocSinh.hasNext()) 
 { 
 HocSinhPojo hs = dsHocSinh.next(); 
 System.out.println("Mã học sinh: " + hs.getMaHocSinh()); 
 System.out.println("Tên học sinh: " + 
 hs.getTenHocSinh()); 
 System.out.println("_______________________"); 
 } 
 } 
} 
Lấy thông tin lớp học 
39 
Kết quả 
INVERSER 
40 
 Khi tạo mới hay thay đổi thông tin “một lớp học” thì 
có cần phải cập nhật lại “mã lớp” của học sinh hay 
không? 
Inverser - False 
41 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
 <property 
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect 
 <property 
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver 
 <property 
name="hibernate.connection.url">jdbc:mysql://localhost:3306/quanlysach?use
Unicode=true&characterEncoding=UTF-8 
 root 
 password 
 <property 
name="hibernate.current_session_context_class">thread 
 true 
Lưu ý: để xuất câu truy vấn SQL ra console cho tiện việc xem xét như các slide bên dưới 
ta phải thêm true vào file cấu 
hình hibernate.cfg.xml. 
Inverser - False 
42 
Khi tạo mới hay thay đổi thông tin “một lớp học” thì 
có cần phải cập nhật lại “mã lớp” của học sinh hay 
không? • Nếu inverser = false (Mặc định) 
1 
2 
3 
4 
5 
6 
7 
<set name="danhSachHocSinh" lazy="false" fetch="select" 
inverse=“false"> 
Inverser = false đồng nghĩa với LopHoc đóng vai trò chủ đạo trong 
mối quan hệ LopHoc-HocSinh, vì vậy khi tạo mới hay cập nhật 
thông tin một lớp học sẽ phải cập nhật lại mã lớp của học sinh. 
Inverser - FALSE 
43 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
public class Main { 
 public static void main(String[] args) { 
 Session session=MyHibernateUtil.getSessionFactory().getCurrentSession(); 
 session.beginTransaction(); 
 LopPojo lop = new LopPojo("12F", "Lớp 12 chuyên văn"); 
 HocSinhPojo hs = new HocSinhPojo(6, "Mạc Thị Bưởi", lop); 
 lop.getDanhSachHocSinh().add(hs); 
 session.save(lop); 
 session.save(hs); 
 session.getTransaction().commit(); 
 } 
} 
Inverser - TRUE 
44 
Hibernate: 
 insert 
 into 
 lop 
 (TenLop, MaLop) 
 values 
 (?, ?) 
Hibernate: 
 insert 
 into 
 hocsinh 
 (TenHocSinh, MaLop, MaHocSinh) 
 values 
 (?, ?, ?) 
Hibernate: 
 update 
 hocsinh 
 set 
 MaLop=? 
 where 
 MaHocSinh=? 
BUILD SUCCESSFUL (total time: 1 second) 
Có 3 câu truy vấn 
SQL được sử dụng. 
 Có 2 câu insert dữ liệu 
 Có 1 câu update dùng để 
Update 
lại mã lớp của học sinh. 
 Trong trường hợp này câu 
update 
không cần thiết. 
Inverser 
45 
Khi tạo mới hay thay đổi thông tin “một lớp học” thì 
có cần phải cập nhật lại “mã lớp” của học sinh hay 
không? • Nếu inverser = true 
1 
2 
3 
4 
5 
6 
7 
<set name="danhSachHocSinh" lazy="false" fetch="select" 
inverse="true"> 
Inverser = true đồng nghĩa với HocSinh đóng vai trò chủ đạo trong mối quan 
hệ này, vì vậy khi tạo mới hay cập nhật thông tin một lớp học sẽ không cần 
phải cập nhật lại mã lớp của học sinh. 
Inverser - TRUE 
46 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
public class Main { 
 public static void main(String[] args) { 
 Session session=MyHibernateUtil.getSessionFactory().getCurrentSession(); 
 session.beginTransaction(); 
 LopPojo lop = new LopPojo("12F", "Lớp 12 chuyên văn"); 
 HocSinhPojo hs = new HocSinhPojo(6, "Mạc Thị Bưởi", lop); 
 lop.getDanhSachHocSinh().add(hs); 
 session.save(lop); 
 session.save(hs); 
 session.getTransaction().commit(); 
 } 
} 
Inverser - TRUE 
47 
Hibernate: 
 insert 
 into 
 lop 
 (TenLop, MaLop) 
 values 
 (?, ?) 
Hibernate: 
 insert 
 into 
 hocsinh 
 (TenHocSinh, MaLop, MaHocSinh) 
 values 
 (?, ?, ?) 
BUILD SUCCESSFUL (total time: 1 second) 
Chỉ có 2 câu insert 
được sử dụng. 
Bớt được một truy vấn đến CSDL 
 tăng hiệu năng đáng kể. 
Many to many 
 Quan hệ Many – Many: 
• Một sinhvien có thể học nhiều lophoc. 
• Một lophoc có nhiều sinhvien. 
48 
LopHocPOJO & SinhVienPOJO 
49 
1 
2 
3 
4 
5 
6 
public class LopHocPOJO implements java.io.Serializable { 
 private String maLopHoc; 
 private String tenLopHoc; 
 private int soTinChi; 
 private Set dsSinhVien = new HashSet(); 
 //Các phương thức set, get, constructor 
} 
1 
2 
3 
4 
5 
6 
public class SinhVienPOJO implements java.io.Serializable { 
 private String maSinhVien; 
 private String tenSinhVien; 
 private int namSinh; 
 private Set dsLopHoc = new HashSet(); 
 //Các phương thức set, get, constructor 
} 
Mapping: SinhVien.hbm.xml 
50 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
Mapping: LopHoc.hbm.xml 
51 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
SinhVienDAO 
52 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
public static List layDsSinhVien() { 
 List list = null; 
 SessionFactory sf = MyHibernateUtil.getSessionFactory(); 
 Session ss = sf.getCurrentSession(); 
 Transaction trans = ss.beginTransaction(); 
 try { 
 trans.begin(); 
 list = ss.createQuery("from pojo.SinhVienPOJO").list(); 
 trans.commit(); 
 } catch (Exception ex) { 
 System.out.append(ex.getMessage()); 
 } 
 return list; 
 } 
App 
53 
1 
2 
3 
4 
5 
6 
List list = dao.SinhVienDAO.layDsSinhVien(); 
 for (int i = 0; i < list.size(); ++i) { 
 System.out.println(list.get(i).getMaSinhVien() + "-" 
 + list.get(i).getTenSinhVien() + "-" 
 + list.get(i).getNamSinh()); 
 } 
App 
54 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
List list = dao.SinhVienDAO.layDsSinhVien(); 
 for (int i = 0; i < list.size(); ++i) { 
 System.out.println(list.get(i).getMaSinhVien() + "-" 
 + list.get(i).getTenSinhVien() + "-" 
 + list.get(i).getNamSinh()); 
 Iterator dsLop = list.get(i).getDsLopHoc().iterator(); 
 while (dsLop.hasNext()) { 
 LopHocPOJO lh = dsLop.next(); 
 System.out.println(lh.getMaLopHoc() + 
 "-" + lh.getTenLopHoc() + 
 "-" + lh.getSoTinChi()); 
 } 
 } 
??? 
App 
55 
 Cách giải quyết: 
• Điều chỉnh thuộc tính lazy trong file mapping. 
• Mặc định lazy = “true” 
1 
2 
3 
4 
Lazy Initialization & fetch 
 Lazy = “true” truy vấn lớp cha sẽ không kèm theo truy 
vấn lớp con 
 Lazy =“false” truy vấn lớp cha kèm theo truy vấn lớp con. 
• Fetch = “select” sử dụng select để truy vấn lớp con. 
sử dụng 2 câu truy vấn, làm chậm tốc độ. 
• Fetch = “join” sử dụng phép kết để gọp truy vấn lớp cha 
và lớp con trong 1 truy vấn. 
56 
Lazy Initialization & fetch 
 Trong Hibernate, Lazy Initialization giúp 
• Tránh các câu truy vấn cơ sở dữ liệu không cần 
thiết 
• Gia tăng hiệu suất thực thi 
• Lazy mặc định có giá trị là true 
57 
App 
58 
Kết quả sau khi chạy lại đoạn 
code. 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
List list = dao.SinhVienDAO.layDsSinhVien(); 
 for (int i = 0; i < list.size(); ++i) { 
 System.out.println(list.get(i).getMaSinhVien() + "-" 
 + list.get(i).getTenSinhVien() + "-" 
 + list.get(i).getNamSinh()); 
 Iterator dsLop = list.get(i).getDsLopHoc().iterator(); 
 while (dsLop.hasNext()) { 
 LopHocPOJO lh = dsLop.next(); 
 System.out.println(lh.getMaLopHoc() + 
 "-" + lh.getTenLopHoc() + 
 "-" + lh.getSoTinChi()); 
 } 
 } 
SinhVienDAO 
59 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
public static boolean dangKyLop(SinhVienPOJO info) { 
 boolean kq = true; 
 SessionFactory sf = MyHibernateUtil.getSessionFactory(); 
 Session ss = sf.getCurrentSession(); 
 Transaction trans = ss.beginTransaction(); 
 try { 
 trans.begin(); 
 ss.saveOrUpdate(info); 
 trans.commit(); 
 } catch (Exception ex) { 
 kq = false; 
 System.out.append(ex.getMessage()); 
 } 
 return kq; 
 } 
App 
60 
1 
2 
3 
SinhVienPOJO sv = dao.SinhVienDAO.layThongTinSinhVien("SV03"); 
 sv.getDsLopHoc().add(new LopHocPOJO("CTT03", “Java phân tán", 4)); 
 dao.SinhVienDAO.dangKyLop(sv); 
Trong CSDL không tồn 
tại sẵn lophoc có mã 
là CTT03 như lúc 
thêm 
Cascade 
61 
 Cách giải quyết: 
• Điều chỉnh thuộc tính cascade trong file mapping. 
• Cascade có 2 giá trị: save-update / delete 
• Nếu dùng cả 2 giá trị thì cách nhau bằng dấu , 
1 
2 
3 
4 
<set name="dsLopHoc" table="chitietlophoc" lazy="false" fetch="join" 
cascade="save-update"> 
App 
62 
1 
2 
3 
4 
5 
6 
7 
SSinhVienPOJO sv = dao.SinhVienDAO.layThongTinSinhVien("SV03"); 
 sv.getDsLopHoc().add(new LopHocPOJO("CTT03", "Java phân tán", 4)); 
 boolean kq = dao.SinhVienDAO.dangKyLop(sv); 
 if (kq) 
 System.out.println("Thêm thành công"); 
 else 
 System.out.println("Thêm thất bại"); 
One to One 
 Quan hệ One – One: 
• Một sinhvien có duy nhất một cmnd. 
• Một cmnd thuộc về duy nhất một sinhvien. 
63 
SinhVienPOJO & cmndPOJO 
64 
1 
2 
3 
4 
5 
public class SinhVienPOJO implements java.io.Serializable { 
 private String maSinhVien; 
 private cmndPOJO cmnd; 
 //Các phương thức set, get, constructor 
} 
1 
2 
3 
4 
5 
6 
public class cmndPOJO implements java.io.Serializable { 
 private String cmnd; 
 private String hoTen; 
 private SinhVienPOJO sinhVien; 
 //Các phương thức set, get, constructor 
} 
Mapping 
65 
 Mapping mối quan hệ một-một giống như mapping mối 
quan hệ nhiều-một: 
• Nhưng thêm thuộc tính unique=“true” 
 Có thể khai báo sử dụng thuộc tính: 
• Lazy 
• Fetch 
• Cascade 
Mapping: SinhVien.hbm.xml 
66 
1 
2 
3 
4 
5 
6 
7 
8 
9 
 <many-to-one class="pojo.cmndPOJO" name="cmnd" fetch="join" lazy="false" 
cascade="save-update,delete"> 
Mapping: cmnd.hbm.xml 
67 
1 
2 
3 
4 
5 
6 
7 
8 
 <one-to-one name="sinhVien" class="antlr.SinhVienPOJO" property-ref="cmnd" 
cascade="save-update,delete" /> 
SinhVienDAO 
68 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
public static List layDanhSachSinhVien() { 
 List list = null; 
 SessionFactory sf = MyHibernateUtil.getSessionFactory(); 
 Session ss = sf.getCurrentSession(); 
 Transaction trans = ss.getTransaction(); 
 try { 
 trans.begin(); 
 list = ss.createQuery("from pojo.SinhVienPOJO").list(); 
 trans.commit(); 
 }catch (Exception ex) { 
 System.out.println(ex.getMessage()); 
 } 
 return list; 
 } 
App 
69 
1 
2 
3 
4 
5 
6 
7 
8 
9 
List dsSV = dao.SinhVienDAO.layDanhSachSinhVien(); 
 for (int i = 0; i < dsSV.size(); ++i) { 
 SinhVienPOJO sv = dsSV.get(i); 
 cmndPOJO cmnd = sv.getCmnd(); 
 System.out.println("Mã SV: " + sv.getMaSinhVien()); 
 System.out.println("Số CMND: " + cmnd.getCmnd()); 
 System.out.println("Họ tên: " + cmnd.getHoTen()); 
 System.out.println("-----------------------"); 
 } 
SinhVienDAO 
70 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
public static SinhVienPOJO layThongTinSinhVien(String maSinhVien){ 
 SinhVienPOJO sv = null; 
 SessionFactory sf = MyHibernateUtil.getSessionFactory(); 
 Session ss = sf.getCurrentSession(); 
 Transaction trans = ss.getTransaction(); 
 try { 
 trans.begin(); 
 sv = (SinhVienPOJO)ss.get(SinhVienPOJO.class, maSinhVien); 
 trans.commit(); 
 }catch (Exception ex) { 
 System.out.println(ex.getMessage()); 
 } 
 return sv; 
 } 
SinhVienDAO 
71 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
public static boolean themSinhVien(SinhVienPOJO info) { 
 boolean kq = true; 
 if (SinhVienDAO.layThongTinSinhVien(info.getMaSinhVien()) != null) { 
 return false; 
 } 
 SessionFactory sf = MyHibernateUtil.getSessionFactory(); 
 Session ss = sf.getCurrentSession(); 
 Transaction trans = ss.getTransaction(); 
 try { 
 trans.begin(); 
 ss.save(info); 
 trans.commit(); 
 }catch (Exception ex) { 
 trans.rollback(); 
 System.out.println(ex.getMessage()); 
 kq = false; 
 } 
 return kq; 
 } 
App 
72 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
SinhVienPOJO sv = new SinhVienPOJO(); 
 sv.setMaSinhVien("0812462"); 
 cmndPOJO cmnd = new cmndPOJO(); 
 cmnd.setCmnd("444444444"); 
 cmnd.setHoTen("Thái Huy Tân"); 
 sv.setCmnd(cmnd); 
 boolean kq = dao.SinhVienDAO.themSinhVien(sv); 
 if (kq) 
 System.out.println("Thêm thành công"); 
 else 
 System.out.println("Thêm thất bại"); 
XIN CẢM ƠN! 

File đính kèm:

  • pdfbai_giang_phat_trien_web_voi_java_ee_bai_7_hibernate_mapping.pdf