You are on page 1of 50


Q)What is Enterprise Application?
=>Enterprise means a business organisation. For eg. bank,insurance,hospital etc.
=>Any computer application that computerises the business activities of an enterprise is nothing but an
Enterprise Application.
Ex - bank application etc.

Q)What is a Java Enterprise Application?
=>An Enterprise Application is said to be Java based if the following things are used in its implementation.
1.)Programming methodology is Object Oriented
2.)Java Programming Language
4.)Java Application Framework (Struts,Spring,Hibernate)
5.)J2SE & J2EE platforms
=>"Enterprise Application Environment 07-sept-12.bmp"

Q)What are the things to be performed in an Enterprise Application?
1.)Hosting enterprise data in a permanent, secured and easily retrivable manner
2.)Accessing data from the persistent storage
3.)Processing data according to the business rule
4.)presenting data to the end users

Q)What is a layer in the context of a Java Enterprise Application?

=>Logic partition of related components of an enterprise application is nothing but a layer.

Q)What is the architecture of Enterprise Java Application?
=>Java Enterprise Application follows Layered Architecture.
=>Layering is based on the 4 task performed in the application.
=>Any Java Enterprise Application has 4 layers
1.)Data Layer
2.)Data Access Layer
3.)Business Logic Layer (Service Layer)
3.)Presentation Layer

=>Java technology/framework used in each partition of a realtime java project.
"java tech in layers 02-sept-12.bmp"

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

Q) What are not the duties of the service layer.
1.)data accessing from database.
2.)providing interaction to the end user.
-if it will be doing these duties also then the real work of service layer will be diluted
Q) What are the duties of service layer?
1.) upon receiving the data processing request from presentation layer invoking DAO methods for
database operation.
2.) Returning response to the presentation layer.
case 1: processed data or success info of data processing
case 2: propagating the requested data not found exception upon receiving the same from DAL
(Data Access Layer).

Hibernate by L N Rao

Page 1

case 3: propagating data processing exception upon receiving data access exception from DAL
case 4: propagating business rule violation exception
3.) Transaction Management

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

Q)What are not the duties of the Presentation Layer?
=>Duties of the Service Layer and Data Access Layer.

Q)What are the duties of the Presentation Layer?
=>1.)providing input screen to the user
2.)capturing the user input
3.)validating the user input
4.)invoking the business method of business component
5.)producing the response page for the end user
=>presentation layer is divided into --

Q)What are the major elements of a Java Enterprise Application?
=>1.)Web Components
2.)Business Components(Service Objects)
3.)DAO Objects

Q)Explain about collaboration between the layers of an enterprise application.
=>One layer serves its immediate provious layer.
=>one layer does not know about next to next layer. It needs to know only about it's immidiate next layer in
order to use its services.
=>one layer provides services to its immediate previous layer in abstraction.
=>web components collaborate with business components and similarly business components collaborate with DAO
objects with has-a relationship.
=>Application components can not be aware of the previous layer.
=>Between layers loose coupling should be established.
=>Three things contribute in loose coupling between application components.
2.)user defined exceptions
3.)design patterns

Q)Why layer architecture for an enterprise application?

=>layered architecture provides the following benifits.
1.)clear seperation of the three concerns and there by division of labour.Consequesntely, well defined
2.)parallel development of three concerns that lead to RAD.
3.)code optimization.
4.)code reuse
5.)better code maintainance
6.)without affecting one concern the other concern can be modified
7.)multi tier support
-layer is logical division & tier is physical division.
-example of 2-tier architecture - windows based banking applications/projects.

Q)What is a tier in the context of an enterprise application?

=>physical partition of related components of the application is known as tier.
=>Enterprise applications generally have any of the following architectures.
1.)Two tier architecture
2.)Three tier architecture

Hibernate by L N Rao

Page 2

Note:- If business logic is physically seperated from 2 tier architecture it becomes it becomes 3 tier.
Two tier architecture

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


Presentation Layer

Data Access Layer

Service Layer

Data layer developmentdrop table account;
create table account(accno varchar(9),name varchar(30),balance varchar(15));
-n+1 no exception classses(n NotFoundException + 1 common DataAccessException)
data access layer exceptions-
----------------------------package com.nareshit.exception;
public class AccountNotFoundException extends Exception
}//user defined, checked exception

package com.nareshit.exception;
public class DataAccessException extends Exception
}//user defined, checked exception

Hibernate by L N Rao

Page 3

----------package com.nareshit.dao;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtil


}catch(ClassNotFoundException e){

public static Connection getConnection() throws SQLException
return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:server","nareshit",


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


Hibernate by L N Rao

Page 4


-------Q)What are the things to be known about a method in order to invoke it?

1.)fully qualified name(package name) of the type(interface or class) to which it belongs
2.)acessibility mode
3.)return type
5.)wether it is class method(static method) or instance method
6.)checked exceptions specified in exception specification(throws clause)
- layer object's servicing methods are never static (but helper methods can)
- also interface methods can not be static


Q)What is the use of factory classes in a Java enterprise application?
=>Presentation Layer uses ServiceFactory to acquire Service Layer objects(references).
=>Service Layer uses DAOFactory to acquire DAO objects(references).
=>DAO methods use ConnectionFactory(DBUtil) to acquire Connection objects(references).
-container acts as the factory for the presentation layer components.

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 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). Java application framework. Hibernate by L N Rao Page 6 . data accessing partition(layer) of a java project i. Note:-JDBC and Hibernate both are ment for the same purpose. 1. =>Hibernate is not from Sun Microsystems it's from Apache Software Foundations. Q)How is Java Persistence achieved? =>There are two styles of implementing Java Persistence. In fact.Create Retrive Update Delete Q)What is the purpose of Hibernate? =>To perform CRUD operations with database. #CRUD . =>Hibernate is not a standard its only a software product developed by ASF. Q)What are the limitations of the traditional approach of Java Persistence? =>SQL statements are not portable across DBMSs and thereby Java applications.e. back-end communication sake Hibernate is used.Servlet & JSP(but it uses both). =>To perform data accessing in java applications. Q)What is Hibernate? =>Hibernate is an open source.)ORM style ================================================================================================= 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. Q)What is Java Persistence? =>The mechanism of storing the enterprise data(business data) of a java applictaio into the relational databases is nothing but Java Persistence. Q)What is a Hibernate Application? =>A java application that communicates with database(DBMS) using Hibernate is a Hibernate Application. =>Hibernate is used as data accessing mechanism in java appliactions. =>Hibernate is not a specification unlike JDBC.Hibernate 25/09/12 -------- Hibernate --------- Q)What is the purpose of JDBC? =>To perform CRUD operations with database. Every project requires1)data holding/hosting //DBMS peoples's duty -2)data accessing | 3)data processing | //programmer's duty 4)data presentaing | -- Q)What is not Hibernate? =>Hibernate is not a technology unlike JDBC(JDBC is a data access technology from Sun).)Traditional style 2. =>Hibernate is neither J2SE nor J2EE unlike JDBC.

