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

Hibernate tutorials

295 773 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Thông tin cơ bản

Tiêu đề Introduction of Hibernate
Trường học Sang News
Chuyên ngành Computer Science
Thể loại Không rõ
Định dạng
Số trang 295
Dung lượng 4,21 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Connect to MySQL :Import mysql-connector-java-5.1.6.jarpublic class TestConnectMySQL { private Connection conn =null; public Connection getMyConnect{ String url= "jdbc:mysql://localhost:

Trang 1

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*

( select top (( select COUNT (CUSTOMER_ID) from CUS)-10) CUSTOMER_ID

from CUS

order by CUSTOMER_ID desc )

order by CUSTOMER_ID asc

Result:

Trang 2

Introduction JDBC

Trang 3

Connect to MySQL :Import mysql-connector-java-5.1.6.jar

public class TestConnectMySQL {

private Connection conn =null;

public Connection getMyConnect(){

String url= "jdbc:mysql://localhost:3306/nhom_mua" ; String serverName= "root" ;

e.printStackTrace();

return null; }

}

public static void main(String[] args){

TestConnectMySQL test=new TestConnectMySQL();

} catch (Exception e) {

e.printStackTrace();

} }

Trang 4

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();

Trang 5

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 :

Trang 6

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;

public class HibernateTest {

public static void main(String[] args){

user.setUserId(5);

user.setUserName("First User");

hibernate.cfg.xml xây dựng thành một SessionFactory rồi gán vào biến sessionFactory.

Trang 7

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

database

}

}

hibernate.cfg.xml (default)

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

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

name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property>

<! Disable the second-level cache >

name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<! Echo all executed SQL to stdout >

<property name="show_sql">true</property>

Trang 8

<! Drop and re-create the database schema on startup >

<property name="hbm2ddl.auto">create</property>

<! Names the annotated entity class >

</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

Trang 9

@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;

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;

}

Trang 10

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;

Trang 11

import org.hibernate.classic.Session;

import org.koushik.javabrains.dto.UsersDetails;

