Hibernate Framework Slides
Hibernate Framework Slides
Hibernate Framework Slides
G1
04e-BM/NS/HDCV/FSOFT v2/3
Course Content
Hibernate framework An Overview Hibernate association and collection mapping Hibernate object lifecycle Hibernate transaction management Hibernate querying Hibernate HQL Java Persistence API
04e-BM/NS/HDCV/FSOFT v2/3
Learning Approach
The following are strongly suggested for a better learning and understanding of this course:
Noting down the key concepts in the class Analyze all the examples / code snippets provided Study and understand the self study topics Completion and submission of all the assignments, on time Completion of the self review questions in the lab guide Study and understand all the artifacts including the reference materials / e-learning / supplementary materials specified Completion of the project (if application for this course) on time inclusive of individual and group activities Taking part in the self assessment activities Participation in the doubt clearing sessions
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
Objectives
04e-BM/NS/HDCV/FSOFT v2/3
Objectives
04e-BM/NS/HDCV/FSOFT v2/3
N-Tier Architecture
Application is made up of layers or tiers Each layer encapsulates specific responsibilities Enables changes in one area with minimal impact to other areas of the application
04e-BM/NS/HDCV/FSOFT v2/3
Common tiers
Presentation
View in model-view-controller Responsible for displaying data only. No business logic
Service
Responsible for business logic
Persistence
Responsible for storing/retrieving data
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
Benefits
Allows different storage implementations to be plugged in with minimal impact to the rest of the system Decouples persistence layer Encourages and supports code reuse
10
04e-BM/NS/HDCV/FSOFT v2/3
Objectives
11
04e-BM/NS/HDCV/FSOFT v2/3
Traditional Persistence
12
04e-BM/NS/HDCV/FSOFT v2/3
JDBC Overview
13
04e-BM/NS/HDCV/FSOFT v2/3
14
04e-BM/NS/HDCV/FSOFT v2/3
...
FPT SOFTWARE TRAINING MATERIAL Internal use 15
04e-BM/NS/HDCV/FSOFT v2/3
Objectives
18
04e-BM/NS/HDCV/FSOFT v2/3
19
04e-BM/NS/HDCV/FSOFT v2/3
Hibernate History
implementation for the JBoss application server. EJB 3.0 Expert Group (2004)
Key member which helped shape EJB3.0 and JPA
NHibernate
.NET version release in 2005
20
04e-BM/NS/HDCV/FSOFT v2/3
Why Hibernate?
Impedance mismatch
Object-oriented vs. relational
21
04e-BM/NS/HDCV/FSOFT v2/3
Why Hibernate?
Java developers are not database developers
Reduce the need for developers to know and fully understand database design, SQL, performance tuning Increase portability across database vendors
Increase performance by deferring to experts Potential decrease in database calls More efficient SQL statements Hibernate cache usage
22
04e-BM/NS/HDCV/FSOFT v2/3
Summary
Motivation
Origination and history of Hibernate Reasons for Hibernates development
Impedance mismatch Failure of EJB 2.x Java developers are not database developers Performance benefits
23
04e-BM/NS/HDCV/FSOFT v2/3
24
04e-BM/NS/HDCV/FSOFT v2/3
Objectives
Creating a simple, but full, end to end Hibernate Application How to use JUnit in developing Enterprise Application
25
04e-BM/NS/HDCV/FSOFT v2/3
Objectives
Creating a simple, but full, end to end Hibernate Application How to use JUnit in developing Enterprise Application
26
04e-BM/NS/HDCV/FSOFT v2/3
04e-BM/NS/HDCV/FSOFT v2/3
29
04e-BM/NS/HDCV/FSOFT v2/3
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration> <session-factory> ... </session-factory> <hibernate-configuration>
30
04e-BM/NS/HDCV/FSOFT v2/3
hibernate.cfg.xml (Cont)
... <session-factory> <property name="hibernate.connection.driver_class"> oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE </property> <property name="hibernate.connection.username">lecture2</property> <property name="hibernate.connection.password">lecture2</property> ...
31
04e-BM/NS/HDCV/FSOFT v2/3
hibernate.cfg.xml (Cont)
... <property name="dialect"> org.hibernate.dialect.Oracle10gDialect</property> <property name="connection.pool_size">1</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <property name="format_sql">false</property> </session-factory>
32
04e-BM/NS/HDCV/FSOFT v2/3
Configuring Hibernate
There are multiple ways to configure Hibernate, and an application can leverage multiple methods at once Hibernate will look for and use configuration properties in the following order
hibernate.properties (when new Configuration() is called) hibernate.cfg.xml (when configure() is called on Configuration) Programatic Configuration Settings
33
04e-BM/NS/HDCV/FSOFT v2/3
Configuring Hibernate(Cont)
34
04e-BM/NS/HDCV/FSOFT v2/3
35
04e-BM/NS/HDCV/FSOFT v2/3
36
04e-BM/NS/HDCV/FSOFT v2/3
Hibernate ID Generators
Native:
Leverages underlying database method for generating ID (sequence, identity, etc)
Increment:
Automatically reads max value of identity column and increments by 1
UUID:
Universally unique identifier combining IP & Date (128bit)
Many more
37
04e-BM/NS/HDCV/FSOFT v2/3
... <property name="dialect">org.hibernate.dialect.Oracle10gDialect </property> <property name="connection.pool_size">1</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <property name="format_sql">false</property> <mapping resource="Account.hbm.xml"/> </session-factory>
38
04e-BM/NS/HDCV/FSOFT v2/3
HibernateUtil
SessionFactory is thread-safe
Singleton for the entire application
39
04e-BM/NS/HDCV/FSOFT v2/3
HibernateUtil (Cont)
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory; // initialize sessionFactory singleton static { sessionFactory = new Configuration(). configure().buildSessionFactory(); } // method used to access singleton public static SessionFactory getSessionFactory() { return sessionFactory; } }
FPT SOFTWARE TRAINING MATERIAL Internal use 40
04e-BM/NS/HDCV/FSOFT v2/3
Session API
41
04e-BM/NS/HDCV/FSOFT v2/3
42
04e-BM/NS/HDCV/FSOFT v2/3
43
04e-BM/NS/HDCV/FSOFT v2/3
44
04e-BM/NS/HDCV/FSOFT v2/3
45
04e-BM/NS/HDCV/FSOFT v2/3
/** * Create a new account or update an existing one * @param account * account to be persisted */ public void saveOrUpdateAccount(Account account) { accountDAO.saveOrUpdateAccount(account); }
46
04e-BM/NS/HDCV/FSOFT v2/3
/** * Retrieve an account * @param accountId * identifier of the account to be retrieved * @return account represented by the identifier provided */ public Account getAccount(long accountId) { return accountDAO.getAccount(accountId); }
47
04e-BM/NS/HDCV/FSOFT v2/3
/** * Delete account * @param account * account to be deleted */ public void deleteAccount(Account account) { accountDAO.deleteAccount(account); }
48
04e-BM/NS/HDCV/FSOFT v2/3
49
04e-BM/NS/HDCV/FSOFT v2/3
Using JUnit
Download the jar from JUnit.org Add downloaded jar to project classpath Create a class to house your test methods, naming it anything you like (typically identifying it as a test class) Implement test methods, naming them anything you like and marking each with the @Test annotation at the method level Call the code to be tested passing in known variables and based on expected behavior, use assert helper methods provided by Junit to verify correctness
Assert.assertTrue(account.getAccountId() == 0);
50
04e-BM/NS/HDCV/FSOFT v2/3
51
04e-BM/NS/HDCV/FSOFT v2/3
52
04e-BM/NS/HDCV/FSOFT v2/3
Test Create
@Test public void testCreateAccount() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Account account = new Account(); // no need to set id, Hibernate will do it for us account.setAccountType(Account.ACCOUNT_TYPE_SAVINGS); account.setCreationDate(new Date()); account.setBalance(1000L); // confirm that there is no accountId set Assert.assertTrue(account.getAccountId() == 0);
...
53
04e-BM/NS/HDCV/FSOFT v2/3
54
04e-BM/NS/HDCV/FSOFT v2/3
Handling Transactions
Why am I starting/ending my transactions in my test case?
In order to take advantage of certain Hibernate features, the Hibernate org recommends you close your transactions as late as possible. For test cases, this means in the tests themselves Later well discuss suggested ways of handling this within applications
55
04e-BM/NS/HDCV/FSOFT v2/3
Test Get
@Test public void testGetAccount() { Account account = createAccount(); // create account to get Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); AccountService accountService = new AccountService(); Account anotherCopy = accountService.getAccount(account.getAccountId()); // make sure these are two separate instances Assert.assertTrue(account != anotherCopy); session.getTransaction().commit(); HibernateUtil.getSessionFactory().close(); }
56
04e-BM/NS/HDCV/FSOFT v2/3
57
04e-BM/NS/HDCV/FSOFT v2/3
58
04e-BM/NS/HDCV/FSOFT v2/3
Test Delete
@Test public void testDeleteAccount() { // create an account to delete Account account = createAccount(); Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); AccountService accountService = new AccountService(); // delete the account accountService.deleteAccount(account); session.getTransaction().commit(); HibernateUtil.getSessionFactory().close(); ...
59
04e-BM/NS/HDCV/FSOFT v2/3
60
04e-BM/NS/HDCV/FSOFT v2/3
Summary
61
04e-BM/NS/HDCV/FSOFT v2/3
Summary (Cont)
HibernateUtil to handle Session
static { sessionFactory = newConfiguration() .configure().buildSessionFactory(); } public static SessionFactory getSessionFactory() { return sessionFactory; }
62
04e-BM/NS/HDCV/FSOFT v2/3
Q&A
63
04e-BM/NS/HDCV/FSOFT v2/3