Hibernate by l n rao

1,913 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,913
On SlideShare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
Downloads
185
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Hibernate by l n rao

  1. 1. Hibernate Hibernate by L N Rao Page 1 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 3.)Java/J2EE 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" 13/09/12(6:15PM) ---------------- Q) Explain about service layer of an Enterprise Java Application. => A collection of Java class files which are exclusively performing data processing tasks of the enterprise application is nothing but service layer. => For each service provided to the end user implementation is encapsulated in this partition of the application and hence the name. =>Programmatical realization of business rules of the enterprise is nothing but businness logic. => In an enterprise application business logic only processes data. Therefore, service layer is also known as business logic layer. - business rules converted into the programmatic instructions is nothing but business logic. 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).
  2. 2. Hibernate Hibernate by L N Rao Page 2 case 3: propagating data processing exception upon receiving data access exception from DAL case 4: propagating business rule violation exception 3.) Transaction Management ============================================================================================================ ======= 14/09/12 -------- Q)What is Presentation layer? =>That partition of Java Enterprise Application which takes care of the end-user interaction. =>presentation layer is also known as UI layer. 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. 1.)interfaces 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 roles. 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
  3. 3. Hibernate Hibernate by L N Rao Page 3 Note:- If business logic is physically seperated from 2 tier architecture it becomes it becomes 3 tier. Two tier architecture --------------------- ============================================================================================================ ===== 17/09/12 -------- Q)Develop a Java application that has 4 layers.Provide the following services through that application. 1.)account opening service 2.)account closing service 3.)withdraw service 4.)deposit service 5.)balance enquiry service Data Layer ---------- Account(accno,name,balance) Presentation Layer ------------------ WithdrawUseCase.java DepositUseCase.java AccountOpeningUseCase.java AccountClosingUseCase.java BalanceEnquiryUseCase.java Data Access Layer ---------------- AccountNotFoundException DataAccessException.java Account.java Service Layer ------------- AccountService.java ProcessingException.java InsufficientFundsException.java Data layer development- drop 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- AccountNotFoundException.java ----------------------------- package com.nareshit.exception; public class AccountNotFoundException extends Exception { }//user defined, checked exception DataAccessException.java ------------------------ package com.nareshit.exception; public class DataAccessException extends Exception { }//user defined, checked exception
  4. 4. Hibernate Hibernate by L N Rao Page 4 DBUtil.java ----------- package com.nareshit.dao; import java.sql.SQLException; import java.sql.Connection; import java.sql.DriverManager; public class DBUtil { static { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); }catch(ClassNotFoundException e){ // } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:server","nareshit", "nareshit"); } } ============================================================================================================ ==== 18/09/12(6:07) -------- Q)What are the different ways of representing data in a Java Enterprise Application? 1.)Relational format 2.)Object Oriented format =>data permanence(persistence) sake represented in relational format in data layer. =>to process and present the same data in a flexible manner , represented in Object Oriented format. -DTO is also known as Value Object.DTO is a design pattern. Account.java(DTO) ----------------- package com.nareshit.vo; public class Account { int accno; String name; float balance; //setters & getters } -DTO class is necessary in Hibernate application unlike JDBC application =>DTOs are POJOs(Plain Old Java Object classe). =>A java class is said to be a POJO class if it does not inherit from any technlogy specific or framework specific java interface or java class. Note:- Every POJO class of java enterprise application need not be a DTO.Each layer classes can be POJOs. ================================================================================================= 20/09/12 -------- AccountDAO.java --------------- ProcessingException.java ------------------------ InsufficientFundsException --------------------------
  5. 5. Hibernate Hibernate by L N Rao Page 5 AccountService.java ------------------- ================================================================================================= 22/09/12 -------- 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 4.)signature 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 =================================================================================================24/09/12 -------- WithdrawUseCase.java -------------------- AccountOpeningUseCase.java -------------------------- 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. =================================================================================================
  6. 6. Hibernate Hibernate by L N Rao Page 6 25/09/12 -------- Hibernate --------- Q)What is the purpose of JDBC? =>To perform CRUD operations with database. =>To perform data accessing in java applications. #CRUD - Create Retrive Update Delete Q)What is the purpose of Hibernate? =>To perform CRUD operations with database. =>Hibernate is used as data accessing mechanism in java appliactions. Note:-JDBC and Hibernate both are ment for the same purpose. Q)What is a Hibernate Application? =>A java application that communicates with database(DBMS) using Hibernate is a Hibernate Application. In fact, data accessing partition(layer) of a java project i.e. back-end communication sake Hibernate is used. Every project requires- 1)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). =>Hibernate is not a specification unlike JDBC. =>Hibernate is neither J2SE nor J2EE unlike JDBC,Servlet & JSP(but it uses both). =>Hibernate is not from Sun Microsystems it's from Apache Software Foundations. =>Hibernate is not a standard its only a software product developed by ASF. Q)What is Hibernate? =>Hibernate is an open source, Java application framework. =>Hibernate is a software product to be installed into a computer system in order to use it to build data access layer of Java enterprise application(realtime java project). 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)How is Java Persistence achieved? =>There are two styles of implementing Java Persistence. 1.)Traditional style 2.)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 are the limitations of the traditional approach of Java Persistence? =>SQL statements are not portable across DBMSs and thereby Java applications.
  7. 7. Hibernate Hibernate by L N Rao Page 7 =>Coding complexities. =>Mismatches between Object Oriented and Relational principles of data representation can't be handled properly. 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. 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. =>ORM Engine generates SQL statement. =>ORM Engine uses three things to generate the SQL ststement. 1.)method 2.)mapping info 3.)configuration info =>Depends upon the method, appropriate SQL statement is generated. =>Based on mapping info QUERY contect is generated =>DBMS details are taken from the configuration info to generate the DBMS understandable SQL syntex. =>ORM Engine submits the SQL statement using JDBC to the DBMS. Q)What are the elements of ORM approach to perform CRUD operations with the DBMS? 1.)API 2.)O/R Mapper (mapping tool/engine) 3.)Facility to create mapping info (xml tags & annotations) 4.)A special language to facilitate complex QUERY creation. 5.)facility to create configuration file (xml tags) Q)How is Hibernate evolved? =>To address JDBC issues Sun Microsystems created EJB technology in order to build data accessing part of Java Projects. =>Entity Beans of EJB technologies were used for back-end communication. =>Entity Beans had 2 major drawbacks. 1.)complexity in development 2.)very bad performance =>Gavin King developed Hibernate in 2001. =>Hibernate 2.x was released in 2003. =>Industry started using Hibernate since 2004. =>Hibernate 3.x is mostly used in the industry currently. =>Latest version of Hibernate is 4.1.7 Q)What are the elements of Hibernate? =>Hibernate is a Java Persistence Framework. =>Hibernate is ORM Tool. =>Hibernate has the following things. 1.)Hibernate API 2.)Hibernate Engine 3.)Hibernate QUERY Language 4.)facility to create hibernate mapping file 5.)facility to create hibernate configuration file Note:- Hibernate is an ORM implementation.Oracle Toplink,IBatis,Open JPA etc are other ORM products. ============================================================================================================ ==== 28/09/12 -------- Q)What is the architecture of a Hibernate Application? =>refer to "Hibernate Architecture.bmp" Q)Explain about Hibernate API.
  8. 8. Hibernate Hibernate by L N Rao Page 8 =>A collection of interfaces and classes of org.hibernate and its sub packages whose methods are used in Java Application to perform CRUD operations with DBMS is nothing but Hibernate API. =>Hibernate API can be broadly classified into 3 areas. 1.)API to build HQL queries and to send them so as to perform complex CRUD operations. 2.)Criteria API to retrive data from database. 3.)API to perform basic CRUD operations =>Hibernate Engine implements Hibernate API. =>When Java Application makes Hibernate API call to perform CRUD operation, Hibernate Engine receives the method call and generates the appropriate SQL statement. Q)Explain about Hibernate Engine. =>It is special software written in java. =>It is the O/R mapping tool. =>It generates SQL statements and sends them to the DBMS using JDBC. =>Hibernate Engine abstracts JDBC in Java Applications. Q)Explain about Hibernate configuration file. =>Standard name for this file is hibernate.cfg.xml =>DBMS specific details and mapping files details are specified in this file. =>Hibernate Engine uses this file to generate DBMS specific SQL syntax. =>Generally, Hibernate configuration file is one per DBMS.We can have single configuration file for multiple DBMS also. Q)Explain about hibernate mapping file. =>Hibernate Engine is able to generate SQL statement using mapping info created by Hibernate developer. =>For each table of the database we must generate a Java class known Persistence class. Note:- Instance of this class only persisted into the database and hence the name. =>Mapping information is created in special xml file known as Hibernate Mapping file. =>Standard for the mapping file is PersistentClassName.hbm.xml For eg. Account.hbm.xml =>Generally one mapping file per class (persistence class). =>If mapping information is be provided to Hibernate Engine by applying annotations to persistent classes, Hibernate mapping files are not required in a Hibernate Application. Q)Explain about Persistent Class. =>If JDBC is used to perform CRUD operations in a Java project, Object Oriented representation of data is optional. =>If ORM approach is followed, Object Oriented representation of data is mandatory. =>Collection of all tables is nothing but database of the project.It is nothing but relational representation of data. =>In ORM approach we need to define one java class per table.These java classes whose instances are stored into the database are known as persistent classes.These are also known as Entity Classes. For eg. Table:- MYACCOUNT(ANO,NM,BAL) class:-Account(accno,name,balance) Q)Develop the Persistent class for the above MYACCOUNT table. @Table(name="MYACCOUNT") public class Account implements java.io.Serializable { @Column(name="ANO") private int accno; @Column(name="NM") private String name; @Column(name="BAL") private float balance; public void setAccno(int ano) { accno = ano; } public int getAccno() { return accno; } public void setName(String nm)
  9. 9. Hibernate Hibernate by L N Rao Page 9 { name = nm; } public String getName() { return name; } public void setBalance(float bal) { balance = bal; } public void getBalance() { return balance; } }//persistent class -table name and class name need not be same -variable name and column name need not be same -variables need not be private =>Persistent classes are POJOs(Palin Old Java Object classes). =>A java class is said to be a POJO if does not inherit from library interface or class of any java technology or framework. For eg. above Account class is a POJO because it is not inheriting any library interface or class of any java technology or framework. ======================================================================================================= 01/10/12 -------- Q)What is Hibernate Architecture? =>"Hibernate arch 01-10-12.bmp" Q)What are the features of Hibernate? 1.)provides caching mechanism 2.)maintains synchronization between persistent objects and corresponding relational records. 3.)provides Java object's implicit persistence. 4.)provides implicit connection pooling facility 5.)provides transaction support 6.)has a special query language HQL that supports complex CRUD operations 7.)has Object Oriented alternative for HQL in the form of criteria to retrive data from database 8.)provides fine grained exception handling support 9.)generates fine tuned SQL statements 10.)runs both in managed and nonmanaged environment 11.)disburdens the developer from writing boiler plate code to perform CRUD operations and reduce complexity involved in database operations 12.)provides portability of data accessing across DBMSs 13.)support dirty checking 14.)address O/R mismatch problems effectively ================================================================================================= 02/10/12 -------- Q)What are the system requirements to develop Hibernate Applications? 1.)Install J2SE platform(JDK) 2.)Install Hibernate Framework 3.)Place all the jar files of Hibernate & JDBC driver jar file into the CLASSPATH OR/AND Install an IDE, for eg. MyEclipse,NetBeans. make driver jar file available to MyEclipse. Q)How to develop a basic Hibernate Application that performs a CRUD opertaion with the DBMS? Step 1:- Develop a persistence class corresponding to the database table. Step 2:- Develop a Mappig file Step 3:- Develop the configuration file Step 4:- Make use of Hibernate programming model to perform the CRUD operation Q)What is Hibernate Programming Model?
  10. 10. Hibernate Hibernate by L N Rao Page 10 =>refer to "Hibernate Programming Model 2-oct-12.bmp" =================================================================================================03-oct-12 --------- Q)Develop a Hibernate Application that retrives an account details from the database and displays the same. If account doesn't exist with that account number, application should display the same. readapplication Account.java Account.hbm.xml hibernate.cfg.xml ReadApplication.java Data Layer:- MYACCOUNT(ANO,NM,BAL) Account.java ------------ package com.nareshit.dao; public class Account { private int accno; private String name; private float balance; //setters & getters }//persistence class(POJO) Note:- Account class is coressponding to MYACCOUNT table. =>"accno" variable corresponds to "ANO" column of MYACCOUNT. =>Similarly, "name" is "NM" and "balance" is to "BAL". Account.hbm.xml --------------- <hibernate-mapping> <class name="com.nareshit.dao.Account" table="MYACCOUNT"> <id name="accno" column="ANO"/> <property name="name" column="NM"/> <property name="balance" column="BAL"/> </class> </hibernate-mapping> Note:- If table name & class name are the same, "table" attribute not required in <class> tag as Hibernate by default assumes TABLE NAME and persistence class name as same. =>Similarly, "column" attribute not required in <id> tag and <property> tag if instance variable names and corresponding column names are the same. =>In mapping file at least one instance variable of the persistence class should be made as unique field. <id> tag is used for this purpose. =>In the table which column is a primary key column that corresponding instance variable is described using <id> tag in mapping file. configuration file development ------------------------------ =>In this file for this application we specify three pieces of information. 1.)database connection details 2.)dialect corresponding to the DBMS 3.)mapping file name hibernate.cfg.xml ----------------- <hibernate-configuration> <session-factory> <property name="connection.driver_class">jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:server</property> <property name="connection.username">nareshit</property> <property name="connection.password">nareshit</property> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <mapping resource=""/Account.hbm.xml>
  11. 11. Hibernate Hibernate by L N Rao Page 11 </session-factory> </hibernate-configuration> ============================================================================================================ ==== 04/10/12 -------- ReadApplication.java -------------------- import org.hibernate.cfg.Configuration; import org.hibernate.SessionFactory; import org.hibernate.Session; import com.nareshit.dao.Account; class ReadApplication { public static void main(String args[]) { Configuration c = new Configuration(); c.configure(); // 2 xml files are loaded SessionFactory sf = c.buildSessionFactory(); Session session = sf.openSession(); Account acc = (Account)session.get(Account.class,1001); if(acc==null) { System.out.println("Account doesn't exist"); } else { System.out.println("A/C no.: "+acc.getAccno()); System.out.println("A/C holder name: "+acc.getName()); System.out.println("Balance Rs.: "+acc.getBalance()); } session.close(); sessionFactory.close(); } } Note:- Place Hibernate3.jar file into the classpath before compiling the above application. =>javac -d . *.java =>place all the jar files of the Hibernate software into classpath before executing the above application. Q)Develop a hibernate application that prompt the end user to enter the account number and deletes that record from the database. deleteapplication Account.java Account.hbm.xml hibernate.cfg.xml DeleteApplication.java Note:-POJO,mapping file and configuration file from the previous application. DeleteApplication.java ---------------------- import org.hibernate.cfg.Configuration; import org.hibernate.SessionFactory; import org.hibernate.Session; import org.hibernate.Transaction; import com.nareshit.dao.Account; class DeleteApplication { public static void main(String args[])
  12. 12. Hibernate Hibernate by L N Rao Page 12 { Configuration configuration = new Configuration(); configuration.configure(); // 2 xml files are loaded SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Account acc = (Account)session.get(Account.class,1001); if(acc==null) { System.out.println("Account doesn't exist"); } else { Transaction txn = session.beginTransaction(); session.delete(acc); txn.commit(); System.out.println("Account Deleted successfully"); } session.close(); sessionFactory.close(); } } Note:- If we are performing insertion,deletion or updation Transaction has to be created and commited. insertapplication StoreAccount.java ----------------- Account acc = new Account(); acc.setAccno(1001); acc.setName("Rama"); acc.setBalance(5600f); Transaction txn = session.beginTransaction(); session.save(acc); txn.commit(); System.out.println("object persisted"); ================================================================================================= 05/10/12 -------- Q)Develop a Hibernate Application that increases the specified account by the specified amount in the database. updateapplication Account.java Account.hbm.xml hibernate.cfg.xml UpdateApplication.java UpdateApplication.java ---------------------- import org.hibernate.cfg.Configuration; import org.hibernate.SessionFactory; import org.hibernate.Session; import org.hibernate.Transaction; import com.nareshit.dao.Account; import java.util.Scanner; class UpdateApplication {
  13. 13. Hibernate Hibernate by L N Rao Page 13 public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.println("Enter the A/C no:"); int ano = s.nextInt(); System.out.print("Enter the depositing amount Rs.:"); float amt = s.nextFloat(); Configuration configuration = new Configuration(); configuration.configure(); // 2 xml files are loaded SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Account acc = (Account)session.get(Account.class,ano); if(acc==null) { System.out.println("Account doesn't exist"); } else { Transaction txn = session.beginTransaction(); float bal = acc.getBalance(); float newbal = bal+amt; acc.setBalance(newbal); txn.commit(); System.out.println("Account Updated successfully"); } session.close(); sessionFactory.close(); } } Q)Explain about "Configuration" of a Hibernate Application? =>org.hibernate.cfg.Configuration is a library class of Hibernate API. =>Configuration object serves two purposes. 1.)loading hibernate configuration file and mapping file into memory and making them available to Hibernate Engine. 2.)acting as a factory of SessionFactory. i.e. to create the object of SessionFactory. ->"get() method 05-oct-12.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,dialect and mapping file. =>Hibernate Engine submits the select statement using JDBC API. =>Hibernate Engine processes ResultSet record, creates the instance of persistence class and populates its fields with ResultSet data(database data). Q)What is the prototype of get() method? public Object get(java.lang.Class,java.io.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. =>When persistence object is associated with .... ...... =>If persistence object state is modified and when commit() method is called on Session object, HIbernate engine implicitely generates UPDATE SQL statement and submits to the DBMS using JDBC. Therefore, without the need of any library method Q)What happens in the background when save() method is called on the Session object? =>Hibernate engine receives the method call and generates INSERT SQL statement and submits to the DBMS
  14. 14. Hibernate Hibernate by L N Rao Page 14 using JDBC and therefore, record is inserted. We say, Object is persisted. Q)What happens in the background when delete() method is called on the Session object? =>Hibernate engine receives the method call and generates DELETE SQL statement and submits to the DBMS using JDBC and therefore, record is deleted from the database. We say, persisted object is removed. 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. =>SessionFactory is library interface of Hibernate API. =>Hibernate engine implements org.hibernate.SessionFactory interface. =>SessionFactory's main purpose is creating Session objects for the application. =>SessionFactory is heavy weight object(?). =>SessionFactory object is created only one per DBMS for the entire data access layer. =>SessionFactory is not a singleton. =>SessionFactory is thread-safe. Q)Explain about Session in Hibernate. =>Session is library interface of Hibernate API. =>Hibernate engine implements org.hibernate.Session interface. =>Session object is the persistent manager. =>Hibernate applications use Session object only to perform the CRUD operations. =>Session object is light weight. =>Session object is not thread-safe. =>In every DAO method Session object is created, CRUD operation is performed and it is closed. class AccountDAO { //never create Session object here - b/c it's not thread safe storeAccount() { //create Session object here b/c local variable is thread safe Session session = sessionFactory.openSession(); .... session.save(); session.close(); //it's light weight hence no performance burden ( while creating,using,closing it inside DAO every method) } deleteAccount() { } findAccount() { } } Q)Explain about Transaction class in Hibernate. =>Transaction is library interface of Hibernate API. =>Hibernate engine implements org.hibernate.Transaction interface. =>Transaction object is a singleton per Session. =>Whenever write operation is performed on the database using Hibernate, Transaction object is required in DAO method, as connection is opened with database in auto-commit disabled mode. ================================================================================================= 09/10/12 -------- Q)Explain about dialect in a Hibernate Application. =>For each DBMS variance will be there in SQL syntax. =>dialect is a Java class of org.hibernate.dialect package. =>for each DBMS that Hibernate has support for communication, one dialect class is given as a part of Hibernate framework. =>dialect class holds SQL syntax details of one DBMS. =>When Hibernate Application makes a method call for a CRUD operation, Hibernate takes the help of dialect
  15. 15. Hibernate Hibernate by L N Rao Page 15 class -dialect is abstracting the SQL variances(across the DBMS) from the application Q)Explain about persistent object life cycle. =>Persistence object has 3 life cycle states. 1.)transient state (new state) 2.)persistent state (managed state) 3.)detached state Q.)Explain about transient state of persistent object. =>A persistent object is said to be in transient state if it is not associated with Session and nor has matching record in the database. =>Persistent object holds enterprise data but not yet persisted using Hibernate is said to be in transient state. For eg. Account acc = new Account(); acc.setAccno(1001); acc.setName("Kailash"); acc.setBalance(5600); =>In the above piece of code, Account object is said to be in transient state. Q)Explain about persistent/managed state of a persistent object. =>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. For eg. Account acc = (Account) Session.get(Account.class,1001); =>When the persistent object is in managed state it is in sync with the database. i.e. any data change in the object, Hibernate implicitely updates to the corresponding record. Q)Explain about detached state of a persisted object. =>A persistent object is said to be in detached state, if it is not associated with Session Object but has a matching record in the database. =>If the persistent object is in detached state, it is not in sync with database. For eg. Account acc = (Account) Session.get(Account.class,1001);//managed state session.clear(); //acc becomes detached Transaction txn = session.beginTransaction(); session.save(acc); //error w'll come txn.commit(); Transaction txn = session.beginTransaction(); session.update(acc); txn.commit(); ____________________________________________________________________________________________________________ ____ 10/10/12 -------- Q)Develop a banking application (Hibernate Application) to perform the following operations. 1.)account opening 2.)account closing 3.)deposit 4.)withdraw 5.)getting account details bankingapplication Account.java -- hibernate.cfg.xml | Account.hbm.xml |- Data Access Layer files AccountDAO.java | SessionUtil.java -- DAOFactory.java *.java (other files to implement the 5 use-case) =>In AccountDAO class we implement 4 methods each of which performs one CRUD operation. =>In every DAO method we need to get Session object (reference), use it in performing CRUD operation
  16. 16. Hibernate Hibernate by L N Rao Page 16 and close it. =>SessionUtil class is a utility class (helper class) that ensures the following things for the entire data access layer of the project. 1.)loading meta information only once 2.)creating the heavy weight SessionFactory object only once 3.)providing Session objects to all the DAO methods SessionUtil.java ---------------- package com.nareshit.dao; import org.hibernate.cfg.Configuration; import org.hibernate.SessionFactory; import org.hibernate.Session; public class SessionUtil { private static SessionFactory sf; static { Configuration cfg = new Configuration(); cfg.configure(); sf = cfg.buildSessionFactory(); } public static Session getSession() { return sf.openSession(); } } AccountDAO.java --------------- package com.nareshit.dao; import org.hibernate.Session; public class AccountDAO { public Account findAccount(int ano) { Account acc = null; Session session = SessionUtil.getSession(); acc = (Account) session.get(Account.class,ano); session.close(); return acc; }//DAO method public void storeAccount(Account acc) { Session session = SessionUtil.getSession(); session.getTransaction().begin(); session.save(acc); session.getTransaction().commit(); session.close(); } public void updateAccount(Account acc) { Session session = SessionUtil.getSession(); session.getTransaction().begin(); session.update(acc); session.getTransaction().commit(); session.close(); } public boolean deleteAccount(int ano)
  17. 17. Hibernate Hibernate by L N Rao Page 17 { boolean flag = false; Session session = SessionUtil.getSession(); Account acc = findAccount(ano); //self messaging if(acc!=null) { session.getTransaction().begin(); session.delete(acc); session.getTransaction().commit(); flag = true; } session.close(); return flag; } } 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. =>It serves two purposes. 1.)providing DAO objects to their utilizers 2.)making DAO classes singletons if required DAOFactory.java --------------- package com.nareshit.dao; public class DAOFactory { private static AccountDAO accountDAO = new AccountDAO(); public static AccountDAO getAccountDAO() { return accountDAO; } } DepositUseCase.java (PL Plus SL) ------------------- import com.nareshit.dao.SessionUtil; import com.nareshit.dao.Account; import com.nareshit.dao.AccountDAO; import com.nareshit.dao.DAOFactory; class DepositUseCase { public static void main(String args[]) { //PL code int ano = 1001; float amt = 500f; //SL code AccountDAO accountDAO = DAOFactory.getAccountDAO(); Account acc = accountDAO.findAccount(ano); float bal = acc.getBalance(); float newbal = bal + amt; acc.setBalance(newbal); accountDAO.updateAccount(acc); //SL over System.out.println("deposited successfully");//PL } } ___________________________________________________________________________________________ 12/10/12 ----------
  18. 18. Hibernate Hibernate by L N Rao Page 18 WithdrawUseCase.java (PL + SL) -------------------- import com.nareshit.dao.SessionUtil; import com.nareshit.dao.Account; import com.nareshit.dao.AccountDAO; import com.nareshit.dao.DAOFactory; class WithdrawUseCase { public static void main(String args[]) { //PL code int ano = 1001; float amt = 500f; //SL code AccountDAO accountDAO = DAOFactory.getAccountDAO(); Account acc = accountDAO.findAccount(ano); float bal = acc.getBalance(); float newbal = bal- amt; acc.setBalance(newbal); accountDAO.updateAccount(acc); //SL over System.out.println("Please collect the cash");//PL } } Q)How to make use of Hibernate in a Java Web Application? Step 1:- place Hibernate jar files and driver jar file in lib folder. Step 2:- place hibernate configuration file, mapping file into "classes" folder. Step 3:- place data access layer files into "classes" folder. Step 4:- in web component make use of DAO class to perform CRUD operations. Q)Develop a Java Web Application in which, online deposit use-case is implemented. depositapplication deposit.html WEB-INF web.xml classes hibernate.cfg.xml Account.hbm.xml com nareshit dao Account.class DAOFactory.class AccountDAO.class SessionUtil.class web DepositServlet.class lib *.jar http://localhost:80801/depositapplication/deposit.html web.xml --------- <web-app> <servlet> <servlet-name>deposit</servlet-name> <servlet-class>com.nareshit.web.DepositServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>deposit</servlet-name> <url-pattern>/deposit</url-pattern> </servlet-mapping>
  19. 19. Hibernate Hibernate by L N Rao Page 19 </web-app> deposit.html ------------- <html> <body bgcolor="cyan"> <center> <h1>Deposit Screen</h1> <form action="./deposit" method="POST"> A/C no <input type="text" name="accno"> <br><br> Amount <input type="text" name="amount"> <br><br> <input type="submit" value="Deposit"> </form> </center> </body> </html> DepositServlet.java --------------------- package com.nareshit.web; import javax.servlet.*; import java.io.*; import com.nareshit.dao.Account; import com.nareshit.dao.AccountDAO; import com.nareshit.dao.DAOFactory; public class DepositServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) { int ano = Integer.parseInt(request.getParameter("accno")); float amt = Float.parseFloat(request.getParameter("amount")); AccountDAO accountDAO = DAOFactory.getAccountDAO(); Account acc = accountDAO.findAccount(ano); if(acc == null) { System.out.println("Account does not exist"); } else { acc.setBalance(acc.getBalance()+amt); accountDAO.updateAccount(acc); System.out.println("successfully deposited"); } }//service } Discussion :- Colaboration between the layers of an enterprise application. Colaboration - assisting one another ____________________________________________________________________________________________ 15/10/12(Monday, 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. =>Integrated Development Environment is a tool(software) used to develop, debug, test deploy and execute Java Applications.
  20. 20. Hibernate Hibernate by L N Rao Page 20 =>NetBeans,JDeveloper,JBuilder,RAD,Eclipse are some of the other IDEs used for Java application development. Q)What is workspace in the context of MyEclipse? =>A master folder in which, our Java applications developed using MyEclipse are stored is known as workspace. =>We can create as many number of workspace as we want. =>In a workspace not only Java applications but also environmental information(meta data) is stored (MyEclipse requirement). =>Every MyEclipse session is associated with a workspace. Q)What is a project in the context of MyEclipse? =>Any Java application developed using MyEclipse is known as a project. =>Using MyEclipse we can develop the following kinds of Java applications(projects) 1.)Java project 2.)Web project 3.)EJB project 4.)Web Service project 5.)Enterprise application project Q)What are the main components of MyEclipse Enterprise Workbench? 1.)Package Explorer 2.)Editor 3.)Console Q)How to develop a Java project using MyEclipse? Note:- A standalone Java application(main method program) in MyEclipse context is known as a Java Project. =>Right click on package explorer ->new ->Java Project ->enter project name Note:- MyEclipse creates a directory in master folder(workspace) which is visible in package explorer. Within this directory it creates "src" directory. 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. Step 1:- Create a Java project. Step 2:- Package creation .... ____________________________________________________________________________________________________________ ________ 16/10/12 -------- ...... _________________________________________________________________________________________________ 17/10/12 -------- Q)What are the limitations of Session interface methods in performing CRUD operations? 1.)Can't retrieve multiple persistent objects. 2.)Can't perform bulk updates and bulk deletes. 3.)To retieve single persistence object also we need to specify id field value i.e. using non-id field value as search criteria, we can't retrieve the persistent object. 4.)Can't express required complex criteria to perform the CRUD operation. Q)How to overcome the above limitations? =>Using the following. 1.)HQL 2.)Native SQL 3.)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. =>The way we build the query is similar. Q)What are the differences between HQL and SQL?
  21. 21. Hibernate Hibernate by L N Rao Page 21 1.)Syntactical difference 2.)SQL is expressed in terms of tables and corresponding columns where as, HQL query is expressed in terms of persistence classes and their fields. 3.)SQL in non portable across DBMSs. Where as, HQL is portable. Q)How to make use of HQL in a Hibernate Application? =>"HQL 17-oct-12.bmp" Step 1:- Build HQL Query Step 2:- create Query interface object Step 3:- Bind the parameters if any. Step 4:- Execute the Query(Submitting the query to Hibernate Engine). ____________________________________________________________________________________________________________ _________ 18/10/12 -------- Q)Develop a Hibernate Application that retrieves all the accounts from the database and display their state. readaccountsapplication Account.java hibernate.cfg.xml Account.hbm.xml SessionUtil.java ReadAccountApplication.java ReadAccountsApplication.java ---------------------------- import org.hibernate.Session; import org.hibernate.Query; import java.util.List; import com.nareshit.dao.Account; import com.nareshit.dao.SessionUtil; class ReadAccountsApplication { public static void main(String args[]) { Session session = SessionUtil.getSession(); String hql = "SELECT a from Account a WHERE a.balance > 3000"; Query query = session.createQuery(hql); List<Account> accounts = query.list(); for(Account acc : accounts) { System.out.println("A/C no.: "+acc.getAccno()); System.out.println("A/C holder name: "+acc.getName()); System.out.println("Balance Rs.: "+acc.getBalance()); } session.close(); } } Q)Develop a DAO class to have multiple records retrieving method. Make use of JDBC API. public class AccountDAO { public List<Account> findAccounts() { Connection con = null; Statement st = null; ResultSet rs = null; List<Account> accounts = null; try { con = DBUtil.getConnection();
  22. 22. Hibernate Hibernate by L N Rao Page 22 st = con.createStatement(); rs = st.executeQuery("SELECT * FROM ACCOUNT"); if(rs.next()) { accounts = new ArrayList<Account>(); do { Account acc = new Account(); acc.setAccno(rs.getInt(1)); acc.setName(rs.getString(2)); acc.setBalance(rs.getFloat(3)); accounts.add(acc); }while(rs.next()); } }//try catch(SQLException e) { } finally { DBUtil.close(con,st,rs); } return accounts; }//findAccounts() }//DAO class =>list() method of Query class in Hibernate does all the tasks what findAccounts() method does in the above example. Q)Modify the above DAO class so as to use Hibernate API in DAO method. AccountDAO.java --------------- package com.nareshit.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.Query; public class AccountDAO { public List<Account> findAccounts() { Session session = SessionUtil.getSession(); Query query = session.createQuery("SELECT a FROM Account a"); List<Account> accounts = query.list(); session.close(); return accounts; } } Note:- If the above DAO class is used in ReadAccountsApplication.java, it is as follows. import java.util.List; import com.nareshit.dao.Account; import com.nareshit.dao.AccountDAO; class ReadAccountsApplication { public static void main(String args[]) { AccountDAO accountDAO = new AccountDAO(); List<Account> accounts = accountDAO.findAccounts(); for(Account acc : accounts) {
  23. 23. Hibernate Hibernate by L N Rao Page 23 System.out.println("A/C no.: "+acc.getAccno()); System.out.println("A/C holder name: "+acc.getName()); System.out.println("Balance Rs.: "+acc.getBalance()); } } } ____________________________________________________________________________________________________________ ________ 19/10/12 -------- Q)Develop a Hibernate Application, in which increase the balances of all the accounts by Rs.500. bulkupdatesapplication Account.java BulkUpdatesApplication.java *.xml SessionUtil.java BulkUpdatesApplication.java --------------------------- import org.hibernate.Session; import org.hibernate.Query; import com.nareshit.dao.SessionUtil; public class BulkUpdatesApplication { public static void main(String args[]) { Session session = SessionUtil.getSession(); Query query = session.createQuery("UPDATE Account a SET a.balance=a.balance+500"); session.getTransaction().begin(); int c = query.executeUpdate(); session.getTransaction().commit(); System.out.println(c+" accounts updates"); session.close(); } } Q)Develop a piece of Hibernate code that deletes all the persistence objects from the database whose balance is less than Rs.10000. BulkDeletesApplication.java --------------------------- ..... Session session = SessionUtil.getSession(); Query query = session.createQuery("DELETE FROM Account a WHERE a.balance<10000"); session.getTransaction().begin(); query.executeUpdate(); session.getTransaction().commit(); ..... Q)Explain about parameter binding in a Hibernate Application while using HQL? =>In a HQL query we can have place holders in place of values. These are known as the parameters of HQL query. =>Supplying values to the place holders is nothing but parameter binding. For eg. Q)How are parameters classified? 1.)positional parameters 2.)named parameters Q)Explain about positional parameters. =>If question marks are used as place holders in a HQL query, they are known as positional parameters. =>In case of positional parameters supplying of the values happen based on their position in the query and hence the name. Q)Write a piece of Hibernate code in which, positional parameters are used in HQL query.
  24. 24. Hibernate Hibernate by L N Rao Page 24 Query query = session.createQuery("UPDATE Accounts a SET a.balance=a.balance+? WHERE a.accno=?"); query.setParameter(0,500f); query.setParameter(1,1001); session.getTransaction().begin(); int c = query.executeUpdate(); session.getTransaction().commit(); Q)Explain about named parameters? =>If a user defined name prefixed with colon(:) is used as place holder in HQL query, it is known as a named parameter. piece of code ------------- Query query = session.createQuery("UPDATE Account a SET a.balance=a.balance+:damount WHERE a.accno=:ano"); query.setParameter("damount",500f); query.setParameter("ano",1001); session.getTransaction().begin(); int c = query.executeUpdate(); session.getTransaction().commit(); Q)Which kind of parameters are preferable(named or positional)? =>Named parameters are preferred to positional parameters. =>Positional parameters have the following drawbacks. 1.)Not flexible while binding the parameters if query is altered at later stage 2.)Readability of the query is not that good and thereby binding of parameters not so convincing. Q)Can we mix positional parameters and named parameters in the same HQL query? =>Yes. But, positional parameters first. For eg. Query query = session.createQuery("UPDATE Account a SET a.balance=a.balance+? WHERE a.accno=:ano"); query.setParameter(0,500f); query.setParameter("ano",1001); ____________________________________________________________________________________________________________ 22/10/12 -------- Q)What are the different approaches of a Hibernate application connecting to multiple DBMSs (concurrrently)? 1.)one configuration file per DBMS 2.)single configuration file for any number of DBMSs. Q)Develop a Hibernate Application that communicates with Oracle DBMS and MySQL DBMS using "configuration file per DBMS approach". multidbmsreadapplication Account.hbm.xml Account.java ReadApplication.java hibernate.oraclecfg.xml hibernate.cfgmysql.xml Note:- Mapping file, persistent class, hibernate.oraclecfg.xml source code from earlier applications only. hibernate.cfgmysql.xml ---------------------- driver class name = com.mysql.jdbc.Driver db url = jdbc:mysql://localhost:3306/MySQL user = root password = root dialect = org.hibernate.dialect.MySQLDialect ReadApplication.java -------------------- import com.nareshit.dao.Account; import org.hibernate.*; import org.hibernate.cfg.*;
  25. 25. Hibernate Hibernate by L N Rao Page 25 public class ReadApplication { public static void main(String args[]) { Configuration mcfg = new Configuration(); mcfg.configure("hibernate.cfgmysql.xml"); SessionFactroy msf = mcfg.buildSessionFactory(); Session msession = msf.openSession(); Account acc = (Account)msession.get(Account.class,1001); System.out.println("Balance is Rs. "+acc.getBalance()); msession.close(); msf.close(); Configuration ocfg = new Configuration(); ocfg.configure("hibernate.oraclecfg.xml"); SessionFactory osf = ocfg.buildSessionFactory(); Session osession = osf.openSession(); //System.out.println(osession.connection()); acc = (Account)osession.get(Account.class,1001); System.out.println("Balance is Rs. "+acc.getBalance()); osession.close(); osf.close(); } } Q)Modify the above application so as to follow single configuration file approach. singleconfigfilereadapplication Account.java hibernate.cfg.xml Account.hbm.xml ReadApplication.java DBUtil.java ReadApplication.java -------------------- _________________________________________________________________________________________________________ 25/10/12 -------- hibernate.cfg.xml ----------------- <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <mapping resource="Account.hbm.xml"/> </session-factory> </hibernate-configuration> DBUtil.java ----------- package com.nareshit.dao; import java.sql.SQLException; import java.sql.Connection; import java.sql.DriverManager; public class DBUtil { static { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("com.mysql.jdbc.Driver");
  26. 26. Hibernate Hibernate by L N Rao Page 26 } catch(Exception e) { System.out.println(e); } }//static initializer public static Connection getOracleConnection() { Connection con = null; try { con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:server","nareshit","nareshit"); } catch(Exception e) { } return con; } public static Connection getMySQLConnection() { Connection con = null; try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/MySQL","root","root"); } catch(Exception e) { } return con; }//user defined factory method } ReadApplication.java -------------------- import com.nareshit.dao.Account; import com.nareshit.dao.DBUtil; import org.hibernate.*; import org.hibernate.cfg.*; class ReadApplication { public static void main(String args[]) { Configuration cfg = new Configuration(); cfg.configure(); SessionFactory sf = cfg.buildSessionFactory(); Session osession = sf.openSession(DBUtil.getOracleConnection()); Account acc = (Account) osession.get(Account.class,1001); System.out.println("Oracle balance Rs."+acc.getBalance()); osession.close(); Session msession = sf.openSession(DBUtil.getMySQLConnection()); acc = (Account)msession.get(Account.class,1001); System.out.println("MySQL balance Rs."+acc.getBalance()); msession.close(); } } 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.e. exceptions getting raised. =>Dealing with these exceptions is nothing but handling exceptions in hibernate applications. =>In DAO method, for every CRUD operation performed using Session interface method we have
  27. 27. Hibernate Hibernate by L N Rao Page 27 org.hibernate.HibernateException catch block. =>from within the catch block of every DAO method propagate userdefined exception to service layer. ____________________________________________________________________________________________________________ _______ 26/10/12 -------- Q)Implement exception handling in AccountDAO class. AccountNotFoundException.java ------------------------------ package com.nareshit.exception; public class AccountNotFoundException extends Exception { }//user defined checked exception DataAccessException.java ------------------------------ package com.nareshit.exception; public class DataAccessException extends Exception { }//user defined checked exception AccountDAO.java --------------- package com.nareshit.dao; import com.nareshit.exception.AccountNotFoundException; import com.nareshit.exception.DataAccessException; import java.util.List; public interface AccountDAO { public abstract void storeAccount(Account acc)throws DataAccessException; public abstract void deleteAccount(int accno)throws DataAccessException,AccountNotFoundException; public abstract void updateAccount(Account acc)throws DataAccessException; public abstract Account findAccount(int accno)throws DataAccessException,AccountNotFoundException; public abstract List<Account> findAccounts()throws DataAccessException,AccountNotFoundException; } AccountDAOImpl.java ------------------- package com.nareshit.dao; import com.nareshit.exception.AccountNotFoundException; import com.nareshit.exception.DataAccessException; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; public class AccountDAOImpl implements AccountDAO { public Account findAccount(int accno)throws AccountNotFoundException,DataAccessException { Account acc = null; Session session = null; try { session = SessionUtil.getSession(); acc = (Account) session.get(Account.class,accno); if(acc==null) throw new AccountNotFoundException(); }
  28. 28. Hibernate Hibernate by L N Rao Page 28 catch(HibernateException e) { throw new DataAccessException(); } finally { if(session != null) { session.close(); } } return acc; }//findAccount public void storeAccount(Account acc)throws DataAccessException{} public void deleteAccount(int accno)throws DataAccessException,AccountNotFoundException{} public void updateAccount(Account acc)throws DataAccessException{} public Account findAccount(int accno)throws DataAccessException,AccountNotFoundException{} public List<Account> findAccounts()throws DataAccessException,AccountNotFoundException{} } __________________________________________________________________________________________________________ 29/10/12 -------- Q)Modify the first hibernate example so as to provide mapping information to hibernate engine using annotations. readapplication Account.java hibernate.cfg.xml ReadApplication.java ReadApplication.java -------------------- =>From the first application as it is. hibernate.cfg.xml ----------------- <hibernate-configuration> <session-factory> ..... <mapping class="com.nareshit.dao.Account"/> </session-factory> </hibernate-configuration> Account.java ------------ package com.nareshit.dao; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Id; import javax.persistence.Column; @Entity @Table(name="MYACCOUNT") public class Account { @Id @Column(name="ANO") private int accno; @Column(name="MN") private String name; @Column(name="BAL") private String balance;
  29. 29. Hibernate Hibernate by L N Rao Page 29 //setters and getters } Q)What is an anonymous HQL query? =>Nameless HQL query are anonymous queries. =>Anonymous queries have the following limitations 1.)query is not reusable 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. =>HQL query is built either in mapping file or in persistence class and given a name to it in case of named query. =>In DAO methods that name is used to execute the query. __________________________________________________________________________________________________________ 30/10/12 -------- Q)How to make use of a named HQL query in a Hibernate Application? Step 1:- Build the query either in the mapping file or at the persistent class. Step 2:- Create query object. Step 3:- Bind the parameters if any. Step 4:- Execute the query. Note:- Step 3 and Step 4 are the same for both annonymous and named HQL query. Q)Develop a hibernate application in which, named query is used. namedqueryapplication Account.java SessionUtil.java Account.hbm.xml hibernate.cfg.xml AccountDAO.java NamedQueryApplication.java Account.hbm.xml --------------- <hibernate-mapping> <class ....> </class> <query name="allaccounts"> SELECT a FROM Account a </query> </hibernate-mapping> AccountDAO.java --------------- package com.nareshit.dao; import org.hibernate.Query; import org.hibernate.Session; import java.util.List; public class AccountDAO { public List<Account> findAccounts() { Session session = SessionUtil.getSession(); Query query = session.getNamedQuery("allaccounts"); List<Account> accounts = query.list(); session.close(); return accounts; } }
  30. 30. Hibernate Hibernate by L N Rao Page 30 NamedQueryApplication.java -------------------------- import com.nareshit.dao.AccountDAO; import com.nareshit.dao.Account; import java.util.List; class NamedQueryApplication { public static void main(String args[]) { AccountDAO dao = new AccountDAO(); List<Account> accounts = dao.findAccounts(); System.out.println("Number of accounts: "+accounts.size()); for(Account acc : accounts) { System.out.println("Accno : "+ acc.getAccno()); System.out.println("Name : "+ acc.getName()); System.out.println("Balance : "+ acc.getBalance()); } } } Q)How to overcome the violation of well-formedness of mapping file as a result of named query? =>An xml document is said to be well-formed if it is syntactically correct. =>When HQL query is violating the syntactical rules of xml document, we need to write the query in a special area known as CDATA section. For eg. <![CDATA[ SELECT a FROM Account a WHERE a.balance<9000 ]]> <![CDATA[SELECT a FROM Account a WHERE a.balance<:bal]]> Q)Modify the previous hibernate application so as to give mapping info to Hibernate Engine using annotations. namedqueryannotationapplication Account.java SessionUtil.java hibernate.cfg.xml AccountDAO.java NamedQueryApplication.java Note:- SessionUtil.java, AccountDAO.java, NamedQueryApplication.java are from previous application. hibernate.cfg.xml ----------------- <hibernate-configuration> <session-factory> ....... <mapping class="com.nareshit.dao.Account"/> </session-factory> </hibernate-configuration> Account.java ------------ package com.nareshit.dao; import javax.persistence.*; @Entity @Table(name="myaccount") @NamedQuery(name="allaccounts",query="SELECT a FROM Account a WHERE a.balance<:bal") public class Account { @Id
  31. 31. Hibernate Hibernate by L N Rao Page 31 @Column(name="ANO") private int accno; @Column(name="NM") private String name; @Column(name="BAL") private float balance; //setters & getters } _________________________________________________________________________________________________ 31/10/12 -------- Q)Explain about different cases of list() method. Case i:- No persistent object field is specified in HQL SELECT clause. list() method returns a collection of Persistent objects. Case ii:- One persistent field is specified in SELECT clause of HQL query. list() method returns a collection of wrapper objects or Strings depending upon the type of persistent object field. Case iii:- more than one persistent field specified in the SELECT clause of HQL query. list() method returns a collection of java.lang.Object arrays. Q)Hibernate application on different cases of list() method. listmethodsapplication Account.java SessionUtil.java Account.hbm.xml hibernate.cfg.xml ListMethodsApplication.java ListMethodsApplication.java --------------------------- class ListMethodsApplication { public static void main(String args[]) { Session session = SessionUtil.getSession(); String hql1 = "SELECT a.balance FROM Account a"; Query query = session.createQuery(hql1); List<Float> bals = query.list(); for(Float bal : bals) System.out.println(bal); String hql2 = "SELECT a.name FROM Account a"; query = session.createQuery(hql2); List<String> nms = query.list((); for(String name : nms) System.out.println(name); String hql3 = "SELECT a.name,a.balance FROM Account a"; query = session.createQuery(hql3); List<Object[]> accdetails = query.list(); for(Object[] arr : accdetails) { for(Object v : arr) System.out.println(v+"t"); System.out.println(); } for(Object[] arr : accdetails) { System.out.println(arr[0]+"t"+arr[1]); } session.close(); }//main() } Q)Hibernate application in which, the following things are used in HQL queries. 1.)Named query
  32. 32. Hibernate Hibernate by L N Rao Page 32 2.)aggregate function calling in HQL 3.)GROUP BY and ORDER BY clauses 4.)maintaining well-formedness of the mapping file while building the named HQL query. SQL script ---------- DROP TABLE EMPLOYEE; CREATE TABLE EMPLOYEE(EMPNO NUMBER(6),NAME VARCHAR2(12),SALARY NUMBER(9,2), DEPTNO NUMBER(3)); INSERT INTO EMPLOYEE VALUES(1001,'Rahim',6400,10); INSERT INTO EMPLOYEE VALUES(1002,'Rama',65OO,10); INSERT INTO EMPLOYEE VALUES(1003,'Samules',66OO,10); INSERT INTO EMPLOYEE VALUES(1004,'Singh',67OO,20); COMMIT; SELECT * FROM EMPLOYEE; / hqlapplication Employee.java Employee.hbm.xml hibernate.cfg.xml SessionUtil.java HibernateApplication.java Employee.java ------------- package com.nareshit.dao; public class Employee { private int empno; private String name; private float salary; private int deptno; //setters & getters } Employee.hbm.xml ---------------- <hibernate-mapping> <class name="com.nareshit.dao.Employee"> <id name="empno"/> <property name="name"/> <property name="salary"/> <property name="deptno"/> </class> <query name="avgsal"> SELECT AVG(e.salary) FROM Employee e </query> <query name="groupsal"> SELECT e.deptno,AVG(e.salary) FROM Employee e GROUP BY e.deptno </query> <query name="ordersal"> <![CDATA[ SELECT e.name,e.salary FROM Employee e ORDER BY e.salary DESC ]]> </query> </hibernate-mapping> __________________________________________________________________________________________________________ 01/11/12 -------- HibernateApplication.java ------------------------- import org.hibernate.Session; import org.hibernate.Query; import org.hibernate.List; import com.nareshit.dao.SessionUtil;
  33. 33. Hibernate Hibernate by L N Rao Page 33 import com.nareshit.dao.Employee; public class HibernateApplication { public static void main(String args[]) { Session session = SessionUtil.getSession(); Query query = session.getNamedQuery("avgsal"); System.out.println("Average salary is Rs."+query.uniqueResult()); query = session.getNamedQuery("groupsal"); List<Object[]> emps = query.list(); System.out.println("DEPTNO AVG SAL"); for(Object[] o : emps) { System.out.println(o[0]+"t"+o[1]); } query = session.getNamedQuery("ordersal"); List<Object[]> emps1 = query.list(); System.out.println("NAME SALARY"); for(Object[] o : emps1) { System.out.println(o[0]+"t"+o[1]); } session.close(); } } Note:- Whenever there is a chance of getting a single object(single result) from the query, it is advisable to call uniqueResult() method on Query object, instead of calling list() method. If multiple objects are returned from the query, this method throws NonUniqueResultException. hibernate.cfg.xml ----------------- <hibernate-configuration> <session-factory> ........ <mapping resource="Employee.hbm.xml"/> </session-factory> </hibernate-configuration> Q)Modify the previous application so as to provide mapping info to Hibernate Engine using annotations. lasthqlapplication Employee.java hibernate.cfg.xml SessionUtil.java HibernateApplication.java Employee.java ------------- package com.nareshit.dao; import javax.persistence.Entity; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Id; @Entity @NamedQueries( { @NamedQuery(name="avgsal",query="SELECT AVG(e.salary) FROM Employee e") @NamedQuery(name="groupsal",query="SELECT e.deptno,AVG(e.salary) FROM Employee e GROUP BY e.deptno") @NamedQuery(name="ordersal",query="SELECT e.name,e.salary FROM Employee e ORDER BY e.salary DESC") })
  34. 34. Hibernate Hibernate by L N Rao Page 34 public class Employee { @Id private int empno; private String name; private float salary; private int deptno; //setters & getters } hibernate.cfg.xml ----------------- <hibernate-configuration> <session-factory> ........ <mapping class="com.nareshit.dao.Employee"/> </session-factory> </hibernate-configuration> ____________________________________________________________________________________________________________ ________ 02/11/12 -------- Q)Hibernate application in which one session object per thread is created. threadpersessionapplication ThreadLocalApplication.java SessionUtil.java hibernate.cfg.xml Account.java Account.hbm.xml SessionUtil.java ---------------- package com.nareshit.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Configuration; //import java.lang.ThreadLocal; public class SessionUtil { private static SessionFactory sf; private static ThreadLocal<Session> threadLocal; static { Configuration cfg = new Configuration(); cfg.configure(); sf = cfg.buildSessionFactory(); threadLocal = new ThreadLocal<Session>(); }//static initializer public static Session getSession() { return sf.openSession(); }//user defined method public static Session getThreadLocalSession() { Session session = threadLocal.get(); if(session == null) { session = sf.openSession(); threadLocal.set(session); } return session;
  35. 35. Hibernate Hibernate by L N Rao Page 35 }//user defined method } ThreadLocalApplication.java --------------------------- import com.nareshit.dao.SessionUtil; class ThreadLocalApplication { public static void main(String args[]) { for(int i=1;i<=5;i++) System.out.println(Thread.currentThread().getName()+":"+ SessionUtil.getThreadLocalSession().hashCode()); MyThread m = new MyThread(); m.setName("child"); m.start(); } } class MyThread extends Thread { public void run() { for(int i=1;i<=5;i++) System.out.println(Thread.currentThread().getName()+":"+ SessionUtil.getThreadLocalSession().hashCode()); } } --We can change the name of "main" thread. Q)What is ThreadLocal? =>java.lang.ThreadLocal is java class. =>It is a collection class. =>Instance of ThreadLocal class holds other objects(references); =>It stores in it Objects with thread name as the key. ___________________________________________________________________________________________________________ 05/11/12 -------- Q)What are the rules/ 1.)Class should not be final. 2.)properties corresponding to table columns -ecapsulation - code organising -iheriance - reusability -abstraction - reducing complexity -polymorphism - -getter - accessor -setter - 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. =>It is one way of querying the database in a Hibernate Application(session methods, HQL and native SQL are the other ways). =>Crieria API is used only to retrieve the data from the database. i.e. it can't be used for DML operations. =>Criteria API is an object oriented alternative for HQL to read data from database. =>Criteria API supports compile time checking for the query that we build unlike HQL. =>Dynamic query building is flexible with Criteria when compared to HQL.
  36. 36. Hibernate Hibernate by L N Rao Page 36 =>If query is very large, Criteria API is difficult to use and HQL is preferable. Q)How to make use of Criteria in a Hibernate Application? Step 1:- create org.hibernate.Criteria interface object. Step 2:- create one or more org,hibernate.criterion.Criterion interface object(s). Step 3:- add Criterion object(s) to Criteria object. Step 4:- call list() or uniqueResult() method on Criteria object. Q)Develop a Hibernate Application to retrieve all accounts from the database and display their state. criteriareadapplication Account.java SessionUtil.java hibernate.cfg.xml Account.hbm.xml CriteriaReadApplication.java CriteriaReadApplication.java ---------------------------- import org.hibernate.Session; import org.hibernate.Criteria; import java.util.List; import com.nareshit.dao.Account; import com.nareshit.dao.SessionUtil; class CriteriaReadApplication { public static void main(String args[]) { Session session = SessionUtil.getSession(); Criteria criteria = session.createCriteria(Account.class); List<Account> accounts = criteria.list(); for(Account acc : accounts) { System.out.println("A/C no.: "+acc.getAccno()); System.out.println("A/C holder name: "+acc.getName()); System.out.println("Balance Rs.: "+acc.getBalance()); } session.close(); } } Q)Develop a piece of code to retrieve all the accounts whose balance is less than Rs.10,000. import org.hibernate.Session; import org.hibernate.Criteria; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import java.util.List; import com.nareshit.dao.Account; import com.nareshit.dao.SessionUtil; class CriteriaReadApplication { public static void main(String args[]) { Session session = SessionUtil.getSession(); Criteria criteria = session.createCriteria(Account.class); Criterion criterion = Restrictions.lt("balance",10000f); criteria.add(criterion); List<Account> accounts = criteria.list(); for(Account acc : accounts) { System.out.println("A/C no.: "+acc.getAccno()); System.out.println("A/C holder name: "+acc.getName());
  37. 37. Hibernate Hibernate by L N Rao Page 37 System.out.println("Balance Rs.: "+acc.getBalance()); } session.close(); } } Note:- Criterion interface and Restrictions interface class belong to org.hibernate.criterion package. __________________________________________________________________________________________________________ 06/11/12 -------- no class ___________________________________________________________________________________________________________ 07/11/12 -------- no class ________________ 08/11/12 -------- Q)How to retrieve all the accounts whose balance between Rs. 7000 and 10000. //left ...... Criterion criterion1 = Criterion criterion2 = Restrictions.lt("balance",10000f); criteria.add(criterion1); criteria.add(criterion2); List<Account> accounts = criteria.list(); OR Criterion criterion = Restrictions.between("balance",7000,10000f); criteria.add(criterion); Q)Explain about projections in Criteria API. =>Without projections, list method of Criteria object returns a collection of persistent objects. It is not possible to retrieve few fields and also can't invoke aggregate functions. =>Using projections involves the following steps. Step 1:- creating org.hibernate.criterion.Projection object. Step 2:- creating org.hibernate.criterion.ProjectionList object. Step 3:- adding Projection objects to ProjectionList object. Step 4:- adding ProjectionList to Criteria object. Step 5:- invoking the list() OR uniqueResult() of Criteria. Note :- For examples on projection RTH. Q)Explain about pagination in Hibernate. 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. =>Paging/Pagination is a technique of loading few records into memory at a time when the query retrieves huge number of records. =>Criteria interface has 2 methods to support pagination. 1.)setFirstResult(int n) 2.)setMaxResults(int fixedSize) =>setMaxResults method is used to specify the page size(the maximum nuber of records at a time retrieved i.e. the maximum number of persistent objects loaded into the memory) =>setFirstResult method is used to specify the initial record number of each page. Note:- org.hibernate.Query interface also has the same methods to implement pagination while using HQL in querying the database in a Hibernate Application. --scrolling blindness problem + memory + performance problem ____________________________ Q)How to make use of connection pooling in a Hibernate Application.
  38. 38. Hibernate Hibernate by L N Rao Page 38 =>Without J2EE container (For eg. web container) if the Java application is running, it is known as non-managed environment. =>In such environment, to enable Hibernate provided connection pooling facility, make use of following tag in Hibernate Configuration file additionally. <property name="connection.pool_size">5</property> =>Almost all Java Enterprise Applications run in J2EE container. J2EE container provided connection pool is the most efficient. =>hibernate.cfg.xml should not have database connection related tags in order to use container provided connection pool. hibernate.cfg.xml ----------------- <hibernate-configuration> <session-factory> <property name="connection.datasource">java:comp/env/myds</property> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <mapping resource="Account.hbm.xml"> </session-factory> </hibernate-configuration> ___________________________________________________________________________________________________________ 09/11/12 --------- Native SQL ~~~~~~~~~~ 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. =>Native SQL is used in Hibernate Applications in the following scenarios. 1.)to call the stored procedure 2.)Feature required in the project provided by SQL but not provided by Hibernate. 3.)While communicating with legacy databases. Note:- As far as possible avoid native Native SQL due to portability reasons. --vendor lock? Q)Develop a Hibernate application in which Native SQL is used to retrieve all the accounts? nativesqlreadapplication Account.java SessionUtil.java hibernate.cfg.xml Account.hbm.xml NativeReadApplication.java NativeReadApplication.java -------------------------- Q)Develop a piece of code to retrieve name and balance of all the accounts using Native SQL. Q)Modify the above piece of code so as to use named native SQL query. namednativesqlapplication Account.java SessionUtil.java hibernate.cfg.xml Account.hbm.xml NamedNativeQueryApplication.java NamedNativeQueryApplication.java -------------------------------- SQLQuery query = (SQLQuery)session.getNamedQuery("allaccounts"); OR
  39. 39. Hibernate Hibernate by L N Rao Page 39 Query query = session.getNamedQuery("allaccounts"); //no need to change DAO method if we wnat to //use NamedSQLQuery List<Object[]> accounts = query.list(); -- @NamedSQLQuery annotation to use in persistence class. Calling aggregate function using native SQL ------------------------------------------- Query query = session.getNamedQuery("avg"); float avgbal = (Float) query.uniqueResult(); System.out.println("Average balance is Rs."+avgbal); 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.createSQLQuery("SELECT AVG(bal) AS avgbal FROM MYACCOUNT"); query.addScalar("avgbal",Hibernate.FLOAT); float avgbal = (FLOAT) query.uniqueResult(); System.out.println("Average balance is Rs."+avgbal); __________________________________________________________________________________________________________ 10/11/12 -------- Calling a strored procedure in a HIbernate Application ------------------------------------------------------ Example stored procedure ------------------------ create or replace procedure changeBal(accno number,newbal number) as begin update myaccount set bal=newbal where ano=accno; end; / Q)Develop a Hibernate Application to call the above stored procedure. storedprocedureapplication1 Account.java hibernate.cfg.xml Account.hbm.xml SessionUtil.java StoredProcedureApplication.java StoredProcedureApplication.java ------------------------------- import org.hibernate.Session; import com.nareshit.dao.SessionUtil; import java.sql.Connection; import java.sql.CallableStatement; import java.sql.SQLException; public class StoredProcedureApplication { public static void main(String args[])throws SQLException { Session session = SessionUtil.getSession(); Connection con = session.connection();
  40. 40. Hibernate Hibernate by L N Rao Page 40 CallableStatement cst = con.prepareCall("{call changeBal(?,?)}"); cst.setInt(1,1001); cst.setFloat(2,4500f); session.getTransaction().begin(); cst.execute(); session.getTransaction().commit(); System.out.println("account updated"); session.close(); } } Q)Modify the above application so as to call the stored procedure in pure hibernate style. StoredProcedureNativeSQLApplication.java ----------------------------------------- import org.hibernate.Session; import org.hibernate.SQLQuery; import com.nareshit.dao.SessionUtil; public class StoredProcedureNativeSQLApplication { public static void main(String args[]) { Session session = SessionUtil.getSession(); SQLQuery query = session.createSQLQuery("{call changeBal(?,?)}"); query.setParameter(0,1001); query.setParameter(1,7300f); session.getTransaction().begin(); query.executeUpdate(); session.getTransaction().commit(); System.out.println("account updated"); session.close(); } } Q)Modify the avove application so as to bring portability while calling the stored procedure. Account.hbm.xml --------------- <hibernate-mapping> <class ....> </class> <sql-query name="chgbal"> {call changeBal(?,?)} </sql-query> </hibernate-mapping> StoredProcedureNamedQueryApplication.java ----------------------------------------- Query query = session.getNamedQuery("chgbal"); query.setParameter(0,1001); query.setParameter(1,4300f); session.getTransaction().begin(); query.executeUpdate(); session.getTransaction().commit(); -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------- 12/11/12 ------------ Q)Explain about O/R mismatches.* =>There exists paradigm mismatch(impedence mismatch) between Object Oriented and Relational representation of data in a enterprise application. =>Most notable mismatches are
  41. 41. Hibernate Hibernate by L N Rao Page 41 1.)Problem of granularity 2.)Problem of sub types(inheritance mismatch) 3.)problem of relationships(relationship mismatch) Q)Explain about problem of granularity. =>Relative size of data with which we are working is known as granularity. =>data are(is) both course grained and fine grained. =>if UDT is the column type of a table, it is said to be course grained. If no table column is of UDT, that table is said to be fine grained. =>Course grained table in RDBMS has no consistent support and therefore almost abandoned. =>If UDT is a data member in a persistent class, it is said to be course grained. =>If no data member is a UDT in a persistent class, it is said to be fine grained. For eg. public class Address { String hno; String street; String state; int pin; }//fine grained class public class Employee { int empno; String name; float salary; Address addr; }//course grained persistent class =>Object oriented flexibility sake, course grained objects are often used in an enterprise application. =>Persistent class is course grained but corresponding table into which the oebjcts has to be persisted is fine grained. This is granularity mismatch. =>By using <component> tag in mapping file this mismatch is addressed. Q)HIbernate Application in which, granularity mismatch is addressed. granularitymismatchapplication Employee.java Address.java Employee.hbm.xml GranularityApplication.java hibernate.cfg.xml SessionUtil.java =>RTH page 11 sql script ---------- drop table employee; create table employee(empno number(8),name varchar2(12),salary number(8,2),deptno number(3), hno varchar2(20),street varchar2(12),city varchar2(15),pin number(6)); insert into employee values(1001,'Rama',40000,10,'7-7-45','Shiv Bagh','Hyderabad',500072); commit; select * from employee; / 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. Q)Explain about "hbm2ddl.auto" property of hibernate configuration file. =>This property instructs Hibernate Engine to genarate the Table creation statement and submit to DBMS by using mapping file information. For eg. <property name="hbm2ddl.auto">create</property> OR
  42. 42. Hibernate Hibernate by L N Rao Page 42 <property name="hbm2ddl.auto">update</property> =>If "create" value is given to this property, even if the table is already exixting, it will be dropped and new table is created. If table is not exixting then any how it will be created. =>"update" instructs Hibernate Engine to create table if it is not there. If it is there, use the already existing table and don't create the new one is the instruction. __________________________________________________________________________________________________________ 14/11/12 -------- --not attended -- inheritance mismatch __________________________________________________________________________________________________________ 15/11/12 -------- Q)Explain about relationship mismatch in a Hibernate Application. =>In relational representation of data i.e. at database level, many to many relationship doesn't exist between tables.Whereas, corresponding persistent object support many-to-many relationship.This is known as relationship mismatch between object oriented and relational representation of data. =>One persistent class declaring a collection of the other persistent objects and vice versa is nothing but many-to-many relationship between persistent objects. For eg. public class Course { List<Student> students; ..... ..... } public class Student { List<Course> courses; ...... ...... } Q)How is relationship mismatch addressed in a Hibernate Application? =>In Hibernate Application to address this mismatch, link table is used. In mapping file <many-to-many> tag is used and appropriate column of link table is specified. Note:- For corresponding application refer to the handout page 9. Q)What are the differences between get() and load() method? =>Both are meant for the same purpose. =>get() returns null if search failed. Whereas load() throws ObjectNotFoundException. =>get() performs eager loading. Whereas load() method performs lazy loading. --persistent class should not be final. --lazy loading concept can not be applied without proxy. __________________________________________________________________________________________________________ 16/11/12 -------- Q)What is lazy loading in the context of Hibernate? =>If Java application is querying for persistent object, instead of querying the database hibernate providing proxy of the queried persistent object with default value to the application and hitting the database only when getter(accessor) method is called is nothing but lazy loading. =>If lazy attribute of <class> tag is given "false" value, lazy loading of a persistent object is disabled even if load() method is called on the session object. =>Sometimes lazy loading improves performance. Q)Explain about caching mechanism in a Hibernate Application. =>Maintain local copy of already requested data at application side in a Java Enterprise Application is nothing but Caching. =>Caching improves performance. =>If we use JDBC as data access mechanism, application developer is responsible to implement caching
  43. 43. Hibernate Hibernate by L N Rao Page 43 through coding. =>Hibernate provides caching support without any programming effort in the application side. =>Two types of caching exists in Hibernate applications 1.)L1(Level 1) cache 2.)L2(Level 2) cache =>L1 cache is nothing but Session level cache. Which is implicitly provided by Hibernate. =>L2 cache is optional unlike L1 and it is externally configurable. =>"caching 16-nov-12.bmp" Q)Hibernate applications in which, level2 cache is configured. =>Refer to the handout. ___________________________________________________________________________________________________________ 19/11/12 -------- Q)What is the purpose of refresh() method of Session interface? =>When record is externally (outside the Hibernate Application) updated, those changes are not implicitely reflected in the corresponding persistent object. i.e. synchronization doesn't happen between database and persistent object. =>refresh method gets modified state of the record to the persistent object. For eg. session.refresh(acc); Generators ---------------- Q)Explain about generators in the context of Hibernate? =>A generator is a Java class that implements org.hibernate.id.IdentifierGenerator interface. =>We have two kinds of generators. 1.)built-in generators 2.)user-defined generators =>Hibernate provided generators are known as built-in generators. For eg. assigned, increment, sequence, native, hilo etc. =>When built-in generators are unable to fulfil our application requirement, we can have our own developed generator class which is nothing but user defined generators. =>Any generator purpose is to auto-generate id field value for the persistent object while persisting it into the database. =>While persisting the persistent object into the database, Hibernate engine takes generator class's help to get the id field value for the persistent object. Q)Explain about "assigned" generator. =>We can specify this generator as follows. <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.id.Assigned"/> </id> =>For this generator type application only is responsible to assign id field value to the persistent object before it is persisted. Q)Explain about "increment" generator? =>Increment generator is applied explicitely as follows.
  44. 44. Hibernate Hibernate by L N Rao Page 44 <id name="accno" column="ANO"> <generator class="increment"/> </id> OR <id name="accno" column="ANO"> <generator class="org.hibernate.id.IncrementGenerator"/> </id> =>generate() method of increment generator retrieves max value of id field of already persistent object, increments it by 1 and returns to Hibernate engine. =>When save method is called on the Session object, HIbernate engine calls generate() method of increment generator, gets the id field value, assigns it to the persistent object and then it is persisted. For eg. Account acc = new Account(); acc.setName("XYZ"); acc.setBalance(8900f); Transaction txn = session.beginTransaction(); java.io.Serializable id = session.save(acc); txn.commit(); System.out.println("Account persisted with id: "+id); Q)Explain about "sequence" generator. =>sequence generator is specified as follows. <id name="accno" column="ANO"> <generator class="org.hibernate.id.SequenceGenerator"/> </id> =>If we configure the sequence generator as above, we should have already created a database object called sequence with a name "hibernate_sequence". For eg. SQL>CREATE SEQUENCE HIBERNATE_SEQUENCE START WITH 20001 INCREMENT BY 1; =>If we want to use user defined sequence name in the application, we have to configure as follows. <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. __________________________________________________________________________________________________________ 20/11/12 -------- Q)Explain about hilo generator? =>"hilo" is one of the built-in generators of Hibernate. =>We can specify "hilo" generator as follows in mapping file. <id name="accno" column="ano"> <generator class="hilo"/> </id> =>When "hilo" generator class is specified as above, by default table name "hibernate_unique_key" and its column "next_hi" is taken as default. We need to create that table with that column in the dbms with some value. =>The generator method of the org.hibernate.id.TableHiLoGenerator takes the high value from the table and adds some low value to it and generates some identifier. i.e. it uses high low(hilo) algorithm to generate the identifier. =>We can specify user defined table also while configuring the generator class in the mapping file. <id name="accno" column="ano"> <generator class="org.hibernate.id.TableHiLoGenerator"> <param name="table">table name</param> <param name="column">column name</param> </generator>
  45. 45. Hibernate Hibernate by L N Rao Page 45 </id> Q)Explain about user defined generator . =>If data access layer developer generated the generator class explicitely without depending upon the built-in generators, it is known as user defined generator. =>For two reasons we go for user defined generator. 1.)when id field has Alpha numerical value. 2.)application specific algorithm is required to be implemented in the auto-generation of id field value. Q)Develop a Hibernate application in which user defined generator is used. userdefinedgeneratorapplication Loan.java(Persistent class) Loan.hbm.xml hibernate.cfg.xml LoanIdGenerator.java StoreApplication.java Loan.java ------------ package com.nareshit.dao; public class Loan { private String loan_id; private String name; private float loan_amount; //setters & getters } Loan.hbm.xml ------------------ <hibernate-mapping> <class name="com.nareshit.dao.Loan"> <id name="loan_id"> <generator class="com.nareshit.dao.LoadIdGenerator"/> </id> <property name="name"/> <property name="loan_amount"/> </class> </hibernate-mapping> StoreApplication.java ---------------------------- Session session = SessionUtil.getSession(); Loan l = new Loan(); l.setName("ABC"); l.setLoan_amount(45000f); session.getTransaction.begin(); System.out.println("Loan persisted with id: "+session.save()); session.getTransaction.commit(); LoanIdGenerator.java ---------------------------- package com.nareshit.dao; import org.hibernate.id.IdentifierGenerator; import org.hibernate.engine.SessionImplementor; import java.io.Serializable; import java.sql.*; class LoanIdGenerator implements IdentifierGenerator { public Serializable generate(SessionImplementor si,Object o) { String lid="HDFCLP";
  46. 46. Hibernate Hibernate by L N Rao Page 46 try { Connection con = si.connection(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select to_char(loanid_sequence.nextval,'FM000000') from dual"); rs.next(); lid = lid + rs.getString(1); rs.close(); st.close(); con.close(); } catch(Exception e) { e.printStackTrace(); } return lid; } } --<property name="hbm2ddl.auto">create</property> sql script ---------- create table loan(loan_id varchar2(12) primary key,name varchar2(12),loan_amount number(9,2)); create sequence loanid_sequence start with 1 increment by 1; select to_char(loanid_sequence.nextval,'FM000000') from dual; ___________________________________________________________________________________________________________ 21/11/12 -------- Q)Explain about IdentityGenerator? =>org.hibernate.id.IdentityGenerator is the built in class for this generator. =>This class's generate method internally uses some identity table of DBMS to generate the id value and return to the hibernate engine. =>Oracle does not support this generator. MySQL, MS SQL Server, DB2 and Sybase support this generator. <id name="accno" column="ano"> <generator class="identity"/> </id> Q)Explain about "native" generator? =>If we specify "native" as the generator in mapping file, if the DBMS is Oracle, "sequence" generator is used to auto generate the value for this field. Similarly, if MySQL DBMS is used, "identity" generator is used. =>There is no generator class for "native" generator. Depending upon the underlying DBMS, supported generator class is used. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------- Relationships ------------------ Q)Explain about realationships(associations) in Data Layer? =>One record in one table is associated with one or more records of another table. =>Association between tables( and there by records ) in data layer is created using primary key and foreign key columns. =>In data layer we have 3 kinds of associations(relationships). 1.)one-to-one 2.)one-to-many 3.)many-to-one =>One-to-one relationship is possible in the two ways. PK => PK PK => FK(unique) =>One-to-many and many-to-one relationship is created using FK column which is non-unique.

×