public class HibernateTest {

public static void main(String[] args){

private int userId;

private String userName;

private Date joinedDate;

private String address;

private String description;

public int getUserId() {

return userId;}

public void setUserId(int userId) {

Trang 12

this.userId = userId;

}

public String getUserName() {

return userName;}

public void setUserName(String userName) {

this.userName = userName;

}

public Date getJoinedDate() {

return joinedDate;}

public void setJoinedDate(Date joinedDate) {

this.joinedDate = joinedDate;

}

public String getAddress() {

return address;}

public void setAddress(String address) {

this.address = address;

}

public String getDescription() {

return description;}

public void setDescription(String description) {

this.description = description;

}

}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

Trang 13

<property

name="connection.url">jdbc:sqlserver://QUANG_THAO:1433;database=CUSTOMER</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>

<! SQL dialect >

name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property>

<! Disable the second-level cache >

name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<! 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 >

</hibernate-configuration>

Kết quả :

Trang 14

Ví dụ 2:Ta có thể thêm nhiểu phần tử vào class Entity nhưng nó không đóng vài trò là một column trong bảng đó.

Ta thêm thuộc tính @Transient trước biến đó.

private String userName;

private Date joinedDate;

private String address;

private String description;

public int getUserId() {

return userId;}

public void setUserId(int userId) {

this.userId = userId;

}

public String getUserName() {

return userName;}

public void setUserName(String userName) {

Trang 15

this.userName = userName;

}

public Date getJoinedDate() {

return joinedDate;}

public void setJoinedDate(Date joinedDate) {

this.joinedDate = joinedDate;

}

public String getAddress() {

return address;}

public void setAddress(String address) {

this.address = address;

}

public String getDescription() {

return description;}

public void setDescription(String description) {

this.description = description;

public class HibernateTest {

public static void main(String[] args){

Trang 16

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

Ví dụ 3:Để chỉ chèn ngày tháng năm vào bảng thì ta có cách thể thêm

@Temporal(TemporalType.DATE) vào trước đối tượng có kiểu Date

Bên cạnh đó ta còn có thêm một số kiểu thời gian:

@Temporal(TemporalType.TIME)

@Temporal(TemporalType.TIMESTAMP)

Trang 17

private int userId;

private String userName;

@Temporal(TemporalType.DATE)

private Date joinedDate;

private String address;

private String description;

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;

}

public Date getJoinedDate() {

return joinedDate;}

public void setJoinedDate(Date joinedDate) {

this.joinedDate = joinedDate;

}

public String getAddress() {

return address;}

public void setAddress(String address) {

this.address = address;

}

public String getDescription() {

return description;}

public void setDescription(String description) {

this.description = description;

}

}

Class HibernateTest:

package org.koushik.hibernate;

Trang 18

public class HibernateTest {

public static void main(String[] args){

Ví dụ 4: Để chuyển dữ liệu vào thành kiểu text ta thêm @Lob vào trước phần tử đó.

4 Retrieving Objects using session.get (Truy xuất những đối tượng sử dụng session.get) //giống câu lệnh select

Giống như câu lệnh select.Ta xem ví dụ sau :

Ví dụ:

Trang 19

private int userId;

private String userName;

private Date joinedDate;

private String address;

private String description;

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;

}

public Date getJoinedDate() {

return joinedDate;}

public void setJoinedDate(Date joinedDate) {

this.joinedDate = joinedDate;

}

public String getAddress() {

return address;

Trang 20

public void setAddress(String address) {

this.address = address;

}

public String getDescription() {

return description;}

public void setDescription(String description) {

this.description = description;

public class HibernateTest {

public static void main(String[] args){

session.save(user);

session.getTransaction().commit();

session.close();

Trang 21

session=sessionFatory.openSession();//Mở Session (mở phiên)

một đối tượng UsersDetails trong bảng UsersDetail với id=5 Id có thể

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 (address, description, joinedDate, userName, userId) values (?, ?, ?, ?, ?)

Hibernate: select usersdetai0_.userId as userId0_0_,

usersdetai0_.address as address0_0_, usersdetai0_.description as

descript3_0_0_, usersdetai0_.joinedDate as joinedDate0_0_,

usersdetai0_.userName as userName0_0_ from UsersDetails usersdetai0_ where usersdetai0_.userId=?

Username is :Discription of database

Trang 22

@Id @GeneratedValue

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;

public class HibernateTest {

public static void main(String[] args){

session.save(user);

Trang 23

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

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

<! SQL dialect >

name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property>

<! Disable the second-level cache >

name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<! 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 >

Trang 24

<mapping class="org.koushik.javabrains.dto.UsersDetails"/>

</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) values (?)

Hibernate: insert into UsersDetails (userName) values (?)

Ngoài ra ta còn có 3 giá trị cho từ khóa @GeneratedValue là:

@GeneratedValue(strategy=GenerationType.AUTO)

@GeneratedValue(strategy=GenerationType.IDENTITY)

@GeneratedValue(strategy=GenerationType.SEQUENCE)

@GeneratedValue(strategy=GenerationType.TABLE)

Những cái trên tự tìm hiểu (đều giúp id tự động tăng)

Tài liệu tham khảo: http://elegando.jcg3.org/2009/08/hibernate-generatedvalue/

6.Value types and embedding objects.

Trang 25

public class Address {

private String street;

private String city;

private String state;

private String pinCode;

public String getStreet() {

return street;}

public void setStreet(String street) {

this.street = street;

}

public String getCity() {

return city;}

public void setCity(String city) {

}

public String getState() {

return state;}

public void setState(String state) {

this.state = state;

}

public String getPinCode() {

return pinCode;}

public void setPinCode(String pinCode) {

this.pinCode = pinCode;

Trang 26

@Table(name="UsersDetails")

public class UsersDetails {

@Id @GeneratedValue(strategy=GenerationType.AUTO)

private int userId;

private String userName;

@Embedded

private Address address;

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;

}

public Address getAddress() {

return address;}

public void setAddress(Address address) {

this.address = address;

Trang 27

public static void main(String[] args){

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

<property name="connection.username">sa</property>

<property name="connection.password">quangthao</property>

Trang 28

<! JDBC connection pool (use the built-in) >

<property name="connection.pool_size">1</property>

<! SQL dialect >

name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property>

<! Disable the second-level cache >

name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<! 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 >

</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 (city, pinCode, state, street, userName) values (?, ?, ?, ?, ?)

Hibernate: insert into UsersDetails (city, pinCode, state, street, userName) values (?, ?, ?, ?, ?)

7.Saving collection.

Trang 29

Để thêm một đối tượng collection vào bảng thì phải thêm từ khóa

@ElementCollection vào trước đối tượng đó.Thì nó sẽ tự động tạo ra một bảng mới và có khóa ngoại là id của bản ghi vừa nhập vào.

public class UsersDetails {

@Id @GeneratedValue(strategy=GenerationType.AUTO)

private int userId;

private String userName;

@ElementCollection

private Set<Address> listOfAddress=new HashSet<Address>();

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;

}

public Set<Address> getListOfAddress() {

return listOfAddress;

Trang 30

public void setListOfAddress(Set<Address> listOfAddress) {

this.listOfAddress = listOfAddress;

private String pinCode;

public String getStreet() {

return street;}

public void setStreet(String street) {

this.street = street;

}

public String getCity() {

return city;}

public void setCity(String city) {

}

public String getState() {

return state;}

public void setState(String state) {

this.state = state;

}

public String getPinCode() {

return pinCode;

Trang 31

public void setPinCode(String pinCode) {

this.pinCode = pinCode;

public class HibernateTest {

public static void main(String[] args){

Trang 32

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

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

<! SQL dialect >

name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property>

<! Disable the second-level cache >

name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<! 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 >

Trang 33

<mapping class="org.koushik.javabrains.dto.UsersDetails"/>

</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) values (?)

Hibernate: insert into UsersDetails_listOfAddress

(UsersDetails_userId, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?)

Hibernate: insert into UsersDetails_listOfAddress

(UsersDetails_userId, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?)

Trang 34

Ví dụ 2 :Ta cũng có thể thay đổi tên bảng mới tạo ra bằng cách thêm

@JoinTable(name=”tableName”)

Trang 35

public class UsersDetails {

@Id @GeneratedValue(strategy=GenerationType.AUTO)

private int userId;

private String userName;

@ElementCollection

@JoinTable(name="UsersAddress")

private Set<Address> listOfAddress=new HashSet<Address>();

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;

}

public Set<Address> getListOfAddress() {

return listOfAddress;}

public void setListOfAddress(Set<Address> listOfAddress) {

this.listOfAddress = listOfAddress;

}

}

Trang 36

Ví dụ 3: Ta cũng có thể set tên cột khóa ngoại của bảng mới tạo bằng cách sau :

public class UsersDetails {

@Id @GeneratedValue(strategy=GenerationType.AUTO)

private int userId;

private String userName;

@ElementCollection

@JoinTable(name="UsersAddress",joinColumns=@JoinColumn(name="User_id"))

private Set<Address> listOfAddress=new HashSet<Address>();

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;

}

public Set<Address> getListOfAddress() {

Trang 37

return listOfAddress;}

public void setListOfAddress(Set<Address> listOfAddress) {

this.listOfAddress = listOfAddress;

}

}

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) values (?)

Hibernate: insert into UsersAddress (User_id, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?)

Hibernate: insert into UsersAddress (User_id, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?)

Ví dụ 4:Ta cũng có thể thêm id cho bảng UsersAddress với tên cột id là AddressId.

Trang 38

@Id @GeneratedValue(strategy=GenerationType.AUTO)

private int userId;

private String userName;

@ElementCollection

@JoinTable(name="UsersAddress",joinColumns=@JoinColumn(name="User_id"))//Thiết lập tên bảng và tên cột khóa ngoại

@GenericGenerator(name="hilo-gen",strategy="hilo")

@CollectionId(columns = { @Column(name="AddressId") }, generator

public void setUserId(int userId) {

this.userId = userId;

}

public String getUserName() {

return userName;}

public void setUserName(String userName) {

this.userName = userName;

}

public Collection<Address> getListOfAddress() {

return listOfAddress;}

public void setListOfAddress(Collection<Address> listOfAddress) {

this.listOfAddress = listOfAddress;

Trang 39

import org.koushik.javabrains.dto.UsersDetails;

public class HibernateTest {

public static void main(String[] args){

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) values (?)

Hibernate: insert into UsersAddress (User_id, AddressId, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?, ?)

Hibernate: insert into UsersAddress (User_id, AddressId, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?, ?)

Trang 40

8 Proxy Objects and Eager and Lazy Fetch Types.

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

HÌNH ẢNH LIÊN QUAN

Bảng sẽ bị xóa và tạo dữ liệu mới được thêm vào,đó là do : - Hibernate tutorials
Bảng s ẽ bị xóa và tạo dữ liệu mới được thêm vào,đó là do : (Trang 8)

TỪ KHÓA LIÊN QUAN

w