Open JPA etc are other ORM products.1.)Facility to create mapping info (xml tags & annotations) 4.x is mostly used in the industry currently.)facility to create hibernate mapping file 5. =>ORM Engine submits the SQL statement using JDBC to the DBMS.)Hibernate Engine 3.)configuration info =>Depends upon the method.Hibernate is an ORM implementation. 1.Hibernate =>Coding complexities.)A special language to facilitate complex QUERY creation.)complexity in development 2. =>Based on mapping info QUERY contect is generated =>DBMS details are taken from the configuration info to generate the DBMS understandable SQL syntex.)Hibernate API 2. 5. =>Hibernate is ORM Tool. Hibernate by L N Rao Page 7 .)Hibernate QUERY Language 4. =>Hibernate 2. appropriate SQL statement is generated. Vender Lock? Q)What is O/R M style of Java Persistence? =>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. =>ORM Engine uses three things to generate the SQL ststement. ============================================================================================================ ==== 28/09/12 -------Q)What is the architecture of a Hibernate Application? =>refer to "Hibernate Architecture. =>Entity Beans of EJB technologies were used for back-end communication. Q)What is the architecture of ORM approach of Java Persistence? ================================================================================================= 27/09/12 -------Q)How is CRUD operation performed in ORM approach? =>Java Application performs ORM API call. =>Entity Beans had 2 major drawbacks. =>Latest version of Hibernate is 4. =>Hibernate has the following things.)method 2.)mapping info 3.IBatis.bmp" Q)Explain about Hibernate API. Q)What are the elements of ORM approach to perform CRUD operations with the DBMS? 1. 1.7 Q)What are the elements of Hibernate? =>Hibernate is a Java Persistence Framework.)facility to create configuration file (xml tags) Q)How is Hibernate evolved? =>To address JDBC issues Sun Microsystems created EJB technology in order to build data accessing part of Java Projects. 1.)API 2.Oracle Toplink.)facility to create hibernate configuration file Note:. =>ORM Engine generates SQL statement. =>Hibernate 3.)O/R Mapper (mapping tool/engine) 3. =>Mismatches between Object Oriented and Relational principles of data representation can't be handled properly.x was released in 2003.)very bad performance =>Gavin King developed Hibernate in 2001. =>Industry started using Hibernate since 2004.

)API to perform basic CRUD operations =>Hibernate Engine implements Hibernate API. =>It generates SQL statements and sends them to the DBMS using JDBC. Object Oriented representation of data is optional. =>Hibernate Engine abstracts JDBC in Java Applications. 1. @Column(name="BAL") private float =>Hibernate API can be broadly classified into 3 areas. Hibernate configuration file is one per DBMS.NM. =>For each table of the database we must generate a Java class known Persistence class.hbm. =>Standard name for this file is hibernate. =>It is special software written in java.Instance of this class only persisted into the database and hence the name.Hibernate =>A collection of interfaces and classes of org. 3. For eg. =>Collection of all tables is nothing but database of the project.hibernate and its sub packages whose methods are used in Java Application to perform CRUD operations with DBMS is nothing but Hibernate API. =>When Java Application makes Hibernate API call to perform CRUD operation.It is nothing but relational representation of data. @Table(name="MYACCOUNT") public class Account implements java. =>It is the O/R mapping tool.BAL) class:-Account(accno. =>Mapping information is created in special xml file known as Hibernate Mapping file.cfg. Q)Explain about Hibernate configuration file. =>Hibernate Engine uses this file to generate DBMS specific SQL syntax.xml For eg.xml =>DBMS specific details and mapping files details are specified in this file.hbm.Serializable { @Column(name="ANO") private int accno. =>Hibernate Engine is able to generate SQL statement using mapping info created by Hibernate developer. Table:. Account. Object Oriented representation of data is mandatory. 2. Q)Explain about Hibernate Engine. Hibernate mapping files are not required in a Hibernate Application.MYACCOUNT(ANO. @Column(name="NM") private String name. =>Generally.)API to build HQL queries and to send them so as to perform complex CRUD operations. Note:. } public int getAccno() { return accno. =>In ORM approach we need to define one java class per table. Q)Explain about hibernate mapping file. =>If ORM approach is followed.We can have single configuration file for multiple DBMS also. =>Standard for the mapping file is PersistentClassName. =>If mapping information is be provided to Hibernate Engine by applying annotations to persistent classes. =>If JDBC is used to perform CRUD operations in a Java are also known as Entity Classes.xml =>Generally one mapping file per class (persistence class). } public void setName(String nm) Hibernate by L N Rao Page 8 . public void setAccno(int ano) { accno = ano.balance) Q)Develop the Persistent class for the above MYACCOUNT table.These java classes whose instances are stored into the database are known as persistent classes. Hibernate Engine receives the method call and generates the appropriate SQL statement. Q)Explain about Persistent Class.)Criteria API to retrive data from database.

)has Object Oriented alternative for HQL in the form of criteria to retrive data from database 8.NetBeans. } public void setBalance(float bal) { balance = bal. For eg.)provides implicit connection pooling facility 5.)provides transaction support 6. above Account class is a POJO because it is not inheriting any library interface or class of any java technology or framework.)address O/R mismatch problems effectively ================================================================================================= 02/10/12 -------Q)What are the system requirements to develop Hibernate Applications? 1.)provides portability of data accessing across DBMSs 13. Q)How to develop a basic Hibernate Application that performs a CRUD opertaion with the DBMS? Step 1:.Develop a Mappig file Step 3:. =>A java class is said to be a POJO if does not inherit from library interface or class of any java technology or framework.Make use of Hibernate programming model to perform the CRUD operation Q)What is Hibernate Programming Model? Hibernate by L N Rao Page 9 .)provides fine grained exception handling support 9. MyEclipse. for eg. } }//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).)Install Hibernate Framework 3.)maintains synchronization between persistent objects and corresponding relational records. 3.Hibernate { name = nm.)Install J2SE platform(JDK) 2.)support dirty checking 14.)Place all the jar files of Hibernate & JDBC driver jar file into the CLASSPATH OR/AND Install an IDE. Step 2:.Develop the configuration file Step 4:.)has a special query language HQL that supports complex CRUD operations 7.)disburdens the developer from writing boiler plate code to perform CRUD operations and reduce complexity involved in database operations 12.)runs both in managed and nonmanaged environment 11.)generates fine tuned SQL statements 10. ======================================================================================================= 01/10/12 -------Q)What is Hibernate Architecture? =>"Hibernate arch 01-10-12.Develop a persistence class corresponding to the database table. } public String getName() { return name.bmp" Q)What are the features of Hibernate? 1.)provides Java object's implicit persistence. } public void getBalance() { return balance. make driver jar file available to MyEclipse. 4.)provides caching mechanism 2.

hbm.OracleDialect</property> <mapping resource=""/Account. application should display the same. private float balance. =>In mapping file at least one instance variable of the persistence class should be made as unique field.)dialect corresponding to the DBMS 3.password">nareshit</property> <property name="dialect">org.username">nareshit</property> <property name="connection. "table" attribute not required in <class> tag as Hibernate by default assumes TABLE NAME and persistence class name as same. readapplication Data Layer:- Account.xml ----------------<hibernate-configuration> <session-factory> <property name="connection. =>"accno" variable corresponds to "ANO" column of MYACCOUNT. //setters & getters }//persistence class(POJO) Note:. If account doesn't exist with that account number.nareshit.dialect. private String name.cfg.Account class is coressponding to MYACCOUNT ------------ package com.OracleDriver</property> <property name="connection. "column" attribute not required in <id> tag and <property> tag if instance variable names and corresponding column names are the same.xml hibernate.xml --------------<hibernate-mapping> <class name="com.BAL) Account.hbm. <id> tag is used for this purpose. configuration file development -----------------------------=>In this file for this application we specify three pieces of information. =>Similarly. =>In the table which column is a primary key column that corresponding instance variable is described using <id> tag in mapping file.cfg.NM.hibernate.)mapping file name hibernate.dao.nareshit. =>Similarly. public class Account { private int accno.dao. 1. Account.url">jdbc:oracle:thin:@localhost:1521:server</property> <property name="connection.)database connection details MYACCOUNT(ANO.Account" table="MYACCOUNT"> <id name="accno" column="ANO"/> <property name="name" column="NM"/> <property name="balance" column="BAL"/> </class> </hibernate-mapping> Note:.xml ReadApplication.bmp" =================================================================================================03-oct-12 --------- Q)Develop a Hibernate Application that retrives an account details from the database and displays the Account.Hibernate =>refer to "Hibernate Programming Model 2-oct-12.xml> Hibernate by L N Rao Page 10 .driver_class">jdbc. "name" is "NM" and "balance" is to "BAL".If table name & class name are the same.

} } Note:.getBalance()).hbm.SessionFactory.println("Account doesn't exist"). if(acc==null) { System.get(Account.out.cfg. import Account.Session.println("A/C no.: "+acc.Session.hibernate. class ReadApplication { public static void main(String args[]) { Configuration c = new Configuration(). ---------------------import Note:-POJO.Account.Transaction.nareshit. import com.jar file into the classpath before compiling the above application. System. } else { System. c.hibernate.cfg. class DeleteApplication { public static void main(String args[]) Hibernate by L N Rao Page 11 .configure(). deleteapplication Account. import org. import -------------------- import org.buildSessionFactory().SessionFactory.1001).hibernate.out.: "+acc. import org.getName()).dao.xml DeleteApplication.dao. =>place all the jar files of the Hibernate software into classpath before executing the above application.mapping file and configuration file from the previous application.Configuration. // 2 xml files are loaded SessionFactory sf = c.openSession(). } session.println("Balance Rs. DeleteApplication.out.Place Hibernate3.println("A/C holder name: "+acc. =>javac -d .nareshit.xml hibernate. Account acc = (Account)session. Session session = sf. import org.out. Q)Develop a hibernate application that prompt the end user to enter the account number and deletes that record from the database.Account.hibernate.getAccno()).hibernate.close().hibernate. *.Hibernate </session-factory> </hibernate-configuration> ============================================================================================================ ==== 04/10/12 -------ReadApplication.close(). import org.

Transaction txn = session.setName("Rama").If we are performing insertion. class UpdateApplication { Hibernate by L N Rao Page 12 .commit().1001). System.beginTransaction(). Account acc = (Account) ----------------Account acc = new Account().Account.out.println("Account Deleted successfully").deletion or updation Transaction has to be created and System. session.Configuration. if(acc==null) { System.SessionFactory. ================================================================================================= 05/10/12 -------Q)Develop a Hibernate Application that increases the specified account by the specified amount in the database.close(). insertapplication import org.xml UpdateApplication. Account.class.cfg. // 2 xml files are loaded SessionFactory sessionFactory = configuration.beginTransaction(). import org.hibernate.setBalance(5600f). import java. Session session = sessionFactory.println("object persisted"). txn. acc.commit(). } else { Transaction txn = session. import org. configuration.openSession().println("Account doesn't exist"). acc.out.Session.xml hibernate. session. import com.hbm. } session.Hibernate { } Configuration configuration = new Configuration() ---------------------- Account.get(Account.close().Scanner.cfg.hibernate.delete(acc). import org.setAccno(1001).Transaction. updateapplication UpdateApplication. txn.nareshit.configure(). sessionFactory. } Note:.

} session.openSession().in). =>Configuration object serves two purposes. to create the object of SessionFactory.hibernate.bmp" Q)What happens in the background when get() method of Session is executed? =>Hibernate Engine recieves the method call and generates appropriate SQL statement(select statement) with the help of method name being called. int ano = s.out. txn.buildSessionFactory(). sessionFactory. .configure(). Q)What is the prototype of get() method? public Object get(java.Serializable)throws HibernateException -runtime context of the loaded class ============================================================================================================ ==== 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... configuration.print("Enter the depositing amount Rs.cfg.commit(). =>Hibernate Engine processes ResultSet record. Session session = sessionFactory.out.out. ->"get() method 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 .close(). =>Hibernate Engine submits the select statement using JDBC API. 1. =>When persistence object is associated with .. acc. float bal = acc.dialect and mapping file. if(acc==null) { System.get(Account. HIbernate engine implicitely generates UPDATE SQL statement and submits to the DBMS using JDBC.)loading hibernate configuration file and mapping file into memory and making them available to Hibernate Engine.out.nextInt(). } } Q)Explain about "Configuration" of a Hibernate Application? => float amt = s. } else { Transaction txn = session. Account acc = (Account)session.close().Configuration is a library class of Hibernate API.:"). Configuration configuration = new Configuration().println("Enter the A/C no:"). creates the instance of persistence class and populates its fields with ResultSet data(database data).. System. System. // 2 xml files are loaded SessionFactory sessionFactory = configuration.e...ano).nextFloat().beginTransaction(). System.Class. float newbal = bal+amt. i. 2.lang.getBalance().)acting as a factory of SessionFactory. =>If persistence object state is modified and when commit() method is called on Session object..setBalance(newbal).Hibernate public static void main(String args[]) { Scanner s = new Scanner(System. Therefore.println("Account Updated successfully").println("Account doesn't exist").

dialect package. Q)Explain about Session in Hibernate.Hibernate using JDBC and therefore. =>for each DBMS that Hibernate has support for communication.Transaction interface. We say. =>SessionFactory is thread-safe. Hibernate takes the help of dialect Hibernate by L N Rao Page 14 . . =>dialect class holds SQL syntax details of one DBMS. =>In every DAO method Session object is created. =>When Hibernate Application makes a method call for a CRUD =>SessionFactory is heavy weight object(?). =>Transaction is library interface of Hibernate API. =>Session object is light weight.close(). =>SessionFactory's main purpose is creating Session objects for the application. We say. 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.b/c it's not thread safe storeAccount() { //create Session object here b/c local variable is thread safe Session session = sessionFactory. =>Hibernate engine implements org. record is inserted. =>SessionFactory is not a singleton.Session interface.hibernate. =>Hibernate engine implements org. =>Session object is the persistent manager. =>Hibernate engine implements org.. one dialect class is given as a part of Hibernate framework. =>Whenever write operation is performed on the database using Hibernate. session.. =>Transaction object is a singleton per Session. Object is persisted. record is deleted from the database. CRUD operation is performed and it is closed.using. =>SessionFactory object is created only one per DBMS for the entire data access layer. //it's light weight hence no performance burden ( while creating.hibernate.SessionFactory interface. Q)How to visualise the Hibernate Engine generated SQL statement? =>In configuartion file specify "show_sql" property as follows:<property name="show_sql">true</property> Q)Explain about SessionFactory. persisted object is removed. =>dialect is a Java class of org. Transaction object is required in DAO method. =>Session object is not thread-safe.openSession(). =>Session is library interface of Hibernate API.hibernate. ================================================================================================= 09/10/12 -------Q)Explain about dialect in a Hibernate Application. class AccountDAO { //never create Session object here . =>For each DBMS variance will be there in SQL syntax.. as connection is opened with database in auto-commit disabled mode. =>Hibernate applications use Session object only to perform the CRUD operations. =>SessionFactory is library interface of Hibernate API. session.hibernate.closing it inside DAO every method) } deleteAccount() { } findAccount() { } } Q)Explain about Transaction class in Hibernate.

java -hibernate. =>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. Transaction txn = session. acc.e.class. =>A persistent object is said to be in detached state. For eg. acc.commit().commit().get(Account.Data Access Layer files (other files to implement the 5 use-case) =>In AccountDAO class we implement 4 methods each of which performs one CRUD operation. session.setName("Kailash"). =>If the persistent object is in detached state. For eg.)account closing 3.clear(). Account acc = new Account(). session.)transient state (new state) 2.beginTransaction().xml |.//managed state session.class. Q)Explain about detached state of a persisted object. acc. if it is not associated with Session Object but has a matching record in the database.Hibernate class -dialect is abstracting the SQL variances(across the DBMS) from the application Q)Explain about persistent object life cycle.get(Account. =>Persistence object has 3 life cycle states.)account opening 2. Account object is said to be in transient state. Account acc = (Account) Session. //acc becomes detached Transaction txn = session.setAccno(1001).)detached state Q. any data change in the object. =>In the above piece of code.update(acc).java | SessionUtil. =>In every DAO method we need to get Session object (reference).hbm.1001).setBalance(5600).xml | Account.cfg.)withdraw 5. Q)Explain about persistent/managed state of a persistent object. use it in performing CRUD operation Hibernate by L N Rao Page 15 .java *. =>When the persistent object is in managed state it is in sync with the database. i. txn. ____________________________________________________________________________________________________________ ____ 10/10/12 -------Q)Develop a banking application (Hibernate Application) to perform the following operations. Hibernate implicitely updates to the corresponding record. account details bankingapplication Account.1001).)deposit 4.beginTransaction(). //error w'll come txn. For eg. =>A persistent object is said to be in managed state or persistent state if it is associated with Session and has a matching record in the database. 1. Account acc = (Account) Session.)Explain about transient state of persistent object.)persistent state (managed state) 3. =>Persistent object holds enterprise data but not yet persisted using Hibernate is said to be in transient state. it is not in sync with database.

hibernate. session.getTransaction().nareshit.configure().class. Session session = SessionUtil. } public void updateAccount(Account acc) { Session session = SessionUtil.getSession().hibernate. import org.getTransaction().java --------------package the heavy weight SessionFactory object only once 3.SessionFactory. } public static Session getSession() { return sf.begin(). session.openSession().hibernate. public class AccountDAO { public Account findAccount(int ano) { Account acc = null.Session.commit().Session.close().update(acc). cfg. } } AccountDAO.getSession(). session. session. acc = (Account) session.get(Account.ano).)providing Session objects to all the DAO methods SessionUtil.getTransaction(). } public boolean deleteAccount(int ano) Hibernate by L N Rao Page 16 . }//DAO method public void storeAccount(Account acc) { Session session = SessionUtil.commit().getSession().buildSessionFactory(). session.Hibernate and close it. import org. =>SessionUtil class is a utility class (helper class) that ensures the following things for the entire data access layer of the project. import org.cfg.begin().getTransaction(). return acc.dao.close().dao. ---------------package com.nareshit. 1.hibernate. static { Configuration cfg = new Configuration(). sf = cfg. session. import org. session. public class SessionUtil { private static SessionFactory sf.close(). session.)loading meta information only once 2.

Session session = SessionUtil. 1. } } DepositUseCase.getTransaction().nareshit.nareshit.)making DAO classes singletons if required DAOFactory.//PL } } ___________________________________________________________________________________________ 12/10/12 ---------- Hibernate by L N Rao Page 17 .java --------------package com.dao.nareshit. float bal = acc. import com. //SL over System. } session.begin().getSession(). Account acc = findAccount(ano). acc.setBalance(newbal).delete(acc).findAccount(ano).nareshit.DAOFactory.SessionUtil. public class DAOFactory { private static AccountDAO accountDAO = new AccountDAO().Account.close(). float newbal = bal + amt.getTransaction().out.getBalance(). session. import com. flag = true.commit().updateAccount(acc).nareshit. Q)What is the role of DAOFactory in data access layer? *layer methods are never static =>DAOFactory is in general only one class for the entire data access layer. accountDAO. import (PL Plus SL) ------------------import com.getAccountDAO().Hibernate { } } boolean flag = false.dao.AccountDAO. //SL code AccountDAO accountDAO = DAOFactory.println("deposited successfully").)providing DAO objects to their utilizers 2. session. class DepositUseCase { public static void main(String args[]) { //PL code int ano = 1001. =>It serves two purposes.dao. return flag. Account acc = accountDAO. public static AccountDAO getAccountDAO() { return accountDAO.dao. float amt = 500f. //self messaging if(acc!=null) { session.dao.

Account acc = accountDAO.SessionUtil.dao. online deposit use-case is implemented.nareshit. Step 4:.AccountDAO.xml classes hibernate. } } //SL code AccountDAO accountDAO = DAOFactory.nareshit.nareshit.xml com nareshit dao web lib (PL + SL) -------------------- import hibernate configuration file. float bal = acc.class AccountDAO.println("Please collect the cash"). //SL over System.amt. accountDAO.html WEB-INF web.dao. import com.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 .dao.html Hibernate jar files and driver jar file in lib folder.dao. mapping file into "classes" folder.web. import com.class DepositServlet.Hibernate WithdrawUseCase. class WithdrawUseCase { public static void main(String args[]) { //PL code int ano = data access layer files into "classes" folder.out.setBalance(newbal). float amt = 500f. float newbal = bal.Account.updateAccount(acc).jar http://localhost:80801/depositapplication/deposit. acc.class DAOFactory.cfg. import com.//PL Q)How to make use of Hibernate in a Java Web Application? Step 1:.class *.findAccount(ano).nareshit.DAOFactory. Q)Develop a Java Web Application in web component make use of DAO class to perform CRUD operations.xml Account.hbm. depositapplication deposit. Step 2:.xml --------<web-app> <servlet> <servlet-name>deposit</servlet-name> <servlet-class>com.getBalance(). Step 3:.class SessionUtil.getAccountDAO().

html ------------<html> <body bgcolor="cyan"> <center> <h1>Deposit Screen</h1> <form action=". AccountDAO accountDAO = --------------------package com.dao.println("successfully deposited"). test deploy and execute Java Applications./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.getBalance()+amt). import com. if(acc == null) { System. accountDAO.parseFloat(request. 6PM) -------Developing Hibernate application using MyEclipse -----------------------------------------------Q)What is MyEclipse? =>IDE(Integrated Development Environment) =>RAD(Rapid Application Development) tool =>MyEclipse is one of the widely used IDEs in the industry for Java Project development. public class DepositServlet extends GenericServlet { public void service(ServletRequest request. System. Account acc = accountDAO.nareshit.AccountDAO.nareshit. ServletResponse response) { int ano = Integer.parseInt(request.getParameter("accno")).servlet.nareshit. } }//service } Discussion :. float amt = Float. import javax. debug.Account.DAOFactory.Hibernate </web-app> deposit.println("Account does not exist").setBalance(acc. import between the layers of an enterprise application. Colaboration .updateAccount(acc).out.getAccountDAO().getParameter("amount")).*.*. import com. =>Integrated Development Environment is a tool(software) used to develop.nareshit. Hibernate by L N Rao Page 19 . } else { acc.dao.web.dao.findAccount(ano). import com.assisting one another ____________________________________________________________________________________________ 15/10/12(Monday.out.

our Java applications developed using MyEclipse are stored is known as workspace.Hibernate =>NetBeans. Step 2:. Q)What are the differences between HQL and SQL? Hibernate by L N Rao Page 20 .)Web project 3. Q)What is a project in the context of MyEclipse? =>Any Java application developed using MyEclipse is known as a project. Step 1:.)Web Service project 5.JDeveloper. =>Every MyEclipse session is associated with a workspace.Eclipse are some of the other IDEs used for Java application development. 2..)Enterprise application project Q)What are the main components of MyEclipse Enterprise Workbench? 1. _________________________________________________________________________________________________ 17/10/12 -------Q)What are the limitations of Session interface methods in performing CRUD operations? 1.Package creation .JBuilder. =>Using MyEclipse we can develop the following kinds of Java applications(projects) 1.)Can't retrieve multiple persistent objects.)Console Q)How to develop a Java project using MyEclipse? Note:. using non-id field value as search criteria. =>Right click on package explorer ->new ->Java Project ->enter project name Note:.. 4.. 3.)EJB project 4.Create a Java project. =>In a workspace not only Java applications but also environmental information(meta data) is stored (MyEclipse requirement)..)Can't perform bulk updates and bulk deletes.. All our java files are to be placed in this directory.. Q)Develop a Java application(Java project) that displays "Hello World" on MyEclipse console.)Criteria HQL(Hibernate Query Language) ----------------------------Q)What are the similarities between HQL and SQL? =>Both are used to express our persistent requirements to the DBMS. we can't retrieve the persistent object.)Editor 3.. =>We can create as many number of workspace as we want. =>The way we build the query is similar.A standalone Java application(main method program) in MyEclipse context is known as a Java Project.)To retieve single persistence object also we need to specify id field value i.)Can't express required complex criteria to perform the CRUD operation. Q)What is workspace in the context of MyEclipse? =>A master folder in which. 1. ____________________________________________________________________________________________________________ ________ 16/10/12 -------.)Java project 2.RAD.e.MyEclipse creates a directory in master folder(workspace) which is visible in package explorer.)Native SQL 3.)Package Explorer 2. Q)How to overcome the above limitations? =>Using the following.)HQL 2.. Within this directory it creates "src" directory.

create Query interface object Step 3:.Session. HQL is portable. String hql = "SELECT a from Account a WHERE a. Make use of JDBC API.bmp" Step 1:.getName()).getSession(). } session.: "+acc.: "+acc. System. Step 4:.out. import java.getConnection(). public class AccountDAO { public List<Account> findAccounts() { Connection con = null.Bind the parameters if any. readaccountsapplication Account.Query. } Q)Develop a DAO class to have multiple records retrieving ReadAccountApplication.SessionUtil. List<Account> accounts = null.println("Balance Rs. Hibernate by L N Rao Page 21 .hibernate. } for(Account acc : accounts) { System. 3.dao.List. Query query = session.cfg.)SQL in non portable across ReadAccountsApplication.)Syntactical difference 2.createQuery(hql). class ReadAccountsApplication { public static void main(String args[]) { Session session = SessionUtil.hbm.Account. ResultSet rs = ---------------------------import org. Where as. System. Q)How to make use of HQL in a Hibernate Application? =>"HQL 17-oct-12.util.dao. import hibernate.xml Account.Execute the Query(Submitting the query to Hibernate Engine).list(). import com.Build HQL Query Step 2:. import com. Statement st = null.out.close().Hibernate 1.out.getBalance()). List<Account> accounts = query.getAccno()).println("A/C no.xml SessionUtil.balance > 3000".nareshit.)SQL is expressed in terms of tables and corresponding columns where as. HQL query is expressed in terms of persistence classes and their fields.println("A/C holder name: "+acc. ____________________________________________________________________________________________________________ _________ 18/10/12 -------Q)Develop a Hibernate Application that retrieves all the accounts from the database and display their state. try { con = DBUtil.nareshit.

}while(rs. do { Account acc = new Account().Account.add(acc). for(Account acc : accounts) { Hibernate by L N Rao Page 22 .getFloat(3)).st.createQuery("SELECT a FROM Account a").getInt(1)).util.If the above DAO class is used in ReadAccountsApplication.nareshit.dao.setName( it is as follows. import java.List. acc. AccountDAO.list(). List<Account> accounts = query. accounts.getString(2)).setAccno(rs. return { accounts = new ArrayList<Account>().nareshit. if(rs. import org.close(). acc. }//findAccounts() }//DAO class =>list() method of Query class in Hibernate does all the tasks what findAccounts() method does in the above example.executeQuery("SELECT * FROM ACCOUNT"). acc. import com.setBalance(rs. rs = st. } }//try catch(SQLException e) { } finally { DBUtil.close(con. public class AccountDAO { public List<Account> findAccounts() { Session session = SessionUtil.createStatement().next()).java. import com.dao. session.dao. class ReadAccountsApplication { public static void main(String args[]) { AccountDAO accountDAO = new AccountDAO().List. import java.Hibernate st = con.util. Q)Modify the above DAO class so as to use Hibernate API in DAO method.getSession(). } } Note:.Session.findAccounts().java --------------package com. Query query = session. } return accounts.hibernate. List<Account> accounts = accountDAO.AccountDAO.Query. import org.

nareshit. Q)Write a piece of Hibernate code in which.commit().10000. System. import org. . session. Hibernate by L N Rao Page 23 . These are known as the parameters of HQL *.executeUpdate(). BulkDeletesApplication. Query query = session.println(c+" accounts updates"). int c = query.out.. For eg.close(). Query query = session.out.Session.hibernate.begin().commit().. Session session = SessionUtil.createQuery("UPDATE Account a SET a. System.Hibernate } System.getTransaction(). public class BulkUpdatesApplication { public static void main(String args[]) { Session session = SessionUtil. session. =>If question marks are used as place holders in a HQL query. they are known as positional parameters. session.out.. query.begin(). import com.)named parameters Q)Explain about positional parameters.println("A/C holder name: "+acc. in which increase the balances of all the accounts by Rs.: " BulkUpdatesApplication.balance+500").getSession(). System.getTransaction().println("A/C --------------------------- import org..xml SessionUtil.SessionUtil.getAccno()).)positional parameters 2.getName()). bulkupdatesapplication Account.getBalance()). =>In case of positional parameters supplying of the values happen based on their position in the query and hence the name. Q)Explain about parameter binding in a Hibernate Application while using HQL? =>In a HQL query we can have place holders in place of values. positional parameters are used in HQL query.. BulkUpdatesApplication.balance<10000").balance=a.out. =>Supplying values to the place holders is nothing but parameter binding.hibernate.getSession().println("Balance Rs.: "+acc.. } } ____________________________________________________________________________________________________________ ________ 19/10/12 -------Q)Develop a Hibernate Application.getTransaction(). Q)How are parameters classified? 1.executeUpdate(). session.dao. } } Q)Develop a piece of Hibernate code that deletes all the persistence objects from the database whose balance is less than Rs..getTransaction().Query.createQuery("DELETE FROM Account a WHERE a.500.

balance+? WHERE a.mysql. For eg. query.cfgmysql.hibernate.1001). hibernate. query.xml Note:. positional parameters first. query. int c = query.balance+:damount WHERE a.executeUpdate().Account.getTransaction(). session.*. Hibernate by L N Rao Page 24 .)Not flexible while binding the parameters if query is altered at later stage 2.1001).Hibernate Query query = session.commit().setParameter("ano".500f).begin().cfgmysql.)single configuration file for any number of DBMSs.Mapping file.getTransaction().*.1001).dialect.createQuery("UPDATE Account a SET -------------------import com. import org. Query query = session.getTransaction(). But.setParameter(1.)one configuration file per DBMS 2. query. import org.xml Account. persistent class.balance=a.xml hibernate. 1. Q)Develop a Hibernate Application that communicates with Oracle DBMS and MySQL DBMS using "configuration file per DBMS approach".accno=?").hbm.balance=a.setParameter("damount".createQuery("UPDATE Account a SET a. =>Positional parameters have the following drawbacks. query.xml ---------------------- driver class name = com.dao.jdbc. session. Q)Can we mix positional parameters and named parameters in the same HQL query? =>Yes. Q)Which kind of parameters are preferable(named or positional)? =>Named parameters are preferred to positional parameters.oraclecfg.begin().500f).)Readability of the query is not that good and thereby binding of parameters not so convincing.commit().xml source code from earlier applications only.setParameter(0.createQuery("UPDATE Accounts a SET a.nareshit. piece of code ------------Query query = session.oraclecfg.500f).accno=:ano").hibernate. int c = hibernate. session.MySQLDialect ReadApplication. ReadApplication.accno=:ano").setParameter(0. hibernate.balance=a. it is known as a named parameter.balance+? WHERE a.Driver db url = jdbc:mysql://localhost:3306/MySQL user = root password = root dialect = org.setParameter("ano". session. Q)Explain about named parameters? =>If a user defined name prefixed with colon(:) is used as place holder in HQL query.getTransaction().executeUpdate().cfg. ____________________________________________________________________________________________________________ 22/10/12 -------Q)What are the different approaches of a Hibernate application connecting to multiple DBMSs (concurrrently)? 1. multidbmsreadapplication Account.

System. ReadApplication.configure("hibernate. msession.dialect. SessionFactory osf = ocfg. Account acc = (Account)msession.jdbc. mcfg.xml ReadApplication.openSession().close().cfg.println("Balance is Rs.mysql.openSession().jdbc.get(Account. //System. DBUtil.getBalance()).hbm.oraclecfg. "+acc. osf. Session msession = msf.getBalance()).xml Account.driver. Class.1001). import java.MySQLDialect</property> <property name="dialect">org. msf.nareshit.hibernate.out.sql. public class DBUtil { static { try { Class.1001).xml"/> </session-factory> </hibernate-configuration> DBUtil.dialect.cfgmysql.out.println(osession. Session osession = osf. import _________________________________________________________________________________________________________ 25/10/12 -------hibernate.xml ----------------- <hibernate-configuration> <session-factory> <property name="dialect">org.hbm.Driver"). SessionFactroy msf = hibernate.hibernate. ocfg.close().Hibernate public class ReadApplication { public static void main(String args[]) { Configuration mcfg = new Configuration().println("Balance is Rs. Hibernate by L N Rao Page 25 .buildSessionFactory(). acc = (Account)osession.connection()). } } Configuration ocfg = new Configuration().cfg.DriverManager. Q)Modify the above application so as to follow single configuration file -------------------- singleconfigfilereadapplication Account. import java.SQLException.sql.class.dao.OracleDialect</property> <mapping resource="Account. "+acc.close().xml").Connection.OracleDriver") ----------- package com.configure("hibernate. osession.get(Account.forName("com.forName("oracle.sql.xml").buildSessionFactory().close().

"nareshit".getMySQLConnection()). acc = (Account)msession. try { con = DriverManager. try { con = DriverManager. Q)How to deal with exceptions in a hibernate application? =>When DAo methods of DAO classes are using Session interface methods to perform CRUD operations there is a chance of abnormal events occuring i. import com. } }//static initializer public static Connection getOracleConnection() { Connection con = null.close().getBalance()).openSession(DBUtil. for every CRUD operation performed using Session interface method we have Hibernate by L N Rao Page 26 . msession."nareshit").getBalance()).*.getConnection("jdbc:oracle:thin:@localhost:1521:server".openSession(DBUtil. Account acc = (Account) osession."root"). } } Session msession = sf.getConnection("jdbc:mysql://localhost:3306/MySQL"."root".dao. } catch(Exception e) { } return con.DBUtil.close().1001).get(Account."+acc.get(Account. import org.1001).out.out. System. Session osession = sf. -------------------import com. exceptions getting raised.dao. class ReadApplication { public static void main(String args[]) { Configuration cfg = new Configuration(). }//user defined factory method } ReadApplication.cfg."+acc.Account. } public static Connection getMySQLConnection() { Connection con = null.e. import org. =>In DAO method.println("MySQL balance Rs.Hibernate } catch(Exception e) { System. } catch(Exception e) { } return con.*.class.getOracleConnection()).configure(). SessionFactory sf = cfg.println(e). System. =>Dealing with these exceptions is nothing but handling exceptions in hibernate applications.nareshit.println("Oracle balance Rs.buildSessionFactory().nareshit.hibernate.out.hibernate.class. cfg.

DataAccessException { Account acc = null.exception.Hibernate org. public abstract List<Account> findAccounts()throws DataAccessException.AccountNotFoundException.HibernateException catch block.util. } AccountDAOImpl. public abstract Account findAccount(int accno)throws DataAccessException. import com.nareshit. import java.nareshit. public abstract void deleteAccount(int accno)throws DataAccessException. Session session = null.hibernate.nareshit.exception. import com. try { session = -----------------------------package com.hibernate.nareshit. acc = (Account) session. import com. public class AccountDAOImpl implements AccountDAO { public Account findAccount(int accno)throws AccountNotFoundException. } Hibernate by L N Rao Page 27 . import java.util.exception. import org.AccountNotFoundException. public class AccountNotFoundException extends Exception { }//user defined checked exception DataAccessException.nareshit.exception. =>from within the catch block of every DAO method propagate userdefined exception to service ------------------package com. public interface AccountDAO { public abstract void storeAccount(Account acc)throws DataAccessException.Session. import org.HibernateException.class. AccountNotFoundException.AccountNotFoundException.nareshit.get( --------------- package -----------------------------package com.dao.accno). if(acc==null) throw new AccountNotFoundException().dao.DataAccessException.List. public class DataAccessException extends Exception { }//user defined checked exception AccountDAO.AccountNotFoundException. public abstract void updateAccount(Account acc)throws DataAccessException.exception.getSession().nareshit. ____________________________________________________________________________________________________________ _______ 26/10/12 -------Q)Implement exception handling in AccountDAO class.DataAccessException.AccountNotFoundException.exception.hibernate.List. import com.

} } return acc.cfg.cfg. Hibernate by L N Rao Page 28 .AccountNotFoundException{} } __________________________________________________________________________________________________________ 29/10/12 -------Q)Modify the first hibernate example so as to provide mapping information to hibernate engine using annotations. import -----------package hibernate.Account"/> </session-factory> </hibernate-configuration> Account.xml ReadApplication.Table.nareshit. import javax.close(). <mapping class="com.persistence. @Entity @Table(name="MYACCOUNT") public class Account { @Id @Column(name="ANO") private int accno. import javax.Column.xml ----------------- <hibernate-configuration> <session-factory> .java -------------------- =>From the first application as it is.dao.persistence. hibernate.persistence. import javax.AccountNotFoundException{} public void updateAccount(Account acc)throws DataAccessException{} public Account findAccount(int accno)throws ReadApplication.nareshit.. readapplication Account..Hibernate catch(HibernateException e) { throw new DataAccessException(). @Column(name="MN") private String name.persistence.AccountNotFoundException{} public List<Account> findAccounts()throws DataAccessException. @Column(name="BAL") private String balance. } finally { if(session != null) { session..dao. }//findAccount public void storeAccount(Account acc)throws DataAccessException{} public void deleteAccount(int accno)throws DataAccessException.Id.

Step 4:.nareshit. NamedQueryApplication. Step 2:.)java code of DAO methods is mixed with HQL which is not flexible Q)What is a named HQL query? =>Named query overcomes the limitations of anonymous query.xml --------------<hibernate-mapping> <class .> </class> <query name="allaccounts"> SELECT a FROM Account a </query> </hibernate-mapping> AccountDAO.Query.dao.Execute the query. Query query = session. return accounts. =>HQL query is built either in mapping file or in persistence class and given a name to it in case of named query.Create query object.xml hibernate. import org... Q)Develop a hibernate application in Account.util. __________________________________________________________________________________________________________ 30/10/12 -------Q)How to make use of a named HQL query in a Hibernate Application? Step 1:.xml AccountDAO.hbm.close().Hibernate //setters and getters } Q)What is an anonymous HQL query? =>Nameless HQL query are anonymous queries. =>Anonymous queries have the following limitations 1. named query is used. } } Hibernate by L N Rao Page 29 .getNamedQuery("allaccounts"). namedqueryapplication Account. SessionUtil. List<Account> accounts = query.hibernate. import java.getSession(). Step 3:. =>In DAO methods that name is used to execute the query. import org.Step 3 and Step 4 are the same for both annonymous and named HQL query.Build the query either in the mapping file or at the persistent class.cfg.)query is not reusable 2.Bind the parameters if --------------- package com..List.list(). public class AccountDAO { public List<Account> findAccounts() { Session session = SessionUtil.hibernate. hibernate. we need to write the query in a special area known as CDATA -----------package com.println("Number of accounts: "+accounts.cfg. class NamedQueryApplication { public static void main(String args[]) { AccountDAO dao = new AccountDAO().nareshit. for(Account acc : accounts) { SessionUtil. <mapping class="com.xml ----------------- <hibernate-configuration> <session-factory> .SessionUtil.nareshit. Note:. System.nareshit.out.println("Balance : "+ acc. NamedQueryApplication.query="SELECT a FROM Account a WHERE a.findAccounts()<9000 ]]> <![CDATA[SELECT a FROM Account a WHERE a.size()).. List<Account> accounts = dao.xml AccountDAO.println("Name : "+ acc.List.getAccno()).dao.getName()). =>When HQL query is violating the syntactical rules of xml document.Hibernate NamedQueryApplication. } } } 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. <![CDATA[ SELECT a FROM Account a WHERE a.out.. import NamedQueryApplication.util.dao. @Entity @Table(name="myaccount") @NamedQuery(name="allaccounts". import java.. import are from previous application. For eg. System.println("Accno : "+ acc.nareshit.getBalance()). namedqueryannotationapplication Account.balance<:bal") public class Account { @Id Hibernate by L N Rao Page 30 . System.* -------------------------- import com.dao.persistence.out.AccountDAO.balance<:bal]]> Q)Modify the previous hibernate application so as to give mapping info to Hibernate Engine using annotations.Account"/> </session-factory> </hibernate-configuration> Account.

a. } session. //setters & getters } _________________________________________________________________________________________________ 31/10/12 -------Q)Explain about different cases of list() method. String hql1 = "SELECT a.list(). List<Object[]> accdetails = query. Q)Hibernate application on different cases of list() method. Account. the following things are used in HQL queries. Case ii:. list() method returns a collection of Persistent objects. query = session.xml ListMethodsApplication. @Column(name="BAL") private float balance.list().println().out. ListMethodsApplication. Case i:. Case FROM Account a". @Column(name="NM") private String name. } for(Object[] arr : accdetails) { System.xml for(Object[] arr : accdetails) { for(Object v : arr) System. }//main() Q)Hibernate application in which.println(name).hbm.out.createQuery(hql3). List<Float> bals = query. Query query = session.println(arr[0]+"\t"+arr[1]).close(). String hql2 = "SELECT a.No persistent object field is specified in HQL SELECT clause.out.println(v+"\t").One persistent field is specified in SELECT clause of HQL query.more than one persistent field specified in the SELECT clause of HQL query. list() method returns a collection of wrapper objects or Strings depending upon the type of persistent object field. query = session.)Named query Hibernate by L N Rao Page 31 .Object arrays.createQuery(hql1).cfg. List<String> nms = query. list() method returns a collection of java.lang.balance FROM Account a".Hibernate @Column(name="ANO") private int --------------------------- class ListMethodsApplication { public static void main(String args[]) { Session session = SessionUtil. listmethodsapplication Account. for(Float bal : bals) System.list(().createQuery(hql2).getSession().println(bal). for(String name : nms) System.balance FROM Account a". } String hql3 = "SELECT a.out.out.

INSERT INTO EMPLOYEE VALUES(1004.'Singh'. SELECT * FROM EMPLOYEE.10). import org.xml hibernate. private float salary.salary) FROM Employee e GROUP BY e.65OO.'Samules'. COMMIT.Hibernate 2.xml ---------------- <hibernate-mapping> <class name="com.nareshit. DEPTNO NUMBER(3)).salary FROM Employee e ORDER BY e.)maintaining well-formedness of the mapping file while building the named HQL query.xml SessionUtil.hibernate.SessionUtil. SQL script ---------- DROP TABLE EMPLOYEE. INSERT INTO EMPLOYEE VALUES(1001. INSERT INTO EMPLOYEE VALUES(1002.6400.cfg.Session.SALARY NUMBER(9. Hibernate by L N Rao Page 32 .NAME VARCHAR2(12).2).Employee"> <id name="empno"/> <property name="name"/> <property name="salary"/> <property name="deptno"/> </class> <query name="avgsal"> SELECT AVG(e.nareshit.dao.List.'Rama' ------------package com.10).java ------------------------import org.hbm.deptno </query> <query name="ordersal"> <![CDATA[ SELECT e.hibernate.)aggregate function calling in HQL FROM Employee e </query> <query name="groupsal"> SELECT e.dao.)GROUP BY and ORDER BY clauses 4.20). public class Employee { private int empno. private int deptno.hibernate.AVG(e.hbm. } //setters & getters HibernateApplication. import com.67OO.e. import org. INSERT INTO EMPLOYEE VALUES(1003. / hqlapplication Employee.'Rahim'.java Employee. private String Employee.deptno.10).salary DESC ]]> </query> </hibernate-mapping> __________________________________________________________________________________________________________ 01/11/12 -------HibernateApplication.nareshit. CREATE TABLE EMPLOYEE(EMPNO NUMBER(6).

Employee.salary) FROM Employee e GROUP BY e..query="SELECT AVG(e.salary) FROM Employee e") @NamedQuery(name="groupsal".list().dao. System..AVG(e.out.out. Query query = session. this method throws NonUniqueResultException.println("Average salary is Rs.getNamedQuery("groupsal")."+query.Entity.Employee.cfg.. import javax..uniqueResult()). If multiple objects are returned from the query. for(Object[] o : emps) { System. public class HibernateApplication { public static void main(String args[]) { Session session = SessionUtil.close() hibernate.xml"/> </session-factory> </hibernate-configuration> Q)Modify the previous application so as to provide mapping info to Hibernate Engine using annotations.cfg. for(Object[] o : emps1) { System.NamedQueries.out.nareshit. } session. System.nareshit. instead of calling list() HibernateApplication.Id.xml ----------------<hibernate-configuration> <session-factory> .println("NAME SALARY").query="SELECT e. @Entity @NamedQueries( { @NamedQuery(name="avgsal".e.Hibernate import com. it is advisable to call uniqueResult() method on Query List<Object[]> emps1 = query.getNamedQuery("avgsal")..out..list().java package com.query="SELECT e. import javax.hbm.persistence.getSession()..println(o[0]+"\t"+o[1]). <mapping resource="Employee. List<Object[]> emps = query.xml SessionUtil. } query = session.persistence. hibernate. System.println(o[0]+"\t"+o[1]).Whenever there is a chance of getting a single object(single result) from the query.getNamedQuery("ordersal").dao.salary FROM Employee e ORDER BY ------------- lasthqlapplication Employee. import javax.deptno.println("DEPTNO AVG SAL").NamedQuery.salary DESC") }) Hibernate by L N Rao Page 33 . import javax. query = session.persistence.deptno") @NamedQuery(name="ordersal". } } Note:.

... static { Configuration cfg = new Configuration().Session.dao. } //setters & getters hibernate.dao..nareshit. }//user defined method public static Session getThreadLocalSession() { Session session = threadLocal.cfg.xml ----------------- <hibernate-configuration> <session-factory> . <mapping class="com. sf = cfg.Hibernate public class Employee { @Id private int empno. if(session == null) { session = sf.xml Account. private float salary.buildSessionFactory(). import org.hibernate. Hibernate by L N Rao Page 34 .xml SessionUtil.openSession().hbm.hibernate. threadpersessionapplication ThreadLocalApplication.lang.configure(). public class SessionUtil { private static SessionFactory sf.. import org.. import hibernate.hibernate.nareshit. SessionUtil.SessionFactory.ThreadLocal. private String name. private int deptno. threadLocal = new ThreadLocal<Session>()..openSession(). //import java. Account.cfg. }//static initializer public static Session getSession() { return sf. } return session. private static ThreadLocal<Session> threadLocal.set(session).java ---------------package com.get().Employee"/> </session-factory> </hibernate-configuration> ____________________________________________________________________________________________________________ ________ 02/11/12 -------Q)Hibernate application in which one session object per thread is created.Configuration.

=>Criteria API supports compile time checking for the query that we build unlike HQL.i++) System. =>Instance of ThreadLocal class holds other objects(references).accessor -setter .getName()+":"+ SessionUtil.currentThread(). --------------------------- import com.hashCode()).reducing complexity -polymorphism -getter .)Class should not be final. =>Criteria API is an object oriented alternative for HQL to read data from database. MyThread m = new MyThread(). HQL and native SQL are the other ways). ___________________________________________________________________________________________________________ 05/11/12 -------Q)What are the rules/ 1. =>It is a collection class.mutator Q)Why to prevent a class from being inherited? -to make the class immutable -if furhter specialization has no benifits _______________________________________________ Criteria (API) -------------Q)Explain about Criteria in the context of Hibernate.lang. class ThreadLocalApplication { public static void main(String args[]) { for(int i=1.nareshit.out.getName()+":"+ SessionUtil.getThreadLocalSession(). i.setName("child").reusability -abstraction . =>It stores in it Objects with thread name as the key.e.ThreadLocal is java class. =>Crieria API is used only to retrieve the data from the database. Q)What is ThreadLocal? =>java.hashCode()). =>Dynamic query building is flexible with Criteria when compared to HQL.i<=5.start().dao.i<=5. it can't be used for DML operations.i++) System. =>It is one way of querying the database in a Hibernate Application(session methods.getThreadLocalSession(). Hibernate by L N Rao Page 35 .)properties corresponding to table columns -ecapsulation . } } class MyThread extends Thread { public void run() { for(int i=1.out. m.currentThread().code organising -iheriance .println(Thread.Hibernate } }//user defined method ThreadLocalApplication.SessionUtil. } } --We can change the name of "main" thread.println(Thread. 2.

getName()). import com.SessionUtil.out.: "+acc.getAccno()).SessionUtil.Criteria.list(). for(Account acc : accounts) { System. Step 4:.add(criterion). criteriareadapplication CriteriaReadApplication.: "+acc. System. import org. import com.add Criterion object(s) to Criteria object.: "+acc.Criteria.Restrictions.util. import com.Hibernate =>If query is very large. Step 2:.xml Account.out.close(). Q)How to make use of Criteria in a Hibernate Application? Step 1:.dao. import java. import org.hibernate. System.getBalance()).java hibernate.hibernate.getSession(). import org. List<Account> accounts = criteria.getSession().Account.dao.println("A/C no. Step 3:. Q)Develop a Hibernate Application to retrieve all accounts from the database and display their state.println("A/C holder name: "+acc.hbm. Criterion criterion = Restrictions.Criterion. } for(Account acc : accounts) { System.create org.criterion.dao.cfg.hibernate.out.criterion.List. import org. class CriteriaReadApplication { public static void main(String args[]) { Session session = SessionUtil. criteria.dao.nareshit.hibernate.xml"balance".println("Balance Rs.nareshit.println("A/C holder name: "+acc.hibernate.Criteria interface object. import ---------------------------- Account.nareshit.List.nareshit. List<Account> accounts = criteria. import java.getAccno()). Criteria criteria = session.10000f).10.println("A/C no. Hibernate by L N Rao Page 36 .out.criterion.createCriteria(Account.000.Criterion interface object(s).hibernate.hibernate.hibernate.util.list(). import org. class CriteriaReadApplication { public static void main(String args[]) { Session session = SessionUtil.class).class).Account.create one or more org. } Q)Develop a piece of code to retrieve all the accounts whose balance is less than Rs.out.Session. System.getName()). } session. Criteria criteria = session.Session.createCriteria( import list() or uniqueResult() method on Criteria object. Criteria API is difficult to use and HQL is preferable.

10000f). Criterion criterion1 = Criterion criterion2 = n) 2. Step 2:. Q)Explain about pagination in Hibernate. Step 4:. =>Criteria interface has 2 methods to support pagination.add(criterion1).hibernate.hibernate.7000.)setMaxResults(int fixedSize) =>setMaxResults method is used to specify the page size(the maximum nuber of records at a time retrieved i.invoking the list() OR uniqueResult() of Criteria.adding Projection objects to ProjectionList object. List<Account> accounts = criteria.Query interface also has the same methods to implement pagination while using HQL in querying the database in a Hibernate Application. Hibernate by L N Rao Page 37 . Note:.For examples on projection RTH. --scrolling blindness problem + memory + performance problem ____________________________ Q)How to make use of connection pooling in a Hibernate Application.criterion. Q)Explain about projections in Criteria API. the maximum number of persistent objects loaded into the memory) =>setFirstResult method is used to specify the initial record number of each page.Criterion interface and Restrictions interface class belong to org. } Note:. } session. OR Criterion criterion = Restrictions.. //left .adding ProjectionList to Criteria object. __________________________________________________________________________________________________________ 06/11/12 -------no class ___________________________________________________________________________________________________________ 07/11/12 -------no class ________________ 08/11/12 -------Q)How to retrieve all the accounts whose balance between Rs.out.Projection object.close().Hibernate } System.. It is not possible to retrieve few fields and also can't invoke aggregate functions. Step 1:.println("Balance Rs.hibernate. =>Using projections involves the following steps.list(). Step 5:. Step"balance".hibernate. 7000 and 10000.10000f).e. Note :. criteria.between("balance"..criterion package.add(criterion2).ProjectionList object. =>Paging/Pagination is a technique of loading few records into memory at a time when the query retrieves huge number of records.creating org.add(criterion). =>Without projections.getBalance()).. How to implement pagination using Criteria? =>Loading all the records into memory when huge data sets are involved in a query leads to memory as well as performance problems.creating org. 1..criterion. criteria. criteria.: "+acc. list method of Criteria object returns a collection of persistent objects. -------------------------Q)Develop a piece of code to retrieve name and balance of all the accounts using Native SQL. =>hibernate. J2EE container provided connection pool is the most efficient.xml NativeReadApplication.)While communicating with legacy databases.xml Account. =>In such environment. to enable Hibernate provided connection pooling facility.Oracle9Dialect</property> <mapping resource="Account. Q)Modify the above piece of code so as to use named native SQL query. hibernate.)Feature required in the project provided by SQL but not provided by Hibernate.cfg.xml should not have database connection related tags in order to use container provided connection pool. --vendor lock? Q)Develop a Hibernate application in which Native SQL is used to retrieve all the accounts? nativesqlreadapplication Account. it is known as non-managed environment.xml ----------------<hibernate-configuration> <session-factory> <property name=" -------------------------------- SQLQuery query = (SQLQuery)session.As far as possible avoid native Native SQL due to portability reasons.xml"> </session-factory> </hibernate-configuration> ___________________________________________________________________________________________________________ 09/11/12 --------- Native SQL ~~~~~~~~~~ Q)What is 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.Hibernate =>Without J2EE container (For SessionUtil.xml Account. 3. namednativesqlapplication Account.)to call the stored procedure 2.pool_size">5</property> =>Almost all Java Enterprise Applications run in J2EE container. make use of following tag in Hibernate Configuration file hibernate.cfg. =>Native SQL is used in Hibernate Applications in the following scenarios. OR Hibernate by L N Rao Page 38 .java NamedNativeQueryApplication.cfg.xml NamedNativeQueryApplication.hbm.hbm.hibernate.datasource">java:comp/env/myds</property> <property name="dialect"> SessionUtil. 1. web container) if the Java application is running. <property name="connection.cfg. Note:.getNamedQuery("allaccounts").java NativeReadApplication.

out. float avgbal = (Float) query.SQLException.Connection.cfg. import java. query.sql.Hibernate.xml Account.xml SessionUtil.out. public class StoredProcedureApplication { public static void main(String args[])throws SQLException { Session session = SessionUtil.addScalar("avgbal".println("Average balance is Rs. storedprocedureapplication1 hibernate.nareshit."+avgbal). float avgbal = (FLOAT) query. import com. import ------------------------------import org. import StoredProcedureApplication. / Q)Develop a Hibernate Application to call the above stored procedure.uniqueResult().Session.SessionUtil.@NamedSQLQuery annotation to use in persistence class. Hibernate by L N Rao Page 39 .hibernate. Calling aggregate function using native SQL ------------------------------------------Query query = session.getNamedQuery("avg").newbal number) as begin update myaccount set bal=newbal where ano=accno.createSQLQuery("SELECT AVG(bal) AS avgbal FROM MYACCOUNT"). System.getNamedQuery("allaccounts"). System.dao.getSession()."+avgbal) StoredProcedureApplication. Connection con = session.uniqueResult(). mapping file ------------ <sql-query name="avg"> <return-scalar column="avgbal" type="float"/> SELECT AVG(bal) AS avgbal from MYACCOUNT </sql-query> Using anonymous native SQL query -------------------------------- SQLQuery query = session. end. -. //no need to change DAO method if we wnat to //use NamedSQLQuery List<Object[]> accounts = query.FLOAT).println("Average balance is Rs.sql.connection().list(). __________________________________________________________________________________________________________ 10/11/12 -------Calling a strored procedure in a HIbernate Application -----------------------------------------------------Example stored procedure ------------------------ create or replace procedure changeBal(accno number.Hibernate Query query = session.

hibernate.commit().out. session.getTransaction().Hibernate } } CallableStatement cst = con. } } session.getTransaction().executeUpdate() ----------------------------------------- Query query = session. =>Most notable mismatches are Hibernate by L N Rao Page 40 .commit().?)}").out. SQLQuery query = session.hibernate. session.setParameter(1.getTransaction().. query. Q)Modify the above application so as to call the stored procedure in pure hibernate style. import org. public class StoredProcedureNativeSQLApplication { public static void main(String args[]) { Session session = SessionUtil. session.dao.xml --------------<hibernate-mapping> <class .4300f).getTransaction(). query.println("account updated").begin(). session. Account.getTransaction().> </class> <sql-query name="chgbal"> {call changeBal(?.4500f). session.execute()..getTransaction(). System.7300f). cst. cst.setInt(1.prepareCall("{call changeBal(?.1001). Q)Modify the avove application so as to bring portability while calling the stored procedure.close().println("account updated"). session.1001).java ----------------------------------------import org. import com. session.close(). query.setParameter(0. System.SQLQuery. cst.setParameter(1. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 12/11/12 -----------Q)Explain about O/R mismatches.1001).setFloat(2.?)}")..createSQLQuery("{call changeBal(?. StoredProcedureNativeSQLApplication.hbm.commit().begin().begin().getSession(). query. query.SessionUtil.setParameter(0.Session.?)} </sql-query> </hibernate-mapping> StoredProcedureNamedQueryApplication.executeUpdate().getNamedQuery("chgbal").* =>There exists paradigm mismatch(impedence mismatch) between Object Oriented and Relational representation of data in a enterprise application. query. varchar2(12). that table is said to be fine grained.xml SessionUtil.deptno number(3). =>data are(is) both course grained and fine number(6)). granularitymismatchapplication =>RTH page 11 Employee.street varchar2(12). =>Course grained table in RDBMS has no consistent support and therefore almost abandoned. =>By using <component> tag in mapping file this mismatch is addressed.hbm.salary number(8.)Problem of sub types(inheritance mismatch) 3. Q)Explain about "hbm2ddl. }//course grained persistent class =>Object oriented flexibility sake.'7-7-45'.Hibernate 1.40000. =>Persistent class is course grained but corresponding table into which the oebjcts has to be persisted is fine grained.'Hyderabad'. String street. Q)HIbernate Application in which. float salary. }//fine grained class public class Employee { int empno. This is granularity mismatch. String Employee. For eg.'Shiv Bagh'. =>Relative size of data with which we are working is known as granularity.xml GranularityApplication. it is said to be course grained. / Q)What is reverse engineering? =>The process of creating persistent class and mapping file from already created database table is known as reverse engineering in the context of Hibernate. hno varchar2(20).java sql script ---------drop table employee. Address addr. insert into employee values(1001. <property name="hbm2ddl. If no table column is of" property of hibernate configuration file.2).java Address. =>If no data member is a UDT in a persistent class. create table employee(empno number(8). public class Address { String hno. =>If UDT is a data member in a persistent">create</property> OR Hibernate by L N Rao Page 41 .city varchar2(15). granularity mismatch is addressed. select * from employee. String name.)Problem of granularity 2.)problem of relationships(relationship mismatch) Q)Explain about problem of granularity. int pin.'Rama'.500072). =>if UDT is the column type of a table. hibernate. =>This property instructs Hibernate Engine to genarate the Table creation statement and submit to DBMS by using mapping file information. it is said to be course grained. For eg.10. course grained objects are often used in an enterprise application. it is said to be fine grained.

If table is not exixting then any how it will be created.. =>Maintain local copy of already requested data at application side in a Java Enterprise Application is nothing but Caching. =>In relational representation of data i. =>One persistent class declaring a collection of the other persistent objects and vice versa is nothing but many-to-many relationship between persistent objects..This is known as relationship mismatch between object oriented and relational representation of data. If it is there. 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.. even if the table is already exixting.. =>get() performs eager loading.. application developer is responsible to implement caching Hibernate by L N Rao Page 42 . =>get() returns null if search failed. . Whereas load() method performs lazy loading. --persistent class should not be final. --lazy loading concept can not be applied without proxy.. public class Course { List<Student> students. use the already existing table and don't create the new one is the">update</property> =>If "create" value is given to this property.e. =>Caching improves performance.. } Q)How is relationship mismatch addressed in a Hibernate Application? =>In Hibernate Application to address this mismatch..... In mapping file <many-to-many> tag is used and appropriate column of link table is specified. Q)What are the differences between get() and load() method? =>Both are meant for the same purpose. lazy loading of a persistent object is disabled even if load() method is called on the session object. =>If lazy attribute of <class> tag is given "false" value... } public class Student { List<Course> courses... =>If we use JDBC as data access mechanism.Whereas. it will be dropped and new table is created..inheritance mismatch __________________________________________________________________________________________________________ 15/11/12 -------Q)Explain about relationship mismatch in a Hibernate Application.. For eg. many to many relationship doesn't exist between tables. . corresponding persistent object support many-to-many relationship. Note:.Hibernate <property name="hbm2ddl. __________________________________________________________________________________________________________ 16/11/12 -------Q)What is lazy loading in the context of Hibernate? =>If Java application is querying for persistent object. =>Sometimes lazy loading improves performance. .. Whereas load() throws ObjectNotFoundException. =>"update" instructs Hibernate Engine to create table if it is not there. link table is used.For corresponding application refer to the handout page 9. . __________________________________________________________________________________________________________ 14/11/12 ---------not attended -. at database level. Q)Explain about caching mechanism in a Hibernate Application.

=>Refer to the handout. assigned. native. =>Two types of caching exists in Hibernate applications 1. Generators ---------------Q)Explain about generators in the context of Hibernate? =>A generator is a Java class that implements org.Hibernate through coding.)L1(Level 1) cache 2. =>We can specify this generator as follows. Hibernate by L N Rao Page 43 .id. =>refresh method gets modified state of the record to the persistent object. =>When built-in generators are unable to fulfil our application requirement.hibernate. Q)Explain about "assigned" For eg. synchronization doesn't happen between database and persistent object.hibernate. Q)Explain about "increment" generator? =>Increment generator is applied explicitely as follows.bmp" Q)Hibernate applications in which. ___________________________________________________________________________________________________________ 19/11/12 -------- Q)What is the purpose of refresh() method of Session interface? =>When record is externally (outside the Hibernate Application) updated.)user-defined generators =>Hibernate provided generators are known as built-in generators. =>L2 cache is optional unlike L1 and it is externally configurable. For eg. level2 cache is configured. <id name="accno" column="ANO"/> OR <id name="accno" column="ANO"> <generator class="assigned"/> </id> OR <id name="accno" column="ANO"> <generator class="org. Hibernate engine takes generator class's help to get the id field value for the persistent object.IdentifierGenerator interface. =>Any generator purpose is to auto-generate id field value for the persistent object while persisting it into the database. we can have our own developed generator class which is nothing but user defined generators. those changes are not implicitely reflected in the corresponding persistent object. Which is implicitly provided by Hibernate. sequence. hilo etc. =>While persisting the persistent object into the database. =>We have two kinds of generators. =>"caching 16-nov-12.e.Assigned"/> </id> =>For this generator type application only is responsible to assign id field value to the persistent object before it is persisted. i.)built-in generators 2. session.)L2(Level 2) cache =>L1 cache is nothing but Session level cache. 1. increment. =>Hibernate provides caching support without any programming effort in the application side.refresh(acc).

__________________________________________________________________________________________________________ 20/11/12 -------- Q)Explain about hilo generator? =>"hilo" is one of the built-in generators of Hibernate. SQL>CREATE SEQUENCE HIBERNATE_SEQUENCE START WITH 20001 INCREMENT BY"XYZ"). =>The generator method of the org. we should have already created a database object called sequence with a name "hibernate_sequence".Hibernate <id name="accno" column="ANO"> <generator class="increment"/> </id> OR <id name="accno" column="ANO"> <generator class=" =>When save method is called on the Session object. it uses high low(hilo) algorithm to generate the identifier.e.hibernate.commit(). we have to configure as follows. <id name="accno" column="ano"> <generator class="org.setBalance(8900f) =>We can specify "hilo" generator as follows in mapping file. acc.TableHiLoGenerator takes the high value from the table and adds some low value to it and generates some identifier. Q)Explain about "sequence" generator.TableHiLoGenerator"> <param name="table">table name</param> <param name="column">column name</param> </generator> Hibernate by L N Rao Page 44 . HIbernate engine calls generate() method of increment generator. Transaction txn = session.IncrementGenerator"/> </id> =>generate() method of increment generator retrieves max value of id field of already persistent object. =>If we want to use user defined sequence name in the application. =>We can specify user defined table also while configuring the generator class in the mapping System.SequenceGenerator"/> </id> =>If we configure the sequence generator as above.hibernate. java. <id name="accno" column="ANO"> <generator class="sequence"> <param name="sequence">ACCOUNT_SEQUENCE</param> </generator> </id> =>ACCOUNT_SEQUENCE is assumed to have already been created. by default table name "hibernate_unique_key" and its column "next_hi" is taken as default. i. acc. gets the id field value. txn. <id name="accno" column="ano"> <generator class="hilo"/> </id> =>When "hilo" generator class is specified as above.beginTransaction(). increments it by 1 and returns to Hibernate engine.hibernate. Account acc = new Account(). For eg. assigns it to the persistent object and then it is persisted. =>sequence generator is specified as"Account persisted with id: "+id). <id name="accno" column="ANO"> <generator class="org. For eg. We need to create that table with that column in the dbms with some id = session.

sql.setName("ABC").engine.xml class) Loan.hibernate. userdefinedgeneratorapplication Loan. l. Loan l = new Loan(). it is known as user defined generator. System.*.hbm.xml hibernate.getTransaction.xml -----------------<hibernate-mapping> <class name="com. import org. private float loan_amount. =>If data access layer developer generated the generator class explicitely without depending upon the built-in generators.)application specific algorithm is required to be implemented in the auto-generation of id field value.dao.Hibernate </id> Q)Explain about user defined generator . Q)Develop a Hibernate application in which user defined generator is ---------------------------- Session session = SessionUtil.commit().dao.setLoan_amount(45000f). =>For two reasons we go for user defined import java. 1. Hibernate by L N Rao Page 45 . session.hibernate.getTransaction.nareshit.dao.Loan"> <id name="loan_id"> <generator class=" ---------------------------package com.nareshit.SessionImplementor.)when id field has Alpha numerical value. LoanIdGenerator.IdentifierGenerator.getSession().dao. StoreApplication.begin().java -----------package session.nareshit.Object o) { String lid="HDFCLP". import org.LoadIdGenerator"/> </id> <property name="name"/> <property name="loan_amount"/> </class> </hibernate-mapping> StoreApplication.hbm. public class Loan { private String loan_id. //setters & getters } Loan. 2. private String name. class LoanIdGenerator implements IdentifierGenerator { public Serializable generate(SessionImplementor si. import java.println("Loan persisted with id: "+session.

select to_char(loanid_sequence. --<property name="hbm2ddl. =>There is no generator class for "native" generator. rs. ResultSet rs = st. Statement st = con.'FM000000') from dual").next(). Depending upon the underlying DBMS. if the DBMS is Oracle. "sequence" generator is used to auto generate the value for this field. =>This class's generate method internally uses some identity table of DBMS to generate the id value and return to the hibernate engine. =>Association between tables( and there by records ) in data layer is created using primary key and foreign key columns.close().close(). rs. 1. create sequence loanid_sequence start with 1 increment by 1. lid = lid + rs. "identity" generator is used. MS SQL Server.)many-to-one =>One-to-one relationship is possible in the two ways. supported generator class is used. MySQL. st.hibernate.2)).)one-to-one 2. Similarly. PK => PK PK => FK(unique) =>One-to-many and many-to-one relationship is created using FK column which is non-unique.Hibernate try { Connection con = si. DB2 and Sybase support this generator. } } } catch(Exception e) { e. con.printStackTrace().nextval. ___________________________________________________________________________________________________________ 21/11/12 -------Q)Explain about IdentityGenerator? =>org.executeQuery("select to_char(loanid_sequence. Hibernate by L N Rao Page 46 .close(). ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Relationships -----------------Q)Explain about realationships(associations) in Data Layer? =>One record in one table is associated with one or more records of another table. } return lid.'FM000000') from varchar2(12).loan_amount number(9.)one-to-many 3.connection() <id name="accno" column="ano"> <generator class="identity"/> </id> Q)Explain about "native" generator? =>If we specify "native" as the generator in mapping file.getString(1). =>In data layer we have 3 kinds of associations(relationships). if MySQL DBMS is used. =>Oracle does not support this">create</property> sql script ---------- create table loan(loan_id varchar2(12) primary key.IdentityGenerator is the built in class for this generator.

.)uni directional relationship AccountPlus..hbm...2)).xml SessionUtil.)one to many 3.xml hibernate. 1.)one to one 2.Entity relationship has directionality as well. AccountPlus accountPlus. @OneToMany. uni-directional one to one relationship is established between persistent objects(using PK column). we can navigate the details of its associated persistent object(if relationship is created).nareshit. create sequence accountplus_seq atart with 40001 increment by 1. Step 2:. unidironetoonemappingapplication Account.. public class AccountPlus { private int accno.. OR Apply relationship specifying annotations to the persistent class. type varchar2(20)). public class Account { private int accno. Step 1:. create sequence account_seq start with 40001 increment by 1. //setters & getters } AccountPlus.many-to-many relationship support is inherentely not there in data layer. 1. Q)Explain about persistent object's association(entity relationships) in Data Access layer? =>Given a persistent StoreApplication.)many to many =>Two steps are involved in creating entity relationship.Hibernate Note:.dao.xml AccountPlus.make use of appropriate relationship tag in the corresponding mapping file. location varchar2(40).nareshit. name varchar2(20). =>There are 4 kinds of relationship possible between persistent objects of data access layer. @OneToOne Note:. balance number(9. __________________________________________________________________________________________________________ 22/11/12 -----------Q)Develop a . SQL Script ---------- create table account (accno number primary ReadApplication. private String ----------------- package com.dao. Hibernate by L N Rao Page 47 .java ---------------------- package com. create table account_plus (accno number primary key.hbm.cfg.)many to one 4. private float balance. For eg.)bidirectional relationship Q)Develop a Hibernate Application in which.In one persistent class declare other persistent class reference (or collection) as a data member.

println(acc.setName("ABC").out.getSession(). session.getName()).getBalance()).get(Account.setBalance(5600f).println(acc. ReadApplication.getTransaction().out. acc. session. System.getAccountPlus().nareshit.getLocation()). Account acc = new Account(). System.begin().getTransaction().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. System. acc.AccountPlus" cascade="save-update"> </one-to-one> </class> </hibernate-mapping> ---------------------------- Session session = SessionUtil.hbm.nareshit. Q)Explain about cascading in the context of persistent object associations.dao.nareshit.out.getAccountPlus().java -------------------------Account acc = (Account) session. session.commit().class. private String type.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.close().Hibernate } private String location.dao.println(acc.xml --------------------------<hibernate-mapping> <class name="com. aplus. =>cascading indicates to the Hibernate Engine how to deal with associated object(s) when a persistent object is manipulated. aplus.setLocation("HYD"). //setters & getters AccountPlus.)save-update Hibernate by L N Rao Page 48 . =>In the mapping tag.println(acc. session. for "cascade" attribute any one of the following value can be given.xml ---------------------<hibernate-mapping> <class name="com.dao. acc.setType("savings"). 1. AccountPlus aplus = new AccountPlus().setAccountPlus(aplus).out.)none 2.getType()).hbm.

.. =>No two objects with same id value can be associated with Session Object.For example application RTH. Specify relationship <list> One side relationship persistent class declares a collection of Many side persistent objects. sql script ---------- drop table employee. .. } Step 2:.clear()... public class Department { .In Department. =>"delete-orphan" value is given to "cascade" attribute in one-to-many relationship between persistent objects. create table employee(eid number primary key. __________________________________________________________________________________________________________ 23/11/12 -------Q)How is One-to-many relationship established between persistent objects in a Hibernate Application. . For eg. ename varchar2(12). public class Employee { .. If index is specified then we need to go for <list> tag.In many side persistent class corresponding mapping file i. updated or deleted.e..With comma as a seperator. private Department department. multiple values can be given to "cascade" attribute.. NonUniqueObjectException is thrown.. It indicates to the Hibernate to ignore associated object when persistent object is saved. Q)Explain about merge() method. Step 1:. session. List<Employee> employees. Note:.Many side persistent class has instance variable of type One side persistent class. Note:... =>"delete" indicates to HIbernate to delete the associated object when the persistent object is deleted. =>evict() detaches only a particular object. Q)Develop a Hibernate Application on many-to-one relationship implementation. updated or deleted. Otherwise. =>merge() is used to merge two different persistent objects representing same record.. =>Clear detaches all the objects.)delete 4. owner of the relationship mapping file make use of <many-to-one> tag. =>"save-update" indicates to Hibernate to save or update the associated object when the persistent object is saved or updated. } Step 2:. For eg. esal number. Q)Explain about clear() and evict() methods of Session interface.)delete-orphan =>"none" is the default value.Hibernate 3.xml make use of <bag> tag if index column is not specified in the table.. 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.. Specify relationship tag as sub tag of <list> or <bag>. =>RTH Step 1:.hbm...)all 5. update or delete the associated object. Hibernate by L N Rao Page 49 . when persistent object is saved. emp_deptno number references dept(deptno)). =>"all" indicates to Hibernate Engine to save. session.evict(acc).

ename varchar2(12).Hibernate using index create table employee(eid number primary key. emp_deptno number references dept(deptno)). idx_column number. esal number. __________________________________________________________________________________________________________ Hibernate by L N Rao Page 50 .