Professional Documents
Culture Documents
13/09/12(6:15PM)
---------------Q) Explain about service layer of an Enterprise Java Application.
=> A collection of Java class files which are exclusively performing data processing tasks of the
enterprise application is nothing but service layer.
=> For each service provided to the end user implementation is encapsulated in this partition of the
application and hence the name.
=>Programmatical realization of business rules of the enterprise is nothing but businness logic.
=> In an enterprise application business logic only processes data. Therefore, service layer is also
known as business logic layer.
- business rules converted into the programmatic instructions is nothing but business logic.
Hibernate by L N Rao
Page 1
Hibernate
case 3: propagating data processing exception upon receiving data access exception from DAL
case 4: propagating business rule violation exception
3.) Transaction Management
============================================================================================================
=======
14/09/12
-------Q)What is Presentation layer?
=>That partition of Java Enterprise Application which takes care of the end-user interaction.
=>presentation layer is also known as UI layer.
Hibernate by L N Rao
Page 2
Hibernate
Note:- If business logic is physically seperated from 2 tier architecture it becomes it becomes 3 tier.
Two tier architecture
--------------------============================================================================================================
=====
17/09/12
-------Q)Develop a Java application that has 4 layers.Provide the following services through that application.
1.)account opening service
2.)account closing service
3.)withdraw service
4.)deposit service
5.)balance enquiry service
Data Layer
----------
Account(accno,name,balance)
Presentation Layer
------------------
WithdrawUseCase.java
DepositUseCase.java
AccountOpeningUseCase.java
AccountClosingUseCase.java
BalanceEnquiryUseCase.java
Service Layer
-------------
AccountService.java
ProcessingException.java
InsufficientFundsException.java
AccountNotFoundException.java
----------------------------package com.nareshit.exception;
public class AccountNotFoundException extends Exception
{
}//user defined, checked exception
DataAccessException.java
------------------------
package com.nareshit.exception;
public class DataAccessException extends Exception
{
}//user defined, checked exception
Hibernate by L N Rao
Page 3
Hibernate
DBUtil.java
----------package com.nareshit.dao;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtil
{
static
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException e){
//
}
}
public static Connection getConnection() throws SQLException
{
return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:server","nareshit",
"nareshit");
}
}
============================================================================================================
====
18/09/12(6:07)
-------Q)What are the different ways of representing data in a Java Enterprise Application?
1.)Relational format
2.)Object Oriented format
=>data permanence(persistence) sake represented in relational format in data layer.
=>to process and present the same data in a flexible manner , represented in Object Oriented format.
-DTO is also known as Value Object.DTO is a design pattern.
Account.java(DTO)
----------------package com.nareshit.vo;
public class Account
{
int accno;
String name;
float balance;
//setters & getters
}
-DTO class is necessary in Hibernate application unlike JDBC application
=>DTOs are POJOs(Plain Old Java Object classe).
=>A java class is said to be a POJO class if it does not inherit from any technlogy specific or framework
specific java interface or java class.
Note:- Every POJO class of java enterprise application need not be a DTO.Each layer classes can be POJOs.
=================================================================================================
20/09/12
-------AccountDAO.java
--------------ProcessingException.java
-----------------------InsufficientFundsException
--------------------------
Hibernate by L N Rao
Page 4
Hibernate
AccountService.java
------------------=================================================================================================
22/09/12
-------Q)What are the things to be known about a method in order to invoke it?
--------
WithdrawUseCase.java
-------------------AccountOpeningUseCase.java
--------------------------
For eg:-
package com.naresit.service;
public class ServiceFactory
{
private static AccountService accountService = new AccountService();
private static LoanService loanService = new LoanService();
public static AccountService getAccountService()
{
return accountService;
}
public static LoanService getLoanService()
{
return loanService;
}
}
package com.nareshit.dao;
public class DAOFactory
{
private static AccountDAO accountDAO = new AccountDAO();
private static LoanDAO loanDAO = new LoanDAO();
public static AccountDAO getAccountDAO()
{
return accountDAO;
}
public static LoanDAO getLoanDAO()
{
return loanDAO;
}
}
-advantage of factory class is that it makes the layer object singleton.
=================================================================================================
Hibernate by L N Rao
Page 5
Hibernate
25/09/12
--------
Hibernate
---------
=>Hibernate is not a technology unlike JDBC(JDBC is a data access technology from Sun).
=>Hibernate is not a specification unlike JDBC.
=>Hibernate is neither J2SE nor J2EE unlike JDBC,Servlet & JSP(but it uses both).
=>Hibernate is not from Sun Microsystems it's from Apache Software Foundations.
=>Hibernate is not a standard its only a software product developed by ASF.
Q)What is Hibernate?
=>Hibernate is an open source, Java application framework.
=>Hibernate is a software product to be installed into a computer system in order to use it to build data
access layer of Java enterprise application(realtime java project).
26/09/12
-------Q)Explain about traditional approach of Java Persistence?
=>Hard coding/Hand coding SQL statements within the java applications & submitting them to the DBMS to achieve
Java Persistence is nothing but traditional approach.
Hibernate by L N Rao
Page 6
Hibernate
=>Coding complexities.
=>Mismatches between Object Oriented and Relational principles of data representation can't be handled properly.
Vender Lock?
=>The mechanism of implementing implicit Java persistence using meta information that describes the mapping
between Object Oriented and Relational representation of data is nothing but ORM style of Java Persistence.
27/09/12
-------Q)How is CRUD operation performed in ORM approach?
Q)What are the elements of ORM approach to perform CRUD operations with the DBMS?
1.)API
2.)O/R Mapper (mapping tool/engine)
3.)Facility to create mapping info (xml tags & annotations)
4.)A special language to facilitate complex QUERY creation.
5.)facility to create configuration file (xml tags)
Hibernate by L N Rao
Page 7
Hibernate
=>A collection of interfaces and classes of org.hibernate and its sub packages whose methods are used in
Java Application to perform CRUD operations with DBMS is nothing but Hibernate API.
=>Hibernate API can be broadly classified into 3 areas.
1.)API to build HQL queries and to send them so as to perform complex CRUD operations.
2.)Criteria API to retrive data from database.
3.)API to perform basic CRUD operations
=>Hibernate Engine implements Hibernate API.
=>When Java Application makes Hibernate API call to perform CRUD operation, Hibernate Engine receives the
method call and generates the appropriate SQL statement.
Q)Explain about Hibernate Engine.
=>It is special software written in java.
=>It is the O/R mapping tool.
=>It generates SQL statements and sends them to the DBMS using JDBC.
=>Hibernate Engine abstracts JDBC in Java Applications.
Q)Explain about Hibernate configuration file.
=>Standard name for this file is hibernate.cfg.xml
=>DBMS specific details and mapping files details are specified in this file.
=>Hibernate Engine uses this file to generate DBMS specific SQL syntax.
=>Generally, Hibernate configuration file is one per DBMS.We can have single configuration file for multiple
DBMS also.
Q)Explain about hibernate mapping file.
=>Hibernate Engine is able to generate SQL statement using mapping info created by Hibernate developer.
=>For each table of the database we must generate a Java class known Persistence class.
Note:- Instance of this class only persisted into the database and hence the name.
=>Mapping information is created in special xml file known as Hibernate Mapping file.
=>Standard for the mapping file is PersistentClassName.hbm.xml
For eg. Account.hbm.xml
=>Generally one mapping file per class (persistence class).
=>If mapping information is be provided to Hibernate Engine by applying annotations to persistent classes,
Hibernate mapping files are not required in a Hibernate Application.
Q)Explain about Persistent Class.
=>If JDBC is used to perform CRUD operations in a Java project, Object Oriented representation of data is
optional.
=>If ORM approach is followed, Object Oriented representation of data is mandatory.
=>Collection of all tables is nothing but database of the project.It is nothing but relational representation
of data.
=>In ORM approach we need to define one java class per table.These java classes whose instances are
stored into the database are known as persistent classes.These are also known as Entity Classes.
For eg.
Table:- MYACCOUNT(ANO,NM,BAL)
class:-Account(accno,name,balance)
Q)Develop the Persistent class for the above MYACCOUNT table.
@Table(name="MYACCOUNT")
public class Account implements java.io.Serializable
{
@Column(name="ANO")
private int accno;
@Column(name="NM")
private String name;
@Column(name="BAL")
private float balance;
public void setAccno(int ano)
{
accno = ano;
}
public int getAccno()
{
return accno;
}
public void setName(String nm)
Hibernate by L N Rao
Page 8
Hibernate
{
name = nm;
}
public String getName()
{
return name;
}
public void setBalance(float bal)
{
balance = bal;
}
public void getBalance()
{
return balance;
}
}//persistent class
-table name and class name need not be same
-variable name and column name need not be same
-variables need not be private
=>Persistent classes are POJOs(Palin Old Java Object classes).
=>A java class is said to be a POJO if does not inherit from library interface or class of any java
technology or framework.
For eg. above Account class is a POJO because it is not inheriting any library interface or class of
any java technology or framework.
=======================================================================================================
01/10/12
-------Q)What is Hibernate Architecture?
=>"Hibernate arch 01-10-12.bmp"
Q)What are the features of Hibernate?
1.)provides caching mechanism
2.)maintains synchronization between persistent objects and corresponding relational records.
3.)provides Java object's implicit persistence.
4.)provides implicit connection pooling facility
5.)provides transaction support
6.)has a special query language HQL that supports complex CRUD operations
7.)has Object Oriented alternative for HQL in the form of criteria to retrive data from database
8.)provides fine grained exception handling support
9.)generates fine tuned SQL statements
10.)runs both in managed and nonmanaged environment
11.)disburdens the developer from writing boiler plate code to perform CRUD operations and reduce
complexity involved in database operations
12.)provides portability of data accessing across DBMSs
13.)support dirty checking
14.)address O/R mismatch problems effectively
=================================================================================================
02/10/12
-------Q)What are the system requirements to develop Hibernate Applications?
Q)How to develop a basic Hibernate Application that performs a CRUD opertaion with the DBMS?
Step 1:- Develop a persistence class corresponding to the database table.
Step 2:- Develop a Mappig file
Step 3:- Develop the configuration file
Step 4:- Make use of Hibernate programming model to perform the CRUD operation
Hibernate by L N Rao
Page 9
Hibernate
=>refer to "Hibernate Programming Model 2-oct-12.bmp"
=================================================================================================03-oct-12
---------
Q)Develop a Hibernate Application that retrives an account details from the database and displays the
same. If account doesn't exist with that account number, application should display the same.
readapplication
Data Layer:-
Account.java
Account.hbm.xml
hibernate.cfg.xml
ReadApplication.java
MYACCOUNT(ANO,NM,BAL)
Account.java
------------
package com.nareshit.dao;
public class Account
{
private int accno;
private String name;
private float balance;
//setters & getters
}//persistence class(POJO)
Account.hbm.xml
--------------<hibernate-mapping>
<class name="com.nareshit.dao.Account" table="MYACCOUNT">
<id name="accno" column="ANO"/>
<property name="name" column="NM"/>
<property name="balance" column="BAL"/>
</class>
</hibernate-mapping>
Note:- If table name & class name are the same, "table" attribute not required in <class> tag as Hibernate
by default assumes TABLE NAME and persistence class name as same.
=>Similarly, "column" attribute not required in <id> tag and <property> tag if instance variable names
and corresponding column names are the same.
=>In mapping file at least one instance variable of the persistence class should be made as unique field.
<id> tag is used for this purpose.
=>In the table which column is a primary key column that corresponding instance variable is described
using <id> tag in mapping file.
hibernate.cfg.xml
----------------<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:server</property>
<property name="connection.username">nareshit</property>
<property name="connection.password">nareshit</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<mapping resource=""/Account.hbm.xml>
Hibernate by L N Rao
Page 10
Hibernate
</session-factory>
</hibernate-configuration>
============================================================================================================
====
04/10/12
-------ReadApplication.java
--------------------
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import com.nareshit.dao.Account;
class ReadApplication
{
public static void main(String args[])
{
Configuration c = new Configuration();
c.configure(); // 2 xml files are loaded
SessionFactory sf = c.buildSessionFactory();
Session session = sf.openSession();
Account acc = (Account)session.get(Account.class,1001);
if(acc==null)
{
System.out.println("Account doesn't exist");
}
else
{
System.out.println("A/C no.: "+acc.getAccno());
System.out.println("A/C holder name: "+acc.getName());
System.out.println("Balance Rs.: "+acc.getBalance());
}
session.close();
sessionFactory.close();
}
}
Note:- Place Hibernate3.jar file into the classpath before compiling the above application.
=>javac -d . *.java
=>place all the jar files of the Hibernate software into classpath before executing the above application.
Q)Develop a hibernate application that prompt the end user to enter the account number and deletes that
record from the database.
deleteapplication
Account.java
Account.hbm.xml
hibernate.cfg.xml
DeleteApplication.java
Note:-POJO,mapping file and configuration file from the previous application.
DeleteApplication.java
---------------------import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.nareshit.dao.Account;
class DeleteApplication
{
public static void main(String args[])
Hibernate by L N Rao
Page 11
Hibernate
{
Note:- If we are performing insertion,deletion or updation Transaction has to be created and commited.
insertapplication
StoreAccount.java
----------------Account acc = new Account();
acc.setAccno(1001);
acc.setName("Rama");
acc.setBalance(5600f);
Transaction txn = session.beginTransaction();
session.save(acc);
txn.commit();
System.out.println("object persisted");
=================================================================================================
05/10/12
-------Q)Develop a Hibernate Application that increases the specified account by the specified amount in the database.
updateapplication
UpdateApplication.java
----------------------
Account.java
Account.hbm.xml
hibernate.cfg.xml
UpdateApplication.java
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.nareshit.dao.Account;
import java.util.Scanner;
class UpdateApplication
{
Hibernate by L N Rao
Page 12
Hibernate
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the A/C no:");
int ano = s.nextInt();
System.out.print("Enter the depositing amount Rs.:");
float amt = s.nextFloat();
Configuration configuration = new Configuration();
configuration.configure(); // 2 xml files are loaded
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Account acc = (Account)session.get(Account.class,ano);
if(acc==null)
{
System.out.println("Account doesn't exist");
}
else
{
Transaction txn = session.beginTransaction();
float bal = acc.getBalance();
float newbal = bal+amt;
acc.setBalance(newbal);
txn.commit();
System.out.println("Account Updated successfully");
}
session.close();
sessionFactory.close();
}
08/10/12
-------Q)How is account record updated without calling any library method on Session object in UpdateApplication?
=>Persistence object is in-memory representation of a database record.
=>When persistence object is associated with ....
......
=>If persistence object state is modified and when commit() method is called on Session object, HIbernate
engine implicitely generates UPDATE SQL statement and submits to the DBMS using JDBC. Therefore, without
the need of any library method
Q)What happens in the background when save() method is called on the Session object?
=>Hibernate engine receives the method call and generates INSERT SQL statement and submits to the DBMS
Hibernate by L N Rao
Page 13
Hibernate
using JDBC and therefore, record is inserted. We say, Object is persisted.
Q)What happens in the background when delete() method is called on the Session object?
=>Hibernate engine receives the method call and generates DELETE SQL statement and submits to the DBMS
using JDBC and therefore, record is deleted from the database. We say, persisted object is removed.
09/10/12
-------Q)Explain about dialect in a Hibernate Application.
Hibernate by L N Rao
Page 14
Hibernate
class
-dialect is abstracting the SQL variances(across the DBMS) from the application
=>A persistent object is said to be in transient state if it is not associated with Session and nor has matching
record in the database.
=>Persistent object holds enterprise data but not yet persisted using Hibernate is said to be in transient state.
For eg.
Account acc = new Account();
acc.setAccno(1001);
acc.setName("Kailash");
acc.setBalance(5600);
=>In the above piece of code, Account object is said to be in transient state.
=>A persistent object is said to be in detached state, if it is not associated with Session Object but has a
matching record in the database.
=>If the persistent object is in detached state, it is not in sync with database.
For eg.
Account acc = (Account) Session.get(Account.class,1001);//managed state
session.clear(); //acc becomes detached
Transaction txn = session.beginTransaction();
session.save(acc); //error w'll come
txn.commit();
Transaction txn = session.beginTransaction();
session.update(acc);
txn.commit();
____________________________________________________________________________________________________________
____
10/10/12
-------Q)Develop a banking application (Hibernate Application) to perform the following operations.
1.)account opening
2.)account closing
3.)deposit
4.)withdraw
5.)getting account details
bankingapplication
Account.java
-hibernate.cfg.xml
|
Account.hbm.xml
|- Data Access Layer files
AccountDAO.java
|
SessionUtil.java -DAOFactory.java
*.java (other files to implement the 5 use-case)
=>In AccountDAO class we implement 4 methods each of which performs one CRUD operation.
=>In every DAO method we need to get Session object (reference), use it in performing CRUD operation
Hibernate by L N Rao
Page 15
Hibernate
and close it.
=>SessionUtil class is a utility class (helper class) that ensures the following things for the entire
data access layer of the project.
1.)loading meta information only once
2.)creating the heavy weight SessionFactory object only once
3.)providing Session objects to all the DAO methods
SessionUtil.java
---------------package com.nareshit.dao;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
public class SessionUtil
{
private static SessionFactory sf;
static
{
Configuration cfg = new Configuration();
cfg.configure();
sf = cfg.buildSessionFactory();
}
public static Session getSession()
{
return sf.openSession();
}
}
AccountDAO.java
--------------package com.nareshit.dao;
import org.hibernate.Session;
public class AccountDAO
{
public Account findAccount(int ano)
{
Account acc = null;
Session session = SessionUtil.getSession();
acc = (Account) session.get(Account.class,ano);
session.close();
return acc;
}//DAO method
public void storeAccount(Account acc)
{
Session session = SessionUtil.getSession();
session.getTransaction().begin();
session.save(acc);
session.getTransaction().commit();
session.close();
}
public void updateAccount(Account acc)
{
Session session = SessionUtil.getSession();
session.getTransaction().begin();
session.update(acc);
session.getTransaction().commit();
session.close();
}
public boolean deleteAccount(int ano)
Hibernate by L N Rao
Page 16
Hibernate
{
DAOFactory.java
--------------package com.nareshit.dao;
public class DAOFactory
{
private static AccountDAO accountDAO = new AccountDAO();
public static AccountDAO getAccountDAO()
{
return accountDAO;
}
}
DepositUseCase.java (PL Plus SL)
------------------import com.nareshit.dao.SessionUtil;
import com.nareshit.dao.Account;
import com.nareshit.dao.AccountDAO;
import com.nareshit.dao.DAOFactory;
class DepositUseCase
{
public static void main(String args[])
{
//PL code
int ano = 1001;
float amt = 500f;
//SL code
AccountDAO accountDAO = DAOFactory.getAccountDAO();
Account acc = accountDAO.findAccount(ano);
float bal = acc.getBalance();
float newbal = bal + amt;
acc.setBalance(newbal);
accountDAO.updateAccount(acc); //SL over
System.out.println("deposited successfully");//PL
}
}
___________________________________________________________________________________________
12/10/12
----------
Hibernate by L N Rao
Page 17
Hibernate
import com.nareshit.dao.SessionUtil;
import com.nareshit.dao.Account;
import com.nareshit.dao.AccountDAO;
import com.nareshit.dao.DAOFactory;
class WithdrawUseCase
{
public static void main(String args[])
{
//PL code
int ano = 1001;
float amt = 500f;
//SL code
AccountDAO accountDAO = DAOFactory.getAccountDAO();
Account acc = accountDAO.findAccount(ano);
float bal = acc.getBalance();
float newbal = bal- amt;
acc.setBalance(newbal);
accountDAO.updateAccount(acc); //SL over
System.out.println("Please collect the cash");//PL
Step 1:- place Hibernate jar files and driver jar file in lib folder.
Step 2:- place hibernate configuration file, mapping file into "classes" folder.
Step 3:- place data access layer files into "classes" folder.
Step 4:- in web component make use of DAO class to perform CRUD operations.
hibernate.cfg.xml
Account.hbm.xml
com
nareshit
dao
web
lib
Account.class
DAOFactory.class
AccountDAO.class
SessionUtil.class
DepositServlet.class
*.jar
http://localhost:80801/depositapplication/deposit.html
web.xml
--------<web-app>
<servlet>
<servlet-name>deposit</servlet-name>
<servlet-class>com.nareshit.web.DepositServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>deposit</servlet-name>
<url-pattern>/deposit</url-pattern>
</servlet-mapping>
Hibernate by L N Rao
Page 18
Hibernate
</web-app>
deposit.html
------------<html>
<body bgcolor="cyan">
<center>
<h1>Deposit Screen</h1>
<form action="./deposit" method="POST">
A/C no <input type="text" name="accno">
<br><br>
Amount <input type="text" name="amount">
<br><br>
<input type="submit" value="Deposit">
</form>
</center>
</body>
</html>
DepositServlet.java
--------------------package com.nareshit.web;
import javax.servlet.*;
import java.io.*;
import com.nareshit.dao.Account;
import com.nareshit.dao.AccountDAO;
import com.nareshit.dao.DAOFactory;
public class DepositServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response)
{
int ano = Integer.parseInt(request.getParameter("accno"));
float amt = Float.parseFloat(request.getParameter("amount"));
AccountDAO accountDAO = DAOFactory.getAccountDAO();
Account acc = accountDAO.findAccount(ano);
if(acc == null)
{
System.out.println("Account does not exist");
}
else
{
acc.setBalance(acc.getBalance()+amt);
accountDAO.updateAccount(acc);
System.out.println("successfully deposited");
}
}//service
}
15/10/12(Monday, 6PM)
-------Developing Hibernate application using MyEclipse
-----------------------------------------------Q)What is MyEclipse?
Hibernate by L N Rao
Page 19
Hibernate
=>NetBeans,JDeveloper,JBuilder,RAD,Eclipse are some of the other IDEs used for Java
application development.
=>A master folder in which, our Java applications developed using MyEclipse are stored is
known as workspace.
=>We can create as many number of workspace as we want.
=>In a workspace not only Java applications but also environmental information(meta data)
is stored (MyEclipse requirement).
=>Every MyEclipse session is associated with a workspace.
Q)Develop a Java application(Java project) that displays "Hello World" on MyEclipse console.
Step 1:- Create a Java project.
Step 2:- Package creation
....
____________________________________________________________________________________________________________
________
16/10/12
-------......
_________________________________________________________________________________________________
17/10/12
-------Q)What are the limitations of Session interface methods in performing CRUD operations?
1.)Can't retrieve multiple persistent objects.
2.)Can't perform bulk updates and bulk deletes.
3.)To retieve single persistence object also we need to specify id field value i.e. using non-id
field value as search criteria, we can't retrieve the persistent object.
4.)Can't express required complex criteria to perform the CRUD operation.
Hibernate by L N Rao
Page 20
Hibernate
1.)Syntactical difference
2.)SQL is expressed in terms of tables and corresponding columns where as, HQL query is expressed in
terms of persistence classes and their fields.
3.)SQL in non portable across DBMSs. Where as, HQL is portable.
=>"HQL 17-oct-12.bmp"
Step 1:- Build HQL Query
Step 2:- create Query interface object
Step 3:- Bind the parameters if any.
Step 4:- Execute the Query(Submitting the query to Hibernate Engine).
____________________________________________________________________________________________________________
_________
18/10/12
-------Q)Develop a Hibernate Application that retrieves all the accounts from the database and display their state.
readaccountsapplication
Account.java
hibernate.cfg.xml
Account.hbm.xml
SessionUtil.java
ReadAccountApplication.java
ReadAccountsApplication.java
---------------------------import org.hibernate.Session;
import org.hibernate.Query;
import java.util.List;
import com.nareshit.dao.Account;
import com.nareshit.dao.SessionUtil;
class ReadAccountsApplication
{
public static void main(String args[])
{
Session session = SessionUtil.getSession();
String hql = "SELECT a from Account a WHERE a.balance > 3000";
Query query = session.createQuery(hql);
List<Account> accounts = query.list();
Q)Develop a DAO class to have multiple records retrieving method. Make use of JDBC API.
public class AccountDAO
{
public List<Account> findAccounts()
{
Connection con = null;
Statement st = null;
ResultSet rs = null;
List<Account> accounts = null;
try
{
con = DBUtil.getConnection();
Hibernate by L N Rao
Page 21
Hibernate
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM ACCOUNT");
if(rs.next())
{
accounts = new ArrayList<Account>();
do
{
Account acc = new Account();
acc.setAccno(rs.getInt(1));
acc.setName(rs.getString(2));
acc.setBalance(rs.getFloat(3));
accounts.add(acc);
}while(rs.next());
}
}//try
catch(SQLException e)
{
}
finally
{
DBUtil.close(con,st,rs);
}
return accounts;
}//findAccounts()
}//DAO class
=>list() method of Query class in Hibernate does all the tasks what findAccounts() method does in the above
example.
Q)Modify the above DAO class so as to use Hibernate API in DAO method.
AccountDAO.java
--------------package com.nareshit.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Query;
public class AccountDAO
{
public List<Account> findAccounts()
{
Session session = SessionUtil.getSession();
Query query = session.createQuery("SELECT a FROM Account a");
List<Account> accounts = query.list();
session.close();
return accounts;
}
}
class ReadAccountsApplication
{
public static void main(String args[])
{
AccountDAO accountDAO = new AccountDAO();
List<Account> accounts = accountDAO.findAccounts();
for(Account acc : accounts)
{
Hibernate by L N Rao
Page 22
Hibernate
}
____________________________________________________________________________________________________________
________
19/10/12
-------Q)Develop a Hibernate Application, in which increase the balances of all the accounts by Rs.500.
bulkupdatesapplication
Account.java
BulkUpdatesApplication.java
*.xml
SessionUtil.java
BulkUpdatesApplication.java
---------------------------
import org.hibernate.Session;
import org.hibernate.Query;
import com.nareshit.dao.SessionUtil;
public class BulkUpdatesApplication
{
public static void main(String args[])
{
Session session = SessionUtil.getSession();
Query query = session.createQuery("UPDATE Account a SET a.balance=a.balance+500");
session.getTransaction().begin();
int c = query.executeUpdate();
session.getTransaction().commit();
System.out.println(c+" accounts updates");
session.close();
}
}
Q)Develop a piece of Hibernate code that deletes all the persistence objects from the database whose balance
is less than Rs.10000.
BulkDeletesApplication.java
--------------------------.....
Session session = SessionUtil.getSession();
Query query = session.createQuery("DELETE FROM Account a WHERE a.balance<10000");
session.getTransaction().begin();
query.executeUpdate();
session.getTransaction().commit();
.....
Q)Write a piece of Hibernate code in which, positional parameters are used in HQL query.
Hibernate by L N Rao
Page 23
Hibernate
Q)Can we mix positional parameters and named parameters in the same HQL query?
22/10/12
-------Q)What are the different approaches of a Hibernate application connecting to multiple DBMSs (concurrrently)?
1.)one configuration file per DBMS
2.)single configuration file for any number of DBMSs.
Q)Develop a Hibernate Application that communicates with Oracle DBMS and MySQL DBMS using "configuration
file per DBMS approach".
multidbmsreadapplication
Account.hbm.xml
Account.java
ReadApplication.java
hibernate.oraclecfg.xml
hibernate.cfgmysql.xml
Note:- Mapping file, persistent class, hibernate.oraclecfg.xml source code from earlier applications only.
hibernate.cfgmysql.xml
----------------------
ReadApplication.java
-------------------import com.nareshit.dao.Account;
import org.hibernate.*;
import org.hibernate.cfg.*;
Hibernate by L N Rao
Page 24
Hibernate
ReadApplication.java
--------------------
singleconfigfilereadapplication
Account.java
hibernate.cfg.xml
Account.hbm.xml
ReadApplication.java
DBUtil.java
_________________________________________________________________________________________________________
25/10/12
-------hibernate.cfg.xml
-----------------
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<mapping resource="Account.hbm.xml"/>
</session-factory>
</hibernate-configuration>
DBUtil.java
-----------
package com.nareshit.dao;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtil
{
static
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.mysql.jdbc.Driver");
Hibernate by L N Rao
Page 25
Hibernate
}
catch(Exception e)
{
System.out.println(e);
}
}//static initializer
public static Connection getOracleConnection()
{
Connection con = null;
try
{
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:server","nareshit","nareshit");
}
catch(Exception e)
{
}
return con;
}
public static Connection getMySQLConnection()
{
Connection con = null;
try
{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/MySQL","root","root");
}
catch(Exception e)
{
}
return con;
}//user defined factory method
}
ReadApplication.java
-------------------import com.nareshit.dao.Account;
import com.nareshit.dao.DBUtil;
import org.hibernate.*;
import org.hibernate.cfg.*;
class ReadApplication
{
public static void main(String args[])
{
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session osession = sf.openSession(DBUtil.getOracleConnection());
Account acc = (Account) osession.get(Account.class,1001);
System.out.println("Oracle balance Rs."+acc.getBalance());
osession.close();
Hibernate by L N Rao
Page 26
Hibernate
org.hibernate.HibernateException catch block.
=>from within the catch block of every DAO method propagate userdefined exception to service layer.
____________________________________________________________________________________________________________
_______
26/10/12
-------Q)Implement exception handling in AccountDAO class.
AccountNotFoundException.java
-----------------------------package com.nareshit.exception;
public class AccountNotFoundException extends Exception
{
}//user defined checked exception
DataAccessException.java
-----------------------------package com.nareshit.exception;
public class DataAccessException extends Exception
{
}//user defined checked exception
AccountDAO.java
---------------
package com.nareshit.dao;
import com.nareshit.exception.AccountNotFoundException;
import com.nareshit.exception.DataAccessException;
import java.util.List;
public interface AccountDAO
{
public abstract void storeAccount(Account acc)throws DataAccessException;
public abstract void deleteAccount(int accno)throws DataAccessException,AccountNotFoundException;
public abstract void updateAccount(Account acc)throws DataAccessException;
public abstract Account findAccount(int accno)throws DataAccessException,AccountNotFoundException;
public abstract List<Account> findAccounts()throws DataAccessException,AccountNotFoundException;
}
AccountDAOImpl.java
------------------package com.nareshit.dao;
import com.nareshit.exception.AccountNotFoundException;
import com.nareshit.exception.DataAccessException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
public class AccountDAOImpl implements AccountDAO
{
public Account findAccount(int accno)throws AccountNotFoundException,DataAccessException
{
Account acc = null;
Session session = null;
try
{
session = SessionUtil.getSession();
acc = (Account) session.get(Account.class,accno);
if(acc==null)
throw new AccountNotFoundException();
}
Hibernate by L N Rao
Page 27
Hibernate
catch(HibernateException e)
{
throw new DataAccessException();
}
finally
{
if(session != null)
{
session.close();
}
}
return acc;
}//findAccount
public void storeAccount(Account acc)throws DataAccessException{}
public void deleteAccount(int accno)throws DataAccessException,AccountNotFoundException{}
public void updateAccount(Account acc)throws DataAccessException{}
public Account findAccount(int accno)throws DataAccessException,AccountNotFoundException{}
public List<Account> findAccounts()throws DataAccessException,AccountNotFoundException{}
}
__________________________________________________________________________________________________________
29/10/12
-------Q)Modify the first hibernate example so as to provide mapping information to hibernate engine using
annotations.
readapplication
Account.java
hibernate.cfg.xml
ReadApplication.java
ReadApplication.java
--------------------
hibernate.cfg.xml
-----------------
<hibernate-configuration>
<session-factory>
.....
<mapping class="com.nareshit.dao.Account"/>
</session-factory>
</hibernate-configuration>
Account.java
-----------package com.nareshit.dao;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
@Entity
@Table(name="MYACCOUNT")
public class Account
{
@Id
@Column(name="ANO")
private int accno;
@Column(name="MN")
private String name;
@Column(name="BAL")
private String balance;
Hibernate by L N Rao
Page 28
Hibernate
30/10/12
-------Q)How to make use of a named HQL query in a Hibernate Application?
Step 1:- Build the query either in the mapping file or at the persistent class.
Step 2:- Create query object.
Step 3:- Bind the parameters if any.
Step 4:- Execute the query.
Note:- Step 3 and Step 4 are the same for both annonymous and named HQL query.
Account.hbm.xml
--------------<hibernate-mapping>
<class ....>
</class>
<query name="allaccounts">
SELECT a FROM Account a
</query>
</hibernate-mapping>
AccountDAO.java
---------------
package com.nareshit.dao;
import org.hibernate.Query;
import org.hibernate.Session;
import java.util.List;
public class AccountDAO
{
public List<Account> findAccounts()
{
Session session = SessionUtil.getSession();
Query query = session.getNamedQuery("allaccounts");
List<Account> accounts = query.list();
session.close();
return accounts;
}
}
Hibernate by L N Rao
Page 29
Hibernate
NamedQueryApplication.java
--------------------------
import com.nareshit.dao.AccountDAO;
import com.nareshit.dao.Account;
import java.util.List;
class NamedQueryApplication
{
public static void main(String args[])
{
AccountDAO dao = new AccountDAO();
List<Account> accounts = dao.findAccounts();
System.out.println("Number of accounts: "+accounts.size());
for(Account acc : accounts)
{
System.out.println("Accno : "+ acc.getAccno());
System.out.println("Name : "+ acc.getName());
System.out.println("Balance : "+ acc.getBalance());
}
}
}
Q)How to overcome the violation of well-formedness of mapping file as a result of named query?
=>An xml document is said to be well-formed if it is syntactically correct.
=>When HQL query is violating the syntactical rules of xml document, we need to write the query
in a special area known as CDATA section.
For eg.
<![CDATA[
SELECT a FROM Account a WHERE a.balance<9000
]]>
<![CDATA[SELECT a FROM Account a WHERE a.balance<:bal]]>
Q)Modify the previous hibernate application so as to give mapping info to Hibernate Engine using
annotations.
namedqueryannotationapplication
Account.java
SessionUtil.java
hibernate.cfg.xml
AccountDAO.java
NamedQueryApplication.java
Note:- SessionUtil.java, AccountDAO.java, NamedQueryApplication.java are from previous application.
hibernate.cfg.xml
-----------------
<hibernate-configuration>
<session-factory>
.......
<mapping class="com.nareshit.dao.Account"/>
</session-factory>
</hibernate-configuration>
Account.java
-----------package com.nareshit.dao;
import javax.persistence.*;
@Entity
@Table(name="myaccount")
@NamedQuery(name="allaccounts",query="SELECT a FROM Account a WHERE a.balance<:bal")
public class Account
{
@Id
Hibernate by L N Rao
Page 30
Hibernate
@Column(name="ANO")
private int accno;
@Column(name="NM")
private String name;
@Column(name="BAL")
private float balance;
//setters & getters
}
_________________________________________________________________________________________________
31/10/12
-------Q)Explain about different cases of list() method.
ListMethodsApplication.java
---------------------------
class ListMethodsApplication
{
public static void main(String args[])
{
Session session = SessionUtil.getSession();
String hql1 = "SELECT a.balance FROM Account a";
Query query = session.createQuery(hql1);
List<Float> bals = query.list();
for(Float bal : bals)
System.out.println(bal);
String hql2 = "SELECT a.name FROM Account a";
query = session.createQuery(hql2);
List<String> nms = query.list(();
for(String name : nms)
System.out.println(name);
Q)Hibernate application in which, the following things are used in HQL queries.
1.)Named query
Hibernate by L N Rao
Page 31
Hibernate
2.)aggregate function calling in HQL
3.)GROUP BY and ORDER BY clauses
4.)maintaining well-formedness of the mapping file while building the
named HQL query.
SQL script
----------
Employee.java
------------package com.nareshit.dao;
public class Employee
{
private int empno;
private String name;
private float salary;
private int deptno;
}
Employee.hbm.xml
----------------
<hibernate-mapping>
<class name="com.nareshit.dao.Employee">
<id name="empno"/>
<property name="name"/>
<property name="salary"/>
<property name="deptno"/>
</class>
<query name="avgsal">
SELECT AVG(e.salary) FROM Employee e
</query>
<query name="groupsal">
SELECT e.deptno,AVG(e.salary) FROM Employee e GROUP BY e.deptno
</query>
<query name="ordersal">
<![CDATA[
SELECT e.name,e.salary FROM Employee e ORDER BY e.salary DESC
]]>
</query>
</hibernate-mapping>
__________________________________________________________________________________________________________
01/11/12
-------HibernateApplication.java
------------------------import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.List;
import com.nareshit.dao.SessionUtil;
Hibernate by L N Rao
Page 32
Hibernate
import com.nareshit.dao.Employee;
public class HibernateApplication
{
public static void main(String args[])
{
Session session = SessionUtil.getSession();
Query query = session.getNamedQuery("avgsal");
System.out.println("Average salary is Rs."+query.uniqueResult());
query = session.getNamedQuery("groupsal");
List<Object[]> emps = query.list();
System.out.println("DEPTNO AVG SAL");
for(Object[] o : emps)
{
System.out.println(o[0]+"\t"+o[1]);
}
query = session.getNamedQuery("ordersal");
List<Object[]> emps1 = query.list();
System.out.println("NAME SALARY");
for(Object[] o : emps1)
{
System.out.println(o[0]+"\t"+o[1]);
}
session.close();
}
Note:- Whenever there is a chance of getting a single object(single result) from the query,
it is advisable to call uniqueResult() method on Query object, instead of calling
list() method.
If multiple objects are returned from the query, this method throws
NonUniqueResultException.
hibernate.cfg.xml
----------------<hibernate-configuration>
<session-factory>
........
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Q)Modify the previous application so as to provide mapping info to Hibernate Engine using
annotations.
Employee.java
-------------
lasthqlapplication
Employee.java
hibernate.cfg.xml
SessionUtil.java
HibernateApplication.java
package com.nareshit.dao;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Id;
@Entity
@NamedQueries(
{
@NamedQuery(name="avgsal",query="SELECT AVG(e.salary) FROM Employee e")
@NamedQuery(name="groupsal",query="SELECT e.deptno,AVG(e.salary) FROM Employee e GROUP BY e.deptno")
@NamedQuery(name="ordersal",query="SELECT e.name,e.salary FROM Employee e ORDER BY e.salary DESC")
})
Hibernate by L N Rao
Page 33
Hibernate
public class Employee
{
@Id
private int empno;
private String name;
private float salary;
private int deptno;
}
hibernate.cfg.xml
-----------------
<hibernate-configuration>
<session-factory>
........
<mapping class="com.nareshit.dao.Employee"/>
</session-factory>
</hibernate-configuration>
____________________________________________________________________________________________________________
________
02/11/12
-------Q)Hibernate application in which one session object per thread is created.
threadpersessionapplication
ThreadLocalApplication.java
SessionUtil.java
hibernate.cfg.xml
Account.java
Account.hbm.xml
SessionUtil.java
---------------package com.nareshit.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Configuration;
//import java.lang.ThreadLocal;
public class SessionUtil
{
private static SessionFactory sf;
private static ThreadLocal<Session> threadLocal;
static
{
Hibernate by L N Rao
Page 34
Hibernate
ThreadLocalApplication.java
---------------------------
import com.nareshit.dao.SessionUtil;
class ThreadLocalApplication
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+":"+
SessionUtil.getThreadLocalSession().hashCode());
MyThread m = new MyThread();
m.setName("child");
m.start();
}
}
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+":"+
SessionUtil.getThreadLocalSession().hashCode());
}
}
--We can change the name of "main" thread.
Q)What is ThreadLocal?
05/11/12
-------Q)What are the rules/
Criteria (API)
-------------Q)Explain about Criteria in the context of Hibernate.
=>It is one way of querying the database in a Hibernate Application(session methods, HQL and native
SQL are the other ways).
=>Crieria API is used only to retrieve the data from the database. i.e. it can't be used for DML
operations.
=>Criteria API is an object oriented alternative for HQL to read data from database.
=>Criteria API supports compile time checking for the query that we build unlike HQL.
=>Dynamic query building is flexible with Criteria when compared to HQL.
Hibernate by L N Rao
Page 35
Hibernate
=>If query is very large, Criteria API is difficult to use and HQL is preferable.
Q)Develop a Hibernate Application to retrieve all accounts from the database and display their state.
criteriareadapplication
CriteriaReadApplication.java
----------------------------
Account.java
SessionUtil.java
hibernate.cfg.xml
Account.hbm.xml
CriteriaReadApplication.java
import org.hibernate.Session;
import org.hibernate.Criteria;
import java.util.List;
import com.nareshit.dao.Account;
import com.nareshit.dao.SessionUtil;
class CriteriaReadApplication
{
public static void main(String args[])
{
Session session = SessionUtil.getSession();
Criteria criteria = session.createCriteria(Account.class);
List<Account> accounts = criteria.list();
Q)Develop a piece of code to retrieve all the accounts whose balance is less than Rs.10,000.
import org.hibernate.Session;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import java.util.List;
import com.nareshit.dao.Account;
import com.nareshit.dao.SessionUtil;
class CriteriaReadApplication
{
public static void main(String args[])
{
Session session = SessionUtil.getSession();
Criteria criteria = session.createCriteria(Account.class);
Criterion criterion = Restrictions.lt("balance",10000f);
criteria.add(criterion);
List<Account> accounts = criteria.list();
for(Account acc : accounts)
{
System.out.println("A/C no.: "+acc.getAccno());
System.out.println("A/C holder name: "+acc.getName());
Hibernate by L N Rao
Page 36
Hibernate
Note:- Criterion interface and Restrictions interface class belong to org.hibernate.criterion package.
__________________________________________________________________________________________________________
06/11/12
-------no class
___________________________________________________________________________________________________________
07/11/12
-------no class
________________
08/11/12
-------Q)How to retrieve all the accounts whose balance between Rs. 7000 and 10000.
//left
......
Criterion criterion1 =
Criterion criterion2 = Restrictions.lt("balance",10000f);
criteria.add(criterion1);
criteria.add(criterion2);
List<Account> accounts = criteria.list();
OR
Criterion criterion = Restrictions.between("balance",7000,10000f);
criteria.add(criterion);
Note:- org.hibernate.Query interface also has the same methods to implement pagination while using HQL
in querying the database in a Hibernate Application.
--scrolling blindness problem + memory + performance problem
____________________________
Hibernate by L N Rao
Page 37
Hibernate
=>Without J2EE container (For eg. web container) if the Java application is running, it is known as
non-managed environment.
=>In such environment, to enable Hibernate provided connection pooling facility, make use of following
tag in Hibernate Configuration file additionally.
<property name="connection.pool_size">5</property>
=>Almost all Java Enterprise Applications run in J2EE container. J2EE container provided connection
pool is the most efficient.
=>hibernate.cfg.xml should not have database connection related tags in order to use container provided
connection pool.
hibernate.cfg.xml
----------------<hibernate-configuration>
<session-factory>
<property name="connection.datasource">java:comp/env/myds</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<mapping resource="Account.hbm.xml">
</session-factory>
</hibernate-configuration>
___________________________________________________________________________________________________________
09/11/12
---------
Native SQL
~~~~~~~~~~
=>Native SQL in nothing but SQL queries submitting to the DBMS using Hibernate API in a Hibernate
Application similar to that of a JDBC Application.
=>Native SQL is used in Hibernate Applications in the following scenarios.
1.)to call the stored procedure
2.)Feature required in the project provided by SQL but not provided by Hibernate.
3.)While communicating with legacy databases.
Note:- As far as possible avoid native Native SQL due to portability reasons.
--vendor lock?
Q)Develop a Hibernate application in which Native SQL is used to retrieve all the accounts?
nativesqlreadapplication
Account.java
SessionUtil.java
hibernate.cfg.xml
Account.hbm.xml
NativeReadApplication.java
NativeReadApplication.java
-------------------------Q)Develop a piece of code to retrieve name and balance of all the accounts using Native SQL.
Q)Modify the above piece of code so as to use named native SQL query.
namednativesqlapplication
Account.java
SessionUtil.java
hibernate.cfg.xml
Account.hbm.xml
NamedNativeQueryApplication.java
NamedNativeQueryApplication.java
--------------------------------
Hibernate by L N Rao
Page 38
Hibernate
mapping file
------------
<sql-query name="avg">
<return-scalar column="avgbal" type="float"/>
SELECT AVG(bal) AS avgbal from MYACCOUNT
</sql-query>
10/11/12
-------Calling a strored procedure in a HIbernate Application
-----------------------------------------------------Example stored procedure
------------------------
StoredProcedureApplication.java
------------------------------import org.hibernate.Session;
import com.nareshit.dao.SessionUtil;
import java.sql.Connection;
import java.sql.CallableStatement;
import java.sql.SQLException;
public class StoredProcedureApplication
{
public static void main(String args[])throws SQLException
{
Session session = SessionUtil.getSession();
Connection con = session.connection();
Hibernate by L N Rao
Page 39
Hibernate
Q)Modify the above application so as to call the stored procedure in pure hibernate style.
StoredProcedureNativeSQLApplication.java
----------------------------------------import org.hibernate.Session;
import org.hibernate.SQLQuery;
import com.nareshit.dao.SessionUtil;
session.getTransaction().begin();
query.executeUpdate();
session.getTransaction().commit();
System.out.println("account updated");
session.close();
Q)Modify the avove application so as to bring portability while calling the stored procedure.
Account.hbm.xml
--------------<hibernate-mapping>
<class ....>
</class>
<sql-query name="chgbal">
{call changeBal(?,?)}
</sql-query>
</hibernate-mapping>
StoredProcedureNamedQueryApplication.java
-----------------------------------------
12/11/12
-----------Q)Explain about O/R mismatches.*
=>There exists paradigm mismatch(impedence mismatch) between Object Oriented and Relational
representation of data in a enterprise application.
=>Most notable mismatches are
Hibernate by L N Rao
Page 40
Hibernate
1.)Problem of granularity
2.)Problem of sub types(inheritance mismatch)
3.)problem of relationships(relationship mismatch)
=>RTH page 11
Employee.java
Address.java
Employee.hbm.xml
GranularityApplication.java
hibernate.cfg.xml
SessionUtil.java
sql script
---------drop table employee;
create table employee(empno number(8),name varchar2(12),salary number(8,2),deptno number(3),
hno varchar2(20),street varchar2(12),city varchar2(15),pin number(6));
insert into employee values(1001,'Rama',40000,10,'7-7-45','Shiv Bagh','Hyderabad',500072);
commit;
select * from employee;
/
=>The process of creating persistent class and mapping file from already created database table is known
as reverse engineering in the context of Hibernate.
=>This property instructs Hibernate Engine to genarate the Table creation statement and submit to DBMS
by using mapping file information.
For eg.
<property name="hbm2ddl.auto">create</property>
OR
Hibernate by L N Rao
Page 41
Hibernate
<property name="hbm2ddl.auto">update</property>
=>If "create" value is given to this property, even if the table is already exixting, it will be dropped
and new table is created. If table is not exixting then any how it will be created.
=>"update" instructs Hibernate Engine to create table if it is not there. If it is there, use the already
existing table and don't create the new one is the instruction.
__________________________________________________________________________________________________________
14/11/12
---------not attended
-- inheritance mismatch
__________________________________________________________________________________________________________
15/11/12
-------Q)Explain about relationship mismatch in a Hibernate Application.
=>In relational representation of data i.e. at database level, many to many relationship doesn't exist
between tables.Whereas, corresponding persistent object support many-to-many relationship.This is
known as relationship mismatch between object oriented and relational representation of data.
=>One persistent class declaring a collection of the other persistent objects and vice versa is nothing
but many-to-many relationship between persistent objects.
For eg.
public class Course
{
List<Student> students;
.....
.....
}
public class Student
{
List<Course> courses;
......
......
}
16/11/12
-------Q)What is lazy loading in the context of Hibernate?
=>If Java application is querying for persistent object, instead of querying the database hibernate
providing proxy of the queried persistent object with default value to the application and hitting
the database only when getter(accessor) method is called is nothing but lazy loading.
=>If lazy attribute of <class> tag is given "false" value, lazy loading of a persistent object is
disabled even if load() method is called on the session object.
=>Sometimes lazy loading improves performance.
=>Maintain local copy of already requested data at application side in a Java Enterprise Application is
nothing but Caching.
=>Caching improves performance.
=>If we use JDBC as data access mechanism, application developer is responsible to implement caching
Hibernate by L N Rao
Page 42
Hibernate
through coding.
=>Hibernate provides caching support without any programming effort in the application side.
=>Two types of caching exists in Hibernate applications
1.)L1(Level 1) cache
2.)L2(Level 2) cache
=>L1 cache is nothing but Session level cache. Which is implicitly provided by Hibernate.
=>L2 cache is optional unlike L1 and it is externally configurable.
=>"caching 16-nov-12.bmp"
19/11/12
--------
Generators
---------------Q)Explain about generators in the context of Hibernate?
Hibernate by L N Rao
Page 43
Hibernate
<id name="accno" column="ANO">
<generator class="increment"/>
</id>
OR
<id name="accno" column="ANO">
<generator class="org.hibernate.id.IncrementGenerator"/>
</id>
=>generate() method of increment generator retrieves max value of id field of already persistent object,
increments it by 1 and returns to Hibernate engine.
=>When save method is called on the Session object, HIbernate engine calls generate() method of increment
generator, gets the id field value, assigns it to the persistent object and then it is persisted.
For eg.
Account acc = new Account();
acc.setName("XYZ");
acc.setBalance(8900f);
Transaction txn = session.beginTransaction();
java.io.Serializable id = session.save(acc);
txn.commit();
System.out.println("Account persisted with id: "+id);
20/11/12
--------
Hibernate by L N Rao
Page 44
Hibernate
</id>
=>If data access layer developer generated the generator class explicitely without depending upon the
built-in generators, it is known as user defined generator.
=>For two reasons we go for user defined generator.
1.)when id field has Alpha numerical value.
2.)application specific algorithm is required to be implemented in the auto-generation
of id field value.
Loan.java
-----------package com.nareshit.dao;
public class Loan
{
private String loan_id;
private String name;
private float loan_amount;
//setters & getters
}
Loan.hbm.xml
-----------------<hibernate-mapping>
<class name="com.nareshit.dao.Loan">
<id name="loan_id">
<generator class="com.nareshit.dao.LoadIdGenerator"/>
</id>
<property name="name"/>
<property name="loan_amount"/>
</class>
</hibernate-mapping>
StoreApplication.java
----------------------------
LoanIdGenerator.java
---------------------------package com.nareshit.dao;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.engine.SessionImplementor;
import java.io.Serializable;
import java.sql.*;
class LoanIdGenerator implements IdentifierGenerator
{
public Serializable generate(SessionImplementor si,Object o)
{
String lid="HDFCLP";
Hibernate by L N Rao
Page 45
Hibernate
try
{
Connection con = si.connection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select to_char(loanid_sequence.nextval,'FM000000') from dual");
rs.next();
lid = lid + rs.getString(1);
rs.close();
st.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return lid;
--<property name="hbm2ddl.auto">create</property>
sql script
----------
21/11/12
-------Q)Explain about IdentityGenerator?
Relationships
-----------------Q)Explain about realationships(associations) in Data Layer?
=>One record in one table is associated with one or more records of another table.
=>Association between tables( and there by records ) in data layer is created using primary key
and foreign key columns.
=>In data layer we have 3 kinds of associations(relationships).
1.)one-to-one
2.)one-to-many
3.)many-to-one
=>One-to-one relationship is possible in the two ways.
PK => PK
PK => FK(unique)
=>One-to-many and many-to-one relationship is created using FK column which is non-unique.
Hibernate by L N Rao
Page 46
Hibernate
create table account (accno number primary key, name varchar2(20), balance number(9,2));
create table account_plus (accno number primary key, location varchar2(40), type varchar2(20));
create sequence account_seq start with 40001 increment by 1;
create sequence accountplus_seq atart with 40001 increment by 1;
__________________________________________________________________________________________________________
22/11/12
-----------Q)Develop a .......
unidironetoonemappingapplication
Account.java
AccountPlus.java
Account.hbm.xml
AccountPlus.hbm.xml
hibernate.cfg.xml
SessionUtil.java
StoreApplication.java
ReadApplication.java
Account.java
-----------------
package com.nareshit.dao;
public class Account
{
private int accno;
private String name;
private float balance;
AccountPlus accountPlus;
//setters & getters
}
AccountPlus.java
----------------------
package com.nareshit.dao;
public class AccountPlus
{
private int accno;
Hibernate by L N Rao
Page 47
Hibernate
AccountPlus.hbm.xml
--------------------------<hibernate-mapping>
<class name="com.nareshit.dao.AccountPlus" table="Account_Plus">
<id name="accno">
<generator class="sequence">
<param name="sequence">ACCOUNTPLUS_SEQ</param>
</geneator>
</id>
<property name="location"/>
<property name="type"/>
</class>
</hibernate-mapping>
Account.hbm.xml
---------------------<hibernate-mapping>
<class name="com.nareshit.dao.Account" table="Account_Plus">
<id name="accno">
<generator class="sequence">
<param name="sequence">ACCOUNTPLUS_SEQ</param>
</geneator>
</id>
<property name="name"/>
<property name="balance"/>
<one-to-one name="accountPlus" class="com.nareshit.dao.AccountPlus" cascade="save-update">
</one-to-one>
</class>
</hibernate-mapping>
StoreApplication.java
----------------------------
ReadApplication.java
-------------------------Account acc = (Account) session.get(Account.class,40001);
System.out.println(acc.getName());
System.out.println(acc.getBalance());
System.out.println(acc.getAccountPlus().getLocation());
System.out.println(acc.getAccountPlus().getType());
=>cascading indicates to the Hibernate Engine how to deal with associated object(s) when a persistent
object is manipulated.
=>In the mapping tag, for "cascade" attribute any one of the following value can be given.
1.)none
2.)save-update
Hibernate by L N Rao
Page 48
Hibernate
3.)delete
4.)all
5.)delete-orphan
=>"none" is the default value. It indicates to the Hibernate to ignore associated object when persistent
object is saved, updated or deleted.
=>"save-update" indicates to Hibernate to save or update the associated object when the persistent object
is saved or updated.
=>"delete" indicates to HIbernate to delete the associated object when the persistent object is deleted.
=>"all" indicates to Hibernate Engine to save, update or delete the associated object, when persistent
object is saved, updated or deleted.
=>"delete-orphan" value is given to "cascade" attribute in one-to-many relationship between persistent
objects. It indicates to Hibernate to delete the many side object from the database when it is deleted
from one side object at the end of the transaction.
Note:- With comma as a seperator, multiple values can be given to "cascade" attribute.
__________________________________________________________________________________________________________
23/11/12
-------Q)How is One-to-many relationship established between persistent objects in a Hibernate Application.
Step 1:- in One side relationship persistent class declares a collection of Many side persistent objects.
For eg.
public class Department
{
.......
List<Employee> employees;
......
}
Step 2:- In Department.hbm.xml make use of <bag> tag if index column is not specified in the table. If
index is specified then we need to go for <list> tag.
Specify relationship <list> tag. Specify relationship tag as sub tag of <list> or <bag>.
=>RTH
Step 1:- Many side persistent class has instance variable of type One side persistent class.
For eg.
public class Employee
{
....
private Department department;
....
}
Step 2:- In many side persistent class corresponding mapping file i.e. owner of the relationship mapping
file make use of <many-to-one> tag.
=>No two objects with same id value can be associated with Session Object. Otherwise,
NonUniqueObjectException is thrown.
=>merge() is used to merge two different persistent objects representing same record.
sql script
----------
Hibernate by L N Rao
Page 49
Hibernate
using index create table employee(eid number primary key, ename varchar2(12), esal number, idx_column number,
emp_deptno number references dept(deptno));
__________________________________________________________________________________________________________
Hibernate by L N Rao
Page 50