1. Trang chủ
  2. » Công Nghệ Thông Tin

Hibernate tutorials

295 773 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Cấu trúc

  • 1. HQL Select Query Example

  • 2. HQL Update Query Example

  • 3. HQL Delete Query Example

  • 4. HQL Insert Query Example

  • Hibernate Criteria examples

    • Example in HQL and Criteria

      • 1. HQL example

      • 2. Criteria example

    • Criteria API

      • 1. Criteria basic query

      • 2. Criteria ordering query

      • 3. Criteria restrictions query

        • Restrictions.eq

        • Restrictions.lt, le, gt, ge

        • Restrictions.like

        • Restrictions.between

        • Restrictions.isNull, isNotNull

      • 3. Criteria paging the result

    • Why not Criteria !?

      • 1. Performance issue

      • 1. Maintainece issue

    • Conclusion

  • Hibernate Tutorial

    • Hibernate Quick Start

    • Hibernate Association (Table Relationship)

    • Hibernate / JBoss Tools + Eclipse IDE

    • Hibernate Logging

    • Hibernate Connection Pool

    • Hibernate Cascade

    • Hibernate Query Language (HQL)

    • Hibernate Criteria

    • Hibernate Native SQL

    • Hibernate Named Query

    • Hibernate Transaction

    • Hibernate Advance Technique

    • Hibernate Performance

    • Integrate Hibernate with Other Frameworks

    • Hibernate FAQ

    • Hibernate Common Errors

    • Off Topic

    • Hibernate References

  • Maven 2 + Hibernate 3.2 + MySQL Example (XML Mapping)

    • 1. Table Creation

    • 2. Generate project structure with Maven

    • 3. Convert to Eclipse project

    • 4. Import converted project into Eclipse IDE

    • 5. Create a resources folder

    • 6. Review project structure

    • 7. Add Hibernate and MySQL dependency

    • 8. Create Hibernate Mapping file + Model class

    • 9. Create Hibernate Configuration file

    • 10. Create Hibernate Utility class

    • 11. Review project structure again

    • 12. Code it to save the record

    • 13. Run it and see output

    • Reference

  • Maven 2 + Hibernate 3.2 + MySQL Example (Annotation)

    • 1. Create project infrastructure

    • 2. Add JBoss repository

    • 3. Add Hibernate annotation dependency

    • 4. Update project classpath

    • 5. Update HibernateUtil.java

    • 6. Update Model class

      • Stock.java

    • 7. Delete existing Hibernate XML mapping file

    • 8. Update Hibernate configuration file

    • 9. Review project structure

    • 10. Run it and see output

  • Maven 3 + Hibernate 3.6 + Oracle 11g Example (XML Mapping)

    • 1. Table Creation

    • 2. Create Project with Maven

    • 3. Maven to Eclipse IDE

    • 4. Add Hibernate and Oracle Dependency

    • 5. Hibernate Mapping file (hbm) + Model

    • 6. Hibernate Configuration File

    • 7. Hibernate Utility

    • 8. Review Final Project Structure

    • 9. Hibernate Coding

    • 10. Run It

    • Reference

  • Maven 3 + Hibernate 3.6 + Oracle 11g Example (Annotation)

    • 1. pom.xml

    • 2. Delete Hibernate Mapping file (hbm)

    • 3. Update Model

    • 4. Update Hibernate Configuration File

    • 5. Hibernate Utility

    • 6. Review Final Project Structure

    • 7. Run It

    • Reference

  • Hibernate – One-to-One example (XML Mapping)

    • Project Structure

    • Project Dependency

    • 1. “One-to-one” table relationship

    • 2. Hibernate Model Class

    • 3. Hibernate XML Mapping

    • 4. Hibernate Configuration File

    • 5. Run It

    • Reference

  • Hibernate – One-to-One example (Annotation)

    • Project Structure

    • 1. “One-to-one” table relationship

    • 2. Hibernate Model Class

    • 3. Hibernate Configuration File

    • 4. Run It

    • Reference

  • Hibernate – One-to-Many example (XML Mapping)

    • Project Structure

    • Project Dependency

    • 1. “One-to-many” example

    • 2. Hibernate Model Class

    • 3. Hibernate XML Mapping

    • 4. Hibernate Configuration File

    • 5. Run It

    • Reference

  • Hibernate – One-to-Many example (Annotation)

    • Project Structure

    • 1. “One-to-many” table relationship

    • 2. Hibernate Model Class

    • 3. Hibernate Configuration File

    • 4. Run It

    • Reference

  • Hibernate – Many-to-Many example (XML Mapping)

    • Project Structure

    • Project Dependency

    • 1. “Many-to-many” example

    • 2. Hibernate Model Class

    • 3. Hibernate XML Mapping

    • 4. Hibernate Configuration File

    • 5. Run It

    • Reference

  • Hibernate – Many-to-Many example (Annotation)

    • Project Structure

    • 1. “Many-to-many” table relationship

    • 2. Hibernate Model Class

    • 3. Hibernate Configuration File

    • 4. Run It

    • Reference

  • Hibernate – Many-to-Many example – join table + extra column (Annotation)

    • 1. Many-to-many table + extra columns in join table

    • 2. Project Structure

    • 3. Hibernate / JPA Annotation

    • 4. Run it – Case 1

    • 5. Run it – Case 2

    • Reference

  • inverse = “true” example and explanation

    • What is “inverse” ?

    • “inverse”, should change to “relationship owner”?

      • 1. One to many Relationship

      • 2. Hibernate Implementation

      • 3. inverse = true / false

      • 4. inverse=”false” Example

      • 5. inverse=”true” Example

      • Conclusion

      • Reference

  • How to configure the C3P0 connection pool in Hibernate

    • 1. Get hibernate-c3p0.jar

    • 2. Configure c3p0 propertise

    • Run it, output

    • Reference

  • How to configure DBCP connection pool in Hibernate

    • 1. Get DBCP jars

    • 2. DBCPConnectionProvider

    • 3. Configure DBCP in hibernate.cfg.xml

    • 4. Run it, output

    • Reference

  • Values of cascade:

  • Hibernate – Cascade example (save, update, delete and delete-orphan)

    • Cascade save / update example

      • 1. No save-update cascade

      • 2. With save-update cascade

    • Cascade delete example

      • 1. No delete cascade

      • 2. With delete cascade

    • Cascade delete-orphan example

      • 1. No delete-orphan cascade

      • 2. With delete-orphan cascade

    • How to enable cascade ?

      • 1. XML mapping file

      • 2. Annotation

    • inverse vs cascade

    • Conclusion

  • Different between cascade and inverse

    • Cascade vs inverse

      • 1. inverse

        • Example

      • 2. cascade

        • Example

    • Conclusion

    • Reference

  • Cascade – JPA & Hibernate annotation common mistake

    • Mistake

    • Explanation

    • Solution

    • Conclusion

  • Hibernate Query examples (HQL)

    • 1. HQL Select Query Example

    • 2. HQL Update Query Example

    • 3. HQL Delete Query Example

    • 4. HQL Insert Query Example

    • Reference

  • Hibernate parameter binding examples

    • Hibernate parameter binding

      • 1. Named parameters

        • Example 1 – setParameter

        • Example 2 – setString

        • Example 3 – setProperties

      • 2. Positional parameters

    • Conclusion

  • Hibernate Criteria examples

    • Example in HQL and Criteria

      • 1. HQL example

      • 2. Criteria example

    • Criteria API

      • 1. Criteria basic query

      • 2. Criteria ordering query

      • 3. Criteria restrictions query

        • Restrictions.eq

        • Restrictions.lt, le, gt, ge

        • Restrictions.like

        • Restrictions.between

        • Restrictions.isNull, isNotNull

      • 3. Criteria paging the result

    • Why not Criteria !?

      • 1. Performance issue

      • 1. Maintainece issue

    • Conclusion

  • Hibernate native SQL queries examples

    • Native SQL queries example

    • Hibernate’s generated SQL statement is slow !?

    • Conclusion

  • Hibernate named query examples

    • How to declare named query

      • 1. XML mapping file

      • 2. Annotation

    • Call a named query

      • Conclusion

  • Hibernate Transaction handle example

  • Cascade – JPA & Hibernate annotation common mistake

    • Mistake

    • Explanation

    • Solution

    • Conclusion

Nội dung

HIBERNATE Any relationship type in sql . Quan hệ 1- 1: Quan hệ một-một là quan hệ giữa hai bảng mà được thiết lập khi trường quan hệ đều là khóa chính ở cả hai bảng. Mỗi bản ghi trong bảng A chỉ có thể có một bản ghi phù hợp trong bảng B. Quan hệ 1 - n: Quan hệ một – nhiều là quan hệ giữa hai bảng mà khóa chính trong một bảng có thể được sao chép nhiều lần trong bảng khác hoặc có thể hiểu là một bản ghi trong bảng A chỉ có thể có nhiều bản ghi phù hợp trong bảng B, nhưng một bản ghi trong bảng B chỉ có một bản ghi phù hợp trong bảng A. Quan hệ n - n: Riêng đối với kiểu quan hệ này thì hơi đặc biệt 1 tí. Khi gặp phải kiểu quan hệ này thì bạn sẽ phải có 1 bảng trung gian để có thể liên kết 2 bảng đó lại với nhau thông qua KHÓA CHÍNH. Và khi đó, bảng trung gian sẽ trở thành mối quan hệ 1 -1 đối với 2 bảng chính. Some query is inportant .  Same as limit keyword in mysql. select top 10* from CUS where CUSTOMER_ID in (select top((select COUNT(CUSTOMER_ID) from CUS)-10) CUSTOMER_ID from CUS order by CUSTOMER_ID desc) order by CUSTOMER_ID asc Result: Introduction JDBC . Connect to MySQL :Import mysql-connector-java-5.1.6.jar package org.connect; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class TestConnectMySQL { private Connection conn=null; public Connection getMyConnect(){ String url="jdbc:mysql://localhost:3306/nhom_mua"; String serverName="root"; String password="123456"; try { Class.forName("com.mysql.jdbc.Driver"); conn=(Connection) DriverManager.getConnection(url,serverName, password); return conn; } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args){ TestConnectMySQL test=new TestConnectMySQL(); try { Statement st=test.getMyConnect().createStatement(); ResultSet rs=st.executeQuery("select * from users"); while(rs.next()){ System.out.println(rs.getString(1)+" "+rs.getString(2)); } System.out.println("OK"); } catch (Exception e) { e.printStackTrace(); } } } Result: 1 Thao 2 Tuan 3 abc OK Connect to SQLServer :Import sqldbc4.jar package org.connect; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestConnectSQLServer { private Connection conn; public Connection getMyConnect(){ try{ String user="sa"; String password="123456"; String url="jdbc:sqlserver://QUANG_THAO\\SQLEXPRESS:1433;database=nhom_mua"; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); conn=DriverManager.getConnection(url, user, password); return conn; }catch(Exception e){ e.printStackTrace(); return null; } } public static void main(String[] args){ TestConnectSQLServer test=new TestConnectSQLServer(); try { Statement statement=test.getMyConnect().createStatement(); ResultSet rs=statement.executeQuery("select * from Users"); while(rs.next()){ System.out.println(rs.getString(1)+" " +rs.getString(2)); } } catch (SQLException e) { e.printStackTrace(); } if(test.getMyConnect()==null ){ System.out.println("Failed"); }else{ System.out.println("OK"); } } } Result : 1 Thao 2 Tuan 3 Tu 4 Hung OK Connect to Oracle:Import ojdbc6.jar 1.Introduction of hibernate. http://sangnew.blogspot.com/p/hibernate.html 2.Writing a hibernate application. Sau đây là một ví dụ ta có thể tạo một bảng thông qua một object trong hibernate và thực hiện một vài xử lý đối với CSDL. Ví dụ 1: Class UsersDetails : package org.koushik.javabrains.dto; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class UsersDetails { @Id private int userId; private String userName; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } Class HibernateTest: package org.koushik.hibernate; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.classic.Session; import org.koushik.javabrains.dto.UsersDetails; public class HibernateTest { public static void main(String[] args){ UsersDetails user=new UsersDetails(); user.setUserId(5); user.setUserName("First User"); SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory(); //Từ file cấu hình hibernate.cfg.xml xây dựng thành một SessionFactory rồi gán vào biến sessionFactory. Session session=sessionFactory.openSession();//Mở session(mở phiên giao dịch) với những cấu hình được tạo trong file hibernate.cfg.xml rồi gán cho biến session session.beginTransaction();//Bắt đầu giao dịch session.save(user);//Lưu thực thể user vào session session.getTransaction().commit();//Chuyển đối thực thể vào database } } hibernate.cfg.xml (default) <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration- 3.0.dtd"> <hibernate-configuration> <session-factory> <! Database connection settings > <property name="connection.driver_class">java.sql.DriverManager</property> <property name="connection.url">jdbc:sqlserver://QUANG_THAO:1433;database=CUSTOM ER</property> <property name="connection.username">sa</property> <property name="connection.password">quangthao</property> <! JDBC connection pool (use the built-in) > <property name="connection.pool_size">1</property> //Số lượng conect <! SQL dialect > <property name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property> <! Disable the second-level cache > <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</prope rty> <! Echo all executed SQL to stdout > <property name="show_sql">true</property> <! Drop and re-create the database schema on startup > <property name="hbm2ddl.auto">create</property> <! Names the annotated entity class > <mapping class="org.koushik.javabrains.dto.UsersDetails"/> </session-factory> </hibernate-configuration> Kết quả : SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Hibernate: insert into UsersDetails (userName, userId) values (?, ?) Bên cạnh đó,trong database CUSTOMER nếu bảng UsersDetails chưa có thì nó sẽ được thêm một bảng mới có tên là UsersDetails với 2 trường là userId và userName .Được chèn thêm một bản ghi là (5,”First User”) . Ví dụ 2: trong ví dụ 1 ta thấy khi thực hiện insert một bản ghi thì mọi dữ liệu trong bảng sẽ bị xóa và tạo dữ liệu mới được thêm vào,đó là do : <! Drop and re-create the database schema on startup > <property name="hbm2ddl.auto">create</property> Trong file hibernate.cfg.xml Ta có thể thay đổi điều đó bằng cách thay từ khóa create thành update . Ví dụ 3 :Ta cũng có thể thay đổi tên cột bằng cách thêm @Column(name="UserName") Vào trước dòng khai báo biến. Example : package org.koushik.javabrains.dto; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity(name="Users_Details") thay đổi tên bảng(tên thực thể) public class UsersDetails { @Id private int userId; @Column(name="User_Name") private String userName; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } Để thay đổi tên của cột được đặt làm id ta làm như sau : package org.koushik.javabrains.dto; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity(name="Users_Details") public class UsersDetails { @Id @Column(name="User_Id") private int userId; @Column(name="UserName") private String userName; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } Ví dụ 4:Ta cũng có thể thay đổi tên bảng bằng cách sau: package org.koushik.javabrains.dto; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="Users_Details") public class UsersDetails { @Id @Column(name="User_Id") private int userId; @Column(name="UserName") private String userName; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } 3.More annotation. Ví dụ:Thêm nhiều column cho bảng . Class HibernateTest: package org.koushik.hibernate; import java.util.Date; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; [...]... description; } public void setDescription(String description) { this.description = description; } } hibernate. cfg.xml java.sql.DriverManager... session.save(user); } session.save(user2); session.getTransaction().commit(); session.close(); } hibernate. cfg.xml java.sql.DriverManager... session.save(user); session.save(user2); session.getTransaction().commit(); session.close(); } } hibernate. cfg.xml java.sql.DriverManager... session.beginTransaction(); } session.save(user); session.getTransaction().commit(); session.close(); } hibernate. cfg.xml java.sql.DriverManager... public void setUserName(String userName) { this.userName = userName; } } Class HibernateTest: package org.koushik .hibernate; import java.util.Date; import import import import org .hibernate. SessionFactory; org .hibernate. cfg.Configuration; org .hibernate. classic.Session; org.koushik.javabrains.dto.UsersDetails; public class HibernateTest { public static void main(String[] args){ UsersDetails user=new... setDescription(String description) { this.description = description; } } Class HibernateTest : package org.koushik .hibernate; import java.util.Date; import import import import org .hibernate. SessionFactory; org .hibernate. cfg.Configuration; org .hibernate. classic.Session; org.koushik.javabrains.dto.UsersDetails; public class HibernateTest { public static void main(String[] args){ UsersDetails user=new... setAddress(Address address) { this.address = address; } } Class HibernateTest: package org.koushik .hibernate; import java.util.Date; import import import import import org .hibernate. SessionFactory; org .hibernate. cfg.Configuration; org .hibernate. classic.Session; org.koushik.javabrains.dto.Address; org.koushik.javabrains.dto.UsersDetails; public class HibernateTest { public static void main(String[] args){ UsersDetails... setDescription(String description) { this.description = description; } } Class HibernateTest: package org.koushik .hibernate; import java.util.Date; import import import import org .hibernate. SessionFactory; org .hibernate. cfg.Configuration; org .hibernate. classic.Session; org.koushik.javabrains.dto.UsersDetails; public class HibernateTest { public static void main(String[] args){ UsersDetails user=new... setPinCode(String pinCode) { this.pinCode = pinCode; } } Class HibernateTest: package org.koushik .hibernate; import java.util.Date; import import import import import org .hibernate. SessionFactory; org .hibernate. cfg.Configuration; org .hibernate. classic.Session; org.koushik.javabrains.dto.Address; org.koushik.javabrains.dto.UsersDetails; public class HibernateTest { public static void main(String[] args){ UsersDetails... setDescription(String description) { this.description = description; } } Class HibernateTest: package org.koushik .hibernate; import java.util.Date; import import import import org .hibernate. SessionFactory; org .hibernate. cfg.Configuration; org .hibernate. classic.Session; org.koushik.javabrains.dto.UsersDetails; public class HibernateTest { public static void main(String[] args){ UsersDetails user=new . { this.userName = userName; } } Class HibernateTest: package org.koushik .hibernate; import org .hibernate. SessionFactory; import org .hibernate. cfg.Configuration; import org .hibernate. classic.Session; import. cho bảng . Class HibernateTest: package org.koushik .hibernate; import java.util.Date; import org .hibernate. SessionFactory; import org .hibernate. cfg.Configuration; import org .hibernate. classic.Session; import. description; } } Class HibernateTest : package org.koushik .hibernate; import java.util.Date; import org .hibernate. SessionFactory; import org .hibernate. cfg.Configuration; import org .hibernate. classic.Session; import

Ngày đăng: 06/05/2014, 13:54

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN

w