Hibernate Notes

Share Embed Donate


Short Description

h...

Description

Hibernate Notes & Interview Questions-Answers

1

HISTORY OF HIBERNATE Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style Entity Beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features. Early in 2003, the Hibernate development team began Hibernate2 releases which offered many significant improvements over the first release and would go on to catapult Hibernate as the "de facto" standard for persistence in Java. The current version of Hibernate is Version 3.x. This version introduced new features like a new Interceptor/Callback architecture, user defined filters, and JDK 5.0 as of 2010 Hibernate 3 (version 3.5.0 and up) is a certified implementation of the Java Persistence API 2.0 specification via a wrapper for the Core module which provides conformity with the JSR. HIBERNATE ------------- Hibernate is a Persistence Framework is used to implement persistence logic or database operations.  Hibernate is the King among all the persistence Framework like JPA, IBatis, TopLink, JDO etc.  Architecture of Hibernate is Gavin King (from Redhat).  Hibernate is a ORM (Object Relational Mapping) Tool or Framework which simplifies the Persistence Operations. When we are implementing persistence logic with JDBC, we need to write the following code : try{ get the Connection(DataManager/DataSource); create the required Statement (Statement, PreparedStatement, CallableStatement); prepared the SQL Statement submit the query to database (executeXX()) process the result } catch(Exception e){ Handling the Exception } finally{ cleanup } @ In the case of JDBC, we are responsible for write the code for all the above said operations across the multiple programme. @ Some JDBC statements are common like load the DataBase, Connection through DriverManager, catch the Exception and close the all Connection (1, 2, 3, 5, 7) are common across the multiple program which gives us the code duplication problem. @ In the case of JDBC, we are responsible take the required resources and close the resources after using. If we are not closing the resources that may impact the application performance. @ In the case of JDBC, we are responsible to write SQL statements, If SQL statements are not welltuned that may also impact the application performance. We write the Hibernate in two ways : -------------------------------------------Hibernate 3.1 – Core (XML Based) Hibernate 3.2 – Annotation (XML Based)

2

Hibernate Features : -----------------------1. Hibernate System responsible for taking the Connections, creating Statement and releasing the resources. 2. Hibernate support various Mapping Styles : i. Simple Mapping ii. Collection Mapping iii. Inheritance Mapping [a] Table per sub-class Mapping [b] Table per class Mapping [c] Table per concrete class Mapping iv. Association Mapping [a] One-to-One Mapping [b] One-to-Many Mapping [c] Many-to-Many Mapping v. Other Mapping. 3. Hibernate Supports two ways to manage Connection : [i] DriverManager Connection [ii] DataSource Connection 4. Hibernate supports two ways to manage Transactions : [i] JDBC Transaction [ii] JTA Transaction (EJB Container or Spring Container) 5. Hibernate provides various Primary Key generation algorithm. 6. Hibernate has in-built support for Batch Updates. 7. Hibernate provides various Caching mechanisms. 8. Hibernate provides various Object Oriented Query Language (OOQL) : [a] HQL (Hibernate Query Language) [b] QBC (Query By Criteria) [c] QBE (Query By Example) 9. Hibernate System uses many Persistent best practices and forces the developer to use them for better performance.

Hibernate Architecture :

Configuration Our Application Client Code

Connection Provider

JDBC API

Connection

JNDI API

Transaction Factory

JTA API

SessionFactory Session Transaction

DB Reposity

JNDI Reposity

Fig : Hibernate Runtime System Configuration or AnnotationConfiguration : -------------------------------------------------- There are Classes available in org.hibernate.cfg Package.  This is the first class that will be instantiated by the Hibernate application.  We can use Configuration or AnnotationConfiguration class object for 2 tasks :(i) calling configure() method or configure(String) method. (ii) calling buildSessionFactory() method.  configure() method is responsible for following tasks :(i) Reading the data from Hibernate Configuration object. (ii) Reading the data from all the Hibernate mapping documents specified in the Configuration document.  buildSessionFactory() method is responsible for creating SessionFactory object.  Configuration or AnnotationConfiguration object is Single Threaded and Short Lived.

3



Once SessionFactory object is created then there is no use with Configuration or AnnotationConfiguration object.

SessionFactory : -------------------A SessionFactory is an interface available in org.hibernate package. SessionFactory object is MultiThreaded and Long Lived. SessionFactory is clients for connection provider and Transaction Factory. The SessionFactory is created from a Configuration object, and as its name implies it is a factory for Session objects. The SessionFactory object is used by all the threads of an application. It is a thread safe object. The SessionFactory can also provide caching of persistent objects. The main use of session factory object is to get the session object for the application. SessionFactory hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level. SessionFactorys are immutable. The behaviour of a SessionFactory is controlled by properties supplied at configuration time. These properties are defined on Environment. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code. Creating object of SessionFactory : SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory(); When we call buildSessionFactory() method on Configuration object then following tasks will happen :    

Set the defaults to many parameters like BatchSize, FetchSize etc. Generates and Caches the SQL Quires required. Selects the Connection provider. Selects the Transaction Factory.

One SessionFactory object is created per database. Multiple SessionFactory objects (each requiring a separate Configuration) are created when connecting to multiple databases. HibernateUtil.java Class for one Database import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { static SessionFactory factory = null; static{ Configuration cfg = new Configuration(); cfg = cfg.configure("hibernate.cfg.xml"); factory = cfg.buildSessionFactory(); } public static SessionFactory getSessionFactory(){ return factory; } } HibernateUtil.java Class for two Databases import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { static SessionFactory orafactory = null; static SessionFactory jlcfactory = null; static{ Configuration cfg = new Configuration(); Configuration cfg1 = cfg.configure("oracle.cfg.xml"); orafactory = cfg1.buildSessionFactory(); Configuration cfg2 = cfg.configure("mysql.cfg.xml"); jlcfactory = cfg2.buildSessionFactory();

} public static SessionFactory getSessionFactory(int x){

4

}

if(x==1){ return orafactory; }else{ return jlcfactory; }

} Session : ----------This is an interface available in org.hibernate Package. The representation of single unit of work with the Java application and the persistence database is done by this object. The wrapping of a JDBC connection is the emphasized role of a Session interface object. This is the major interface between Java application and Hibernate. This is a runtime interface. The beginning and ending of a transaction cycle is bounded by the Session interface. The purpose of this interface is to perform create, read and delete operations for the objects that are mapped with entity classes. Session session = sessionFactory.openSession();    



Session Object is single Threaded and short Lived. Session represents period of time where user can do multiple database operations. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier. Session object (i) use TransactionFactory to get the Transaction. (ii) get the Connection from Connection Provider. It allows us to create query objects to retrieve persistent objects.

Transaction : ---------------When Transaction is started, then following tasks will happened :  Session Cache will be created.  Connection will be taken and will be associated with the current session. While    

Transaction is commit, following tasks will happen : Session will be flushed. Session Cache will be destroyed. Commit will be issued to database. Connection will be realised.

The general flow of Hibernate communication with RDBMS is : ------------------------------------------------------------------------ The Hibernate configuration is to be loaded and creation of configuration object is done. The mapping of all hbm files will be performed automatically.  Creation of session factory from the configuration object.  Obtain a session from the session factory.  Creation of HQL Query  Execution of the query in order to get the list of containing java objects. DAO + Hibernate (CURD Operation) -----------------------------------------DAO (Data Access Object) is J2EE Design Pattern. Problem : We can store our Enterprise data in any repository like Flat File, XML Files, LDAP, RDBMS etc. Note - Commonly used Repository is RDBMS. When we change the Persistence Storage or Persistence Technology or Framework then we have to change the Persistence Logic.

5

When We change the Persistence Logic then we may need to change the other Layers of the Application. This may give maintenance. Context : When we are interacting with Persistence Storage. Solution : Use DAO Design Pattern (J2EE Pattern) 1. Follow the Interface model. 2. Centralize the DAO instance creation in Factory DAO class. 3. DAO’s are stateless so create one and only instance for DAO using Singlton Pattern (GOF Pattern) ------------- Persistence Layer ---------------

Business Layer main() // Client Code

Integration Layer Interface CustomerDAO{ addCustomer(); } class FactoryDAO{ HCD // Siglton class }

EIS Layer class HibernateCustomer DAOImpl{ addCustomer(){ // Client Code } }

Hibernate Runtime System

J D B C

DataBase

EIS- Enterprise Information System

Hibernate Util 1. Making one SessionFactory for entire Application per DataBase. 2. Reading the data from Hibernate Configuration document and all the mapping document only once. 3. Reducing Code duplication. Hibernate Template Reducing the code duplication. Note : Hibernate uses XML document or properties file to define the object / relational mapping. The ORM File (.hbm file) contains the mapping between the Java object and corresponding database table. Hibernate Mapping Type ----------------------------1. Simple Mapping : When our Persistence Class fields or variables or property of simple type like Primitives, Wrappers, String, Date etc. then use the Simple Mapping. 2.

Collection Mapping : When our Persistence class fields or variables or property of Collection types like List, Set, Map, Array then use Collection Mapping.

3.

Inheritance Mapping : When Multiple Persistence Classes are in Inheritance relationship then use Inheritance Mapping. We can implement Inheritance Mapping in 3 ways :[a] Table per sub-class Mapping [b] Table per class Mapping [c] Table per concrete class Mapping

4.

Association Mapping : If we want to establish the relationship among different Persistence Classes, then we have use Association Mapping. Depending on the Cardinality, there are 3 types of Association Mapping : [a] One-to-One Mapping [b] One-to-Many Mapping [c] Many-to-Many Mapping Depending on the Directionality, there are 2 types : 1. Uni-Directional Relationship

6

2. @ @

Bi- Directional Relationship

Cardinality represents No. of objects participating in relationship on both the sides. Directionality represents whether we can access the Data in one direction only or both the directions.

Inheritance Mapping : -------------------------Hibernate supports the three basic inheritance mapping strategies: o table per class hierarchy o table per subclass o table per concrete class In addition, Hibernate supports a fourth, slightly different kind of polymorphism: o implicit polymorphism It is possible to use different mapping strategies for different branches of the same inheritance hierarchy. You can then make use of implicit polymorphism to achieve polymorphism across the whole hierarchy. However, Hibernate does not support mixing , and mappings under the same root element. It is possible to mix together the table per hierarchy and table per subclass strategies under the the same element, by combining the and elements (see below for an example). It is possible to define subclass, union-subclass, and joined-subclass mappings in separate mapping documents directly beneath hibernate-mapping. This allows you to extend a class hierarchy by adding a new mapping file. You must specify an extends attribute in the subclass mapping, naming a previously mapped superclass. Previously this feature made the ordering of the mapping documents important. Since Hibernate3, the ordering of mapping files is irrelevant when using the extends keyword. The ordering inside a single mapping file still needs to be defined as superclasses before subclasses. Table per class hierarchy Suppose we have an interface Payment with the implementors CreditCardPayment, CashPayment, andChequePayment. The table per hierarchy mapping would display in the following way: ... ... ... ...

7

Exactly one table is required. There is a limitation of this mapping strategy: columns declared by the subclasses, such as CCTYPE, cannot have NOT NULL constraints. Table per subclass A table per subclass mapping looks like this: ... ... ... ... Four tables are required. The three subclass tables have primary key associations to the superclass table so the relational model is actually a one-to-one association. Table per subclass: using a discriminator Hibernate's implementation of table per subclass does not require a discriminator column. Other object/relational mappers use a different implementation of table per subclass that requires a type discriminator column in the superclass table. The approach taken by Hibernate is much more difficult to implement, but arguably more correct from a relational point of view. If you want to use a discriminator column with the table per subclass strategy, you can combine the use of and , as follows: ... ... ... ...

8

The optional fetch="select" declaration tells Hibernate not to fetch the ChequePayment subclass data using an outer join when querying the superclass. Mixing table per class hierarchy with table per subclass You can even mix the table per hierarchy and table per subclass strategies using the following approach: ... ... ... ... For any of these mapping strategies, a polymorphic association to the root Payment class is mapped using . Table per concrete class There are two ways we can map the table per concrete class strategy. First, you can use. ... ... ... ... Three tables are involved for the subclasses. Each table defines columns for all properties of the class, including inherited properties.

9

The limitation of this approach is that if a property is mapped on the superclass, the column name must be the same on all subclass tables. The identity generator strategy is not allowed in union subclass inheritance. The primary key seed has to be shared across all unioned subclasses of a hierarchy. If your superclass is abstract, map it with abstract="true". If it is not abstract, an additional table (it defaults to PAYMENT in the example above), is needed to hold instances of the superclass. Table per concrete class using implicit polymorphism An alternative approach is to make use of implicit polymorphism: ... ... ... Notice that the Payment interface is not mentioned explicitly. Also notice that properties of Payment are mapped in each of the subclasses. If you want to avoid duplication, consider using XML entities (for example, [ ] in the DOCTYPE declaration and&allproperties; in the mapping). The disadvantage of this approach is that Hibernate does not generate SQL UNIONs when performing polymorphic queries. For this mapping strategy, a polymorphic association to Payment is usually mapped using . Mixing implicit polymorphism with other inheritance mappings Since the subclasses are each mapped in their own element, and since Payment is just an interface), each of the subclasses could easily be part of another inheritance hierarchy. You can still use polymorphic queries against the Payment interface.

10

... ... ... ... Once again, Payment is not mentioned explicitly. If we execute a query against the Payment interface, for example from Payment, Hibernate automatically returns instances of CreditCardPayment (and its subclasses, since they also implement Payment), CashPayment and ChequePayment, but not instances ofNonelectronicTransaction. Limitations There are limitations to the "implicit polymorphism" approach to the table per concrete-class mapping strategy. There are somewhat less restrictive limitations to mappings. The following table shows the limitations of table per concrete-class mappings, and of implicit polymorphism, in Hibernate. Table : Features of inheritance mappings Inheritance strategy

Polymorph Polymorphic Polymorphic ic manyone-to-one one-to-many to-one

Polymorph ic many- Polymorphic load()/get() to-many

table per classhierarchy







table per subclass







table per concrete-class subclass) table per concrete class (implicit polymorphism )

not supported

e="true"only)

not supported

11

s.createCriteria ( Restrictions.idEq(id) ). uniqueResult()

Association Mapping : -------------------------# One-to-One Mapping through Core (Uni-Directional Mapping) Consider the following relationship between Student and Address entity. * One Student contains one Address. * One Address belongs to one Student.

According to the relationship each student should have a unique address. To create this relationship we need to have a STUDENT and ADDRESS table. The relational model is shown below.

To create the STUDENT and ADDRESS table we need to create the following hibernate mapping files. Student.hbm.xml is used to create the STUDENT table. We use the many-to-one element to create the one-to-one relationship between the Studentand Address entities. We do this my making the STUDENT_ADDRESS column unique in the STUDENT table. Address.hbm.xml is used to create the ADDRESS table.

12

Now create the hibernate configuration file and add all the mapping files. hibernate.cfg.xml org.mysql.jdbc.Driver jdbc:mysql://localhost/school root sandeep 1 org.hibernate.dialect.HSQLDialect true update After creating the configuration file, generate java class files using Hibernate Tools. The following classes will be generated. Student.java package com.vaannila.student; public class Student implements java.io.Serializable { private long studentId; private String studentName; private Address studentAddress; public Student() {} public Student(String studentName, Address studentAddress) { this.studentName = studentName; this.studentAddress = studentAddress; } // Setters and Getters } Address.java package com.vaannila.student; public class Address implements java.io.Serializable { private long addressId; private String street;

13

private String city; private String state; private String zipcode; public Address() {} public Address(String street, String city, String state, String zipcode) { this.street = street; this.city = city; this.state = state; this.zipcode = zipcode; } // Setter and Getter } Create the Main class to run the example. Main.java package com.vaannila.student; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import com.vaannila.util.HibernateUtil; public class Main { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Address address1 = new Address("OMR Road", "Chennai", "TN","600097"); Address address2 = new Address("Ring Road", "Banglore","Karnataka", "560000"); Student student1 = new Student("Eswar", address1); Student student2 = new Student("Joe", address2); session.save(student1); session.save(student2); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } } On executing the Main class we will see the following output. The Student table has two records.

The Address table has two record.

14

Each student record points to a different address record, this illustrates the one-to-one mapping.

# One-to-Many Mapping through Core --------------------------------------------Consider the following relationship between Student and Phone entity.

According to the relationship a student can have any number of phone numbers. To create this relationship we need to have a STUDENT, PHONE and STUDENT_PHONE table. The relational model is shown below.

To create the STUDENT and PHONE table we need to create the following hibernate mapping files. Student.hbm.xml is used to create the STUDENT and STUDENT_PHONE table. we use many-to-many element to create the one-to-many relationship between the Student and Phone entities. Since a student can have any number of phone numbers we use a collection to hold the values. In this case we use Set. Many-to-many element is usually used to create many-to-many relationship, here we place the unique constraint on the PHONE_ID column, this makes the relationship one-to-many. Phone.hbm.xml is used to create the PHONE table.

15

Now create the hibernate configuration file and add all the mapping files. hibernate.cfg.xml Same as One-to-One Mapping After creating the configuration file, generate java class files using Hibernate Tools. The following classes will be generated. Student.java package com.vaannila.student; public class Student implements java.io.Serializable { private long studentId; private String studentName; private Set studentPhoneNumbers = new HashSet(0); public Student() {} public Student(String studentName) { this.studentName = studentName; } public Student(String studentName, Set studentPhoneNumbers) { this.studentName = studentName; this.studentPhoneNumbers = studentPhoneNumbers; } // Setter and Getter } Phone.java package com.vaannila.student; public class Phone implements java.io.Serializable { private long phoneId; private String phoneType; private String phoneNumber; public Phone() {} public Phone(String phoneType, String phoneNumber) { this.phoneType = phoneType; this.phoneNumber = phoneNumber; } // Setter and Getter } Create the Main class to run the example. Main.java

16

package com.vaannila.student; public class Main { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Set phoneNumbers = new HashSet(); phoneNumbers.add(new Phone("house","32354353")); phoneNumbers.add(new Phone("mobile","9889343423")); Student student = new Student("Eswar", phoneNumbers); session.save(student); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } } On executing the Main class we will see the following output. The STUDENT table has one record.

The PHONE table has two records.

The STUDENT_PHONE table has two records to link the student and phone numbers.

A single student record points to two phone numbers, this illustrates the one-to-many mapping. # Many-to-one Mapping through Core --------------------------------------------Consider the following relationship between Student and Address entity.

According to the relationship many students can have the same address. To create this relationship we need to have a STUDENT and ADDRESS table. The relational model is shown below.

17

To create the STUDENT and ADDRESS table we need to create the following hibernate mapping files. Student.hbm.xml is used to create the STUDENT table. The many-to-one element is used to create the many-to-one relationship between the Studentand Address entities. The cascade option is used to cascade the required operations to the associated entity. If the cascade option is set to all then all the operations will be cascaded. For instance when you save a Student object, the associated Address object will also be saved automatically. Address.hbm.xml is used to create the ADDRESS table. Now create the hibernate configuration file and add all the mapping files. Hibernate.cfg.hml Same as Previous After creating the configuration file, generate java class files using Hibernate Tools. The following classes will be generated. Student.java

18

package com.vaannila.student; public class Student implements java.io.Serializable { private long studentId; private String studentName; private Address studentAddress; public Student() {} public Student(String studentName, Address studentAddress) { this.studentName = studentName; this.studentAddress = studentAddress; } // Setter and Getter } Address.java package com.vaannila.student; public class Address implements java.io.Serializable { private private private private private

long addressId; String street; String city; String state; String zipcode;

public Address() { } public Address(String street, String city, String state, String zipcode) { this.street = street; this.city = city; this.state = state; this.zipcode = zipcode; } // Setter and Getter } Create the Main class to run the example. Main.java package com.vaannila.student; public class Main { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Address address = new Address("OMR Road", "Chennai", "TN","600097"); //

By using cascade=all option the address need not be saved explicitly when the student object is persisted the address will be automatically saved. //session.save(address);

19

Student student1 = new Student("Eswar", address); Student student2 = new Student("Joe", address); session.save(student1); session.save(student2); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } } On executing the Main class we will see the following output. The Student table has two records.

The Address table has one record.

Both the student records points to the same address record, this illustrates the many-to-one mapping.

# Many-to-Many Mapping through Core ----------------------------------------------Consider the following relationship between Student and Course entity.

According to the relationship a student can enroll in any number of courses and the course can have any number of students. To create this relationship we need to have a STUDENT, COURSE and STUDENT_COURSE table. The relational model is shown below.

To create the STUDENT and COURSE tables you need to create the following hibernate mapping files. Student.hbm.xml is used to create the STUDENT and STUDENT_COURSE table.

20

We use many-to-many element to create the many-to-many relationship between the Studentand Course entities. Since a student can enroll in any number of courses we use a collection to hold the values. In this case we use Set. Course.hbm.xml is used to create the COURSE table. Now create the hibernate configuration file and add all the mapping files. Hibernate.cfg.hml Same as Previous After creating the configuration file, generate java class files using Hibernate Tools The following classes will be generated. Student.java package com.vaannila.student; public class Student implements java.io.Serializable { private long studentId; private String studentName; private Set courses = new HashSet(0); public Student() { } public Student(String studentName) { this.studentName = studentName; } public Student(String studentName, Set courses) { this.studentName = studentName; this.courses = courses; } // Setter and Getter }

21

Course.java package com.vaannila.student; public class Course implements java.io.Serializable { private long courseId; private String courseName; public Course() { } public Course(String courseName) { this.courseName = courseName; } // Setter and Getter } Create the Main class to run the example. Main.java package com.vaannila.student; public class Main { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Set courses = new HashSet(); courses.add(new Course("Maths")); courses.add(new Course("Computer Science")); Student student1 = new Student("Eswar", courses); Student student2 = new Student("Joe", courses); session.save(student1); session.save(student2); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } } On executing the Main class you will see the following output. The STUDENT table has two records.

The COURSE table has two records.

22

The STUDENT_COURSE table has four records to link the student and courses.

Each student has enrolled in the same two courses, this illustrates the many-to-many mapping.

# Hibernate Mapping Component through Core -------------------------------------------------------In this example we will learn how to map components using Hibernate. Consider the following relationship between Student and Address entity.

According to the relationship each student should have a unique address. Since the Student and Address entities are strongly related (composition relation), it is better to store them in a single table. The relational model is shown below.

Student.hbm.xml is used to create the STUDENT table.

23

The component element is used to map all the Address entity fields to the STUDENT table. In Hibernate terms the Address entity is called the component and it cannot have its own primary key, it uses the primary key of the enclosing Student entity. Now create the hibernate configuration file. hibernate.cfg.xml org.mysql.jdbc.Driver jdbc:mysql://localhost/school root sandeep 1 org.hibernate.dialect.HSQLDialect true update After creating the configuration file, generate java class files using Hibernate Tools. The following classes will be generated. We will still have a Student and Address class seperately but they will be mapped to only one table. Student.java package com.vaannila.student; public class Student implements java.io.Serializable { private long studentId; private String studentName; private Address studentAddress; public Student() { } public Student(String studentName) { this.studentName = studentName; } public Student(String studentName, Address studentAddress) { this.studentName = studentName; this.studentAddress = studentAddress; } // Setter and Getter } Address.java package com.vaannila.student; public class Address implements java.io.Serializable { private String street; private String city;

24

private String state; private String zipcode; public Address() { } public Address(String street, String city, String state, String zipcode) { this.street = street; this.city = city; this.state = state; this.zipcode = zipcode; } // Setter and Getter } Create the Main class to run the example. Main.java ackage com.vaannila.student; public class Main { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Address address = new Address("OMR Road", "Chennai", "TN","600097"); Student student = new Student("Eswar", address); session.save(student); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } } On executing the Main class you will see the following output.

Each student has one address and the values are stored in the same STUDENT table.

25

Working with Primary Key : --------------------------------Hibernate supports to Configure both the types of Primary Key : 1. Simple Primary Key 2. Composite Primary Key Simple Primary Key : Hibernate Provides various Built-in Simple Primary Key Generators follows :  increment  hilo (high low)  sequence  seqhilo  uuid (Universal User ID)  guid  identity  native  assigned  select # using increment # using uuid # using sequence SID_SEQ # using hilo hi_value next_value 10 # using seqhilo SID_SEQ 100 If these Built-In ID Generators are not suitable for our requirements then we can write our own Custom ID Generators. Steps to write Custom ID Generators through Core: ------------------------------------------------------------1. Write our own ID Generator by implementing the interface called IdentifierGenerator which is available in org.hibernate.id.IdentifierGenerator Package. 2. public Serializable generate(SessionImplementor si, Object obj)throws HibernateException

26

3. 4.

Write the required id generation logic in generate() method

Steps to write Custom ID Generators through Annotation: -------------------------------------------------------------------1. Create a custom class as follows : public class SIDGenerator{ public static String getNextSid(){ // write code } } 2. in Client side : Student stu=new Student(SIDGenerator.getNextSid(), “Krishu”,”Patna”,8792461475); session.save(stu); Composite Primary Key : -----------------------------Hibernate does not provides any Built-in ID Generators for Composite Primary Key, We have to write also Custom ID Generator. Steps to configure Composite Primary Keys through Core -------------------------------------------------------------------

1.

2.

3.

4.

5.

Write one custom class which contains composite fields: public class SID{ private String bid; private String sid; // Default Constructor & parameteraized Constructor // setters-getters method } Write one custom class which generate composite key: public class SIDGenerator{ public static SID getNextSid(String bid){ // write code } } in Student.java (Persistence class) public class Student{ private SID studebtId; ………………………. } in Student.hbm.xml File …………………….. in Client class: // insert record SID id= SIDGenerator.getNextSid(“30”); // 30 is a bId, sId will auto generate. Student stu=new Student(id,”Krishu”,”Patna”,999999); session.save(stu); // select record Student stu=(Student)session.load(Student.class, new SID(“30”,”101”)); System.out.println(stu.getStudentId().getBid()); System.out.println(stu.getStudentId().getSid()); System.out.println(stu.getSname());

27

// 30 is bid, 101 is sid. Steps to configure Composite Primary Keys through Annotation ---------------------------------------------------------------------------

1.

2.

3.

4.

Write one custom class which contains composite fields and implements with Serializable: @Embeddable public class SID implements Serializable{ private String bid; private String sid; // Default Constructor & parameteraized Constructor // setters-getters method } Write one custom class which generate composite key: public class SIDGenerator{ public static SID getNextSid(String bid){ // write code } } in Student.java (Persistence class) @Entity @Table(name=”students”) public class Student{ @Id @Embedded @AttributeOverrides({ @AttributeOverride(name=”bid”,column=@Column(name=”bid”)), @AttributeOverride(name=”sid”,column=@Column(name=”sid”)) }) private SID studebtId; ………………………. } in Client class: // insert record SID id= SIDGenerator.getNextSid(“30”); // 30 is a bId, sId will auto generate. Student stu=new Student(id,”Krishu”,”Patna”,999999); session.save(stu); // select record Student stu=(Student)session.load(Student.class, new SID(“30”,”101”)); System.out.println(stu.getStudentId().getBid()); System.out.println(stu.getStudentId().getSid()); System.out.println(stu.getSname());

// 30 is bid, 101 is sid. Types of Object States : ---------------------------Persistence Class Object can be found in three states : 1. Transient State 2. Persistent State 3. Detached State Transient State : When Persistent Class object is newly created and not participated any session operations then that object is called as Transient Object. The state of that object is called Transient State. Transient Object does not Contain any Identify or Primary Key. Persistent State : When Persistent Class object is participated any session operations then that object is called as persistent object. The State of that object is called Persistent State. Persistent Object contains any Identity or Primary Key. * Any Modification happed on the Persistent Object will be reflected to Database.

28

Detached State : When Persistent class object is participated any session operations and removed from Session Cache then that object is called as Detached Object. The State of that object is called Detached State. Detached object contains any Identity or Primary Key. Transaction Management : -------------------------------Transaction is the process of performing multiple database operations as one Unit with all-nothing criteria i.e. when all the database operations in the Unit are successful then Transaction is successful and should be committed. When any one database operation in the unit is failed then Transaction is failed and should be rolled back. When we implement Transactions properly in our application, it guarantees ACID Properties. A - Atomicity C - Consistency I - Isolation D – Durability Atomicity : Definition of Transaction. Consistency : When we are running the transaction we may enforce business rules as per the application requirement. Our application should be consistent when any business rule is failed. Otherwise we may get some inconsistent rules. Consider the withdraw operation : 1. Minimum balance is 5 K 2. Only 5 withdraw per day. 3. if(ATM){ limit : 50 K } if(Branch){ limit : 5 L } Isolation : We can run multiple transactions concurrently. These concurrently running multiple transactions should not disturb other transaction i.e. multiple transactions should run isolately. Case A Consider the case where multiple transactions running concurrently and using multiple Account rows of Accounts Table. Transaction Tx1 Tx2 Tx3

-> -> ->

Operations Withdraw from Withdraw from Withdraw from

A/c No. 101 102 103 A/c No. 101 102 103

Case B Consider the case where multiple transaction running concurrently and using single account row of accounts table. Account No. : 38746292 1. Transfer (withdraw) 2. bank teller (withdraw / deposit) 3. loan EMI (withdraw) In Case B, we may get some problems which are called as Transaction Concurrency Problems. There are three Transaction Concurrency Problems :

29

1. 2. 3.

Dirty Read Problem Repeatable Read Problem Phantom Read Problem

To Avoid these problems, we have to apply the one of the following required Transaction Isolation Level : 1. READ_UNCOMMITTED 2. READ_COMMITTED 3. REPEATABLE_READ 4. SERIALIZABLE Durability : Our enterprise data should be available for long time (as long as our enterprise is running). We have to protect our data from crashes, failures, so we have to implement proper backup and recovery mechanism and proper logging mechanism. Dirty Read Problem : When Transaction reads the Dirty value (Modified but not Committed) then we may get some inconsistent results.  To avoid Dirty reads, we have to lock the column (Cell).  To lock the column, we have to apply Isolation Level called READ_COMMITTED. Repeatable Read Problem : When a Transaction is reading the same row Repeatedly, we may get different kind of problem is called Repeatable Read Problem.  To avoid Repeatable Read Problem, we have to lock the row.  To Lock the Row, we have to apply Isolation Level called REPETABLE_READ. Phantom Read Problem : When the Transaction is reading the set of Rows repeatedly, we may get different set of rows in different reads. This kind of problem is called Phantom Read Problem.  To avoid Phantom Reads, we have to lock the entire Table.  To lock the table, we have to apply Isolation Level called SERIALIZABLE.

Types of Transactions : 1. 2.

Local Transactions Distributed Transactions

Local Transactions : When the single Database is participating in the Transaction Operations then it is called as Local Transactions. Distributed Transactions : When a two or more databases are participating in the Transaction Operations then it is called as Distributed Transactions

Types of Transactions : 1. Flat Transactions 2. Nested Transactions Example - Flat Transaction : begin tx1 op1 op2 op3 end tx2 Example - Nested Transaction : begin tx1 op1 op2 begin tx2 op3 op4 end tx2 op5 begin tx3

30

op6 op7 end tx3 op8 end tx1 Example Make a Trip : Mon-Fri (Bangalore -> Pune -> Delhi -> Mumbai -> Bangalore) JDBC Transaction Management ------------------------------------1. Specify the Transaction Boundaries Connection con = null; try{ con=…………….; con.setAutoCommit(false); op1; op2; op3; con.commit(); } catch(Exception e){ if(con != null) con.rollback; } finally{ if(con != null) con.close(); } 2. Specify the Isolation Levels con.setTransactionIsolation(1/2/4/8); Q. What will happen when we not specifying the Isolation Level ? Ans : Database Vendor specific Default Transaction Isolation Level will be used. Q. How can we get Database Vendor specific Default Transaction Isolation Level ? Ans : int getDefaultTransactionIsolation() of Database MetaData. Default Transaction Isolation Level : MySQL – 4,

Oracle – 2

Hibernate Transaction Management ------------------------------------------1. Specifying the Transaction Boundaries Transaction tx = null; try{ tx = session.beginTransaction(); op1; op2; op3; tx.commit(); } catch(Exception e){ if(tx != null) con.rollback; } 2. Specifying the Isolation Levels Write the following property in hibernate.cfg.xml 1/2/4/8

31

Q.

Can we specify different Isolation Levels for Transaction running in Hibernate Application ? Ans : No Q.

Can we specify different Isolation Levels for Transaction running in JDBC Application ? Ans : Yes Dirty Read

Repeatable Read

Phantom Read

Lock Type

Concurrency

READ_UNCOMMITED

No

No

No

Not Lock

READ_COMMITED

Yes

No

No

Column

REPEATABLE_READ

Yes

Yes

No

Row

SERIALIZABLE

Yes

Yes

Yes

Table

R e d u c e

JDBC

Hibernate

JPA

EJB2/EJB3

Spring

Local Tx.

Yes

Yes

Yes

Yes

Yes

Distributed Tx.

No

Yes (CME) No (Non-CME)

Yes (CME) No (Non-CME)

Yes

Yes

Flat Tx.

Yes

Yes

Yes

Yes

Yes

Nested Tx.

No

No

No

No

Yes

Query Language Supported by Hibernate : 1. 2. 3. 4. 5.

HQL (Hibernate Query Language) QBC (Query By Criteria) QBE (Query BY Example) Native SQL Queries Named SQL Queries

Hibernate Query Language (HQL) : Hibernate Query Language (HQL) is extremely powerful query language. HQL is much like SQL and are case-insensitive, except for the names of the Java Classes and properties. HQL is used to execute queries against database. Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application. HQL is based on the relational object models and makes the SQL object oriented. HQL uses Classes and properties instead of tables and columns. HQL is extremely powerful and it supports Polymorphism, Associations, Much less verbose than SQL. Why to use HQL?



Full support for relational operations: HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns.



Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is easy to use. This elemenates the need of creating the object and populate the data from result set.



Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any.

32



Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the applications.



Support for Advance features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.



Database independent: Queries written in HQL are database independent (If database supports the underlying feature).

Understanding HQL Syntax Any Hibernate Query Language may consist of following elements: Clauses Aggregate functions Subqueries Clauses in the HQL are:  from  select  where  order by  group by Aggregate functions are:  avg(...), sum(...), min(...), max(...)  count(*)  count(...), count(distinct ...), count(all...) Subqueries Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the underlying database supports it.

Hibernate Cache -------------------Cache is representation of Database near to Application. When we cache the Read mostly data, we can reduce the No. of round trips between our application server and database server which increases performance of our application. In general, we can have 3 types of cache scopes : 1. Trancational Scope Cache 2. Process Scope Cache 3. Clustered Scope Cache. Trancational Scope Cache : This kind of cache will created whenever the Transaction is started and Runs as long as Transaction is running. Transactional scope cache will be destroyed whenever the Transaction ends either by commit or by rollback. Process Scope Cache : This kind of cache can be accessed by multiple Transactions running in the Application or process. Clustered Scope Cache : When our enterprise application is large scale application then we must use cluster environment where multiple servers will be clustered and integrated with LBS (Load Balancing Server) for routing the requests. In the case of Clustered Scope Cache, when one node caches the data then same data will be replicated to other nodes automatically. Fig. : Hibernate Cache Architecture First Level Cache : * When we create a Transaction then we have to process more tasks like :  Configuration  buildSessionFactory

33

   

openSession create Transaction call persistence class object process all tasks like updation.

* Multiple persistence object store in SessionCache. When tx.commit() method will be invoked then all transaction store in database and flushing all session object and closing transaction and all. * Tasks are : 1. Session cache is the first level cache. 2. Session cache is the Transactional Scope Cache. 3. Session cache is enabled by default and should not be disabled. 4. Whenever we insert or update or select or delete the records then those persistence objects will be placed automatically in session cache. 5. We can remove the persistence object from session cache using – evict(obj) & clear() Second Level Cache :  Query Cache is the second level cache.  Query Cache can be process scope or cluster scope cache.  Query Cache is disabled by default. You have to enable explicitly if required.  Whenever we execute the Hibernate queries (HQL, QBC etc. – select sql statement) then all the records returned by select statement will be placed in query cache. Steps to implements Query Cache : ---------------------------------------1. Enable the query cache by writing the following property in hibernate configuration doc. true 2. Specify the Required cache provider in hibernate configuration doc. org.hibernate.cache.EhCacheProvider Note : Cache provider supported by Hibernate : 1. HashTableCacheProvider 2. EhCacheProvider (for small application) 3. OSCacheProvider (not mostly use) 4. SWarmCacheProvider (not mostly use) 5. TreeCacheProvider (Jboss Cache Provider) 3. Specify the required caching concurrency strategies in Hibernate mapping doc. Usage value can be one of the following : i> read-only ii> nonstrict-read-write

iii> read-write

iv> transactional

Note : We have to specify the caching concurrency strategies for class, Collections and Associations. Example : class Student{ int cid; String cname; Set emails; -----------} ----------- --------

34

4. Call setCacheable() method with true value on Query or Criteria or SQLQuery objects. HQL Query q=session.createQuery(“from Customer”); q.setCacheable(true); List list=q.list(); QBC Creteria ct=session.createCriteria(Customer.class); ct.setCacheable(true); List list=ct.list(); 5. Specify the Storage Implementations and Expiration Policies. Note : This will change from cache provider to provider. ehcache.xml (place in src folder)

Caching Concurrency Strategies -----------------------------------There are four Caching Concurrency Strategies : * Read-only * non strict-read-only * read-write * transactional

 

This strategies will allow us to apply the required locking mechanism for the persistence objects. Which are available in Query cache. In this case of Process Scope or Clustered Scope Cache, one persistent object can be accessed by multiple Transaction running con-currently. This may leads to some concurrency problems like Dirty Read Problem, Repeatable Read Problem and Phantom Read Problem.

To avoid the problems, we have to required Transactional Isolation Levels as shown in Table : Hibernate Caching Concurrency Strategies :

Concurrency Strategy Transactional Read-write Non-Strictread-write Read Only

CME

Non CME

Supports UNCOMMITED

Supports COMMITED

Supports Read

Supports Serializable

Yes

No

Yes

Yes

Yes

No

Yes

Yes

Yes

Yes

No

No

Yes

Yes

Yes

No

No

No

Yes

Yes

No

No

No

No

35

Hibernate Caching Providers : Cache provider Class Flash Table cache provider Eh cache provider O cache provider Swarn cache provider Tree cache provider

Query Cache Support

Read only

Cluster type

Non strict Read only

Read Write

Transactional

CME

Non CME

Production Support

Memory

Yes

Yes

No

Yes

Yes

No

Yes

Yes

No

Memory

Yes

Yes

No

Yes

Yes

No

Yes

Yes

Yes

Memory Disk

Yes

Yes

No

Yes

Yes

No

Yes

Yes

Yes

Clustered

No

Yes

Yes

Yes

No

No

Yes

Yes

Yes

Clustered

Yes

Yes

Yes

No

No

Yes

Yes

No

Yes

Storage Type

Filter : Hibernate3 provides an innovative new approach to handling data with "visibility" rules. A Hibernate filter is a global, named, parameterized filter that can be enabled or disabled for a particular Hibernate session. Hibernate3 has the ability to pre-define filter criteria and attach those filters at both a class level and a collection level. A filter criteria allows us to define a restriction clause similar to the existing "where" attribute available on the class and various collection elements. These filter conditions, however, can be parameterized. The application can then decide at runtime whether certain filters should be enabled and what their parameter values should be. Filters can be used like database views, but they are parameterized inside the application. In order to use filters, they must first be defined and then attached to the appropriate mapping elements. To define a filter, use the element within a element: This filter can then be attached to a class: ... Or, to a collection:

36

Or, to both or multiples of each at the same time. The methods on Session are: enableFilter(String filterName), getEnabledFilter(String filterName), anddisableFilter(String filterName). Filters must be enabled through use of the Session.enableFilter() method, which returns an instance of the Filter interface. If you used the simple filter defined above, it would look like this: session.enableFilter("myFilter").setParameter("myFilterParam", "some-value"); Methods on the org.hibernate.Filter interface do allow the method-chaining common to much of Hibernate.      

Filter is an Interface available in org.hibernate package. Hibernate filters are defined in Hibernate mapping documents (hbm.xml file)-which are easy to maintain. One can programmatically turn on or off the filters in the application code. Filters can't be created at run time. By default, filters are not enabled for a given session. Sometimes it is required to only process a subset of the data in the underlying Database tables. Hibernate filters are very useful in those situations.

We can attach a single filter to more than one class or collection. To do this, you add a XML element to each class or collection. The XML element has two attributes viz. name and condition. The name references a filter definition (in the sample application it's : statusFilter) while condition is analogous to a WHERE clause in HQL. Note: Each XML element must correspond to a element. It is possible to have more than one filter for each filter definition, and each class can have more than one filter. Idea is to define all the filter parameters in one place and then refer them in the individual filter conditions. In the java code, we can programmatically enable or disable the filter. By default the Hibernate Session doesn't have any filters enabled on it. The Session interface contains the following methods: 

public Filter enableFilter(String filterName)



public Filter getEnabledFilter(String filterName)



public void disableFilter(String filterName) The Filter interface contains some of the important methods:



public Filter setParameter(String name, Object value)



public Filter setParameterList(String name, Collection values)



public Filter setParameterList(String name, Object[] values) setParameter() method is mostly used. Be careful and specify only the type of java object that you have mentioned in the parameter at the time of defining filter in the mapping file.

37

The two setParameterList() methods are useful for using IN clauses in your filters. If you want to use BETWEEN clauses, use two different filter parameters with different names.

38

----------------------------------------------------------------------------

Interview Questions-Answers

---------------------------------------------------------------------------1.What is ORM ? ORM stands for object relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database. 2.What does ORM consists of ? An ORM solution consists of the following four pieces:  API for performing basic CURD operations  API to express queries referring to classes  Facilities to specify metadata  Optimization facilities : dirty checking, lazy associations fetching 3.What are the ORM levels ? The ORM levels are:  Pure relational (stored procedure.)  Light objects mapping (JDBC)  Medium object mapping  Full object Mapping (composition, inheritance, polymorphism, persistence by reachability) 5.Why do you need ORM tools like hibernate? The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:  Improved productivity o High-level object-oriented API o Less Java code to write o No SQL to write  Improved performance o Sophisticated caching o Lazy loading o Eager loading  Improved maintainability o A lot less code to write  Improved portability o ORM framework generates database-specific SQL for you 6.What Does Hibernate Simplify? Hibernate simplifies:  Saving and retrieving your domain objects  Making database column and table name changes  Centralizing pre save and post retrieve logic  Complex joins for retrieving related items  Schema creation from object model 7.What is the need for Hibernate xml mapping file? Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:

39

8.What are the most common methods of Hibernate configuration? The most common methods of Hibernate configuration are:  Programmatic configuration  XML configuration (hibernate.cfg.xml) 9.What are the important tags of hibernate.cfg.xml? Following are the important tags of hibernate.cfg.xml:

10.What are the Core interfaces are of Hibernate framework? The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.  Session interface  SessionFactory interface  Configuration interface

40

 

Transaction interface Query and Criteria interfaces

11.What role does the Session interface play in Hibernate? The Session interface is the primary interface used by Hibernate applications. It is a singlethreaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects. Session session = sessionFactory.openSession(); Session interface role:  Wraps a JDBC connection  Factory for Transaction  Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier 12.What role does the SessionFactory interface play in Hibernate? The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole applicationå¹¼reated during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work SessionFactory sessionFactory = configuration.buildSessionFactory(); 13.What is the general flow of Hibernate communication with RDBMS? The general flow of Hibernate communication with RDBMS is :  Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files  Create session factory from configuration object  Get one session from this session factory  Create HQL Query  Execute query to get list containing Java objects 14.What is Hibernate Query Language (HQL)? Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL. 15.How do you map Java Objects with Database tables?  First we need to write Java domain objects (beans with setter and getter).  Write hbm.xml, where we map java class to table and database columns to Java class variables. Example : 16.What’s the difference between load() and get()? load()

get()

Only use the load() method if you are sure that the object exists.

If you are not sure that the object exists, then use one of the get() methods.

load() method will throw an exception if the unique

get() method will return null if the unique

41

id is not found in the database.

id is not found in the database.

load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.

get() will hit the database immediately.

17.What is the difference between and merge and update ? Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session. 18.How do you define sequence generated primary key in hibernate? Using tag. Example: SEQUENCE_NAME 19.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are? 20.What do you mean by Named – SQL query? Named SQL queries are defined in the mapping xml document and called wherever required. Example: SELECT emp.EMP_ID AS {emp.empid}, emp.EMP_ADDRESS AS {emp.address}, emp.EMP_NAME AS {emp.name} FROM Employee EMP WHERE emp.NAME LIKE :name

Invoke Named Query : List people = session.getNamedQuery("empdetails") .setString("TomBrady", name) .setMaxResults(50) .list(); 21.How do you invoke Stored Procedures? { ? = call selectAllEmployees() } 22.Explain Criteria API

42

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. Example : List employees = session.createCriteria(Employee.class) .add(Restrictions.like("name", "a%") ) .add(Restrictions.like("address", "Boston")) .addOrder(Order.asc("name") ) .list(); 23.Define HibernateTemplate? org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions. 24.What are the benefits does HibernateTemplate provide? The benefits of HibernateTemplate are :  HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.  Common functions are simplified to single method calls.  Sessions are automatically closed.  Exceptions are automatically caught and converted to runtime exceptions. 25.How do you switch between relational databases without code changes? Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined. 26.If you want to see the Hibernate generated SQL statements on console, what should we do? In Hibernate configuration file set as follows: true 27.What are derived properties? The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element. 28.What is component mapping in Hibernate?  A component is an object saved as a value, not as a reference  A component can be saved directly without needing to declare interfaces or identifier properties  Required to define an empty constructor  Shared references not supported Example:

43

29.What is the difference between sorted and ordered collection in hibernate? sorted collection

order collection

A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator.

Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.

If your collection is not large, it will be more efficient way to sort it.

If your collection is very large, it will be more efficient way to sort it .

31.What is the advantage of Hibernate over jdbc? JDBC

Hibernate

With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.

Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.

With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.

Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.

Hibernate provides a powerful query language Hibernate Query Language (independent from JDBC supports only native Structured Query type of database) that is expressed in a Language (SQL). Developer has to find out the familiar SQL like syntax and includes full efficient way to access database, i.e. to select support for polymorphic queries. Hibernate effective query from a number of queries to also supports native SQL statements. It also perform same task. selects an effective way to perform a database manipulation task for an application. Application using JDBC to handle persistent data (database tables) having database

Hibernate provides this mapping itself. The actual mapping between tables and application

44

specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table objects is done in XML files. If there is change fields to object properties. As table changed or in Database or in any table then the only need database changed then it’s essential to change to change XML file properties. object structure as well as to change code written to map table-to-object/object-totable. With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.

Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

With JDBC, caching is maintained by handcoding.

Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.

In JDBC there is no check that always every user has updated data. This check has to be added by the developer.

Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.

33.What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins: An implicit association join  An ordinary join in the FROM clause  A fetch join in the FROM clause.  A theta-style join in the WHERE clause. 34.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are? 35.What is Hibernate proxy? The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

45

36.How can Hibernate be configured to access an instance variable directly and not through a setter method ? By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object. 37.How can a whole class be mapped as immutable? Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application. 38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping? Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.  dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed  dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null. 39.What do you mean by fetching strategy ? A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query. 40.What is automatic dirty checking? Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction. 41.What is transactional write-behind? Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind. 42.What are Callback interfaces? Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality. 44.What are the differences between EJB 3.0 & Hibernate Hibernate Vs EJB 3.0 :Hibernate

EJB 3.0

Session–Cache or collection of loaded objects relating to a single unit of work

Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit

XDoclet Annotations used to support Attribute Oriented Programming

Java 5.0 Annotations used to support Attribute Oriented Programming

Defines HQL for expressing queries to the database

Defines EJB QL for expressing queries

Supports Entity Relationships through mapping files and annotations in JavaDoc

Support Entity Relationships through Java 5.0 annotations

Provides a Persistence Manager API exposed via the Session, Query, Criteria,

Provides and Entity Manager Interface for managing CRUD operations for

46

and Transaction API

an Entity

Provides callback support through lifecycle, interceptor, and validatable interfaces

Provides callback support through Entity Listener and Callback methods

Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships

Entity Relationships are bidirectional or unidirectional

1. What is Hibernate? Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users to develop persistent classes following object-oriented principles such as association, inheritance, polymorphism, composition, and collections 2.What is ORM ? ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another. 3.What are the different levels of ORM quality? There are four levels defined for ORM quality. Ø Pure relational Ø Light object mapping Ø Medium object mapping Ø Full object mapping 4. How will you configure Hibernate? The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service. " hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file. " Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files. 5. What are derived properties? The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element. 8 . What is the difference between sorted and ordered collection in hibernate? sorted collection vs. order collection :sorted collection

order collection

A sorted collection is sorting a collection by Order collection is sorting a collection by utilizing the sorting features provided by the specifying the order-by clause for sorting this Java collections framework. The sorting occurs in collection when retrieval. the memory of JVM which running Hibernate, after the data being read from database using

47

java comparator. If your collection is not large, it will be more efficient way to sort it.

If your collection is very large, it will be more efficient way to sort it .

10. What is Hibernate proxy? The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked Q. How will you configure Hibernate? Answer: The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service. " hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file. " Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files. Q. What is a SessionFactory? Is it a thread-safe object? SessionFactory is Hibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code. SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory(); Q. What is a Session? Can you share a session object between different theads? Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method. & public class HibernateUtil { & public static final ThreadLocal local = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session session = (Session) local.get(); //open a new session if this thread has no session if(session == null) { session = sessionFactory.openSession(); local.set(session); } return session; } }

48

It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy. Q. What are the benefits of detached objects? Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session. Q. What are the pros and cons of detached objects? Pros: " When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session. Cons " In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway. " Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers. Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects? " Hibernate uses the version property, if there is one. " If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. " Write your own strategy with Interceptor.isUnsaved(). Q. What is the difference between the session.get() method and the session.load() method? Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null. Q. What is the difference between the session.update() method and the session.lock() method? Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction. Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well. Q. How would you reatach detached objects to a session when the same object has already been loaded into the session? You can use the session.merge() method call. Q. What are the general considerations or best practices for defining your Hibernate persistent classes? 1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables.

49

2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object. 3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster. 4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects. 5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files. Q) What are the most common methods of Hibernate configuration? A) The most common methods of Hibernate configuration are: * Programmatic configuration * XML configuration (hibernate.cfg.xml) Q) What are the important tags of hibernate.cfg.xml? A) An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest. Q) What are the Core interfaces are of Hibernate framework? A) People who read this also read: The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions. * Session interface * SessionFactory interface * Configuration interface * Transaction interface * Query and Criteria interfaces Q) What role does the Session interface play in Hibernate? A) The Session interface is the primary interface used by Hibernate applications. It is a singlethreaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects. Session session = sessionFactory.openSession(); Session interface role: * Wraps a JDBC connection * Factory for Transaction * Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier Q) What role does the SessionFactory interface play in Hibernate? A) The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work SessionFactory sessionFactory = configuration.buildSessionFactory(); Q) What is the general flow of Hibernate communication with RDBMS? A) The general flow of Hibernate communication with RDBMS is : * Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files * Create session factory from configuration object * Get one session from this session factory * Create HQL Query * Execute query to get list containing Java objects

50

Q) What is Hibernate Query Language (HQL)? A) Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL. Q) How do you map Java Objects with Database tables? A) * First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns. * Write hbm.xml, where we map java class to table and database columns to Java class variables. Example :

Q) What Does Hibernate Simplify? A) Hibernate simplifies: * Saving and retrieving your domain objects * Making database column and table name changes * Centralizing pre save and post retrieve logic * Complex joins for retrieving related items * Schema creation from object model Q) Define cascade and inverse option in one-many mapping? A) cascade – enable operations to cascade to child entities. cascade=”all|none|save-update|delete|all-delete-orphan” inverse – mark this collection as the “inverse” end of a bidirectional association. inverse=”true|false” Essentially “inverse” indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are? Q) What does it mean to be inverse? A) It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). If the one–to–many was marked as non–inverse then a child–>parent relationship would be created. Q) What do you mean by Named – SQL query? A) Named SQL queries are defined in the mapping xml document and called wherever required. Example: SELECT emp.EMP_ID AS {emp.empid}, emp.EMP_ADDRESS AS {emp.address}, emp.EMP_NAME AS {emp.name} FROM Employee EMP WHERE emp.NAME LIKE :name Invoke Named Query : List people = session.getNamedQuery(“empdetails”) .setString(“TomBrady”, name) .setMaxResults(50) .list(); Q) How do you invoke Stored Procedures? A)

51

{ ? = call selectAllEmployees() } Q) Explain Criteria API A) Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like “search” screens where there is a variable number of conditions to be placed upon the result set. Example : List employees = session.createCriteria(Employee.class) .add(Restrictions.like(“name”, “a%”) ) .add(Restrictions.like(“address”, “Boston”)) .addOrder(Order.asc(“name”) ) .list(); Q) What are the benefits does HibernateTemplate provide? A) The benefits of HibernateTemplate are : * HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session. * Common functions are simplified to single method calls. * Sessions are automatically closed. * Exceptions are automatically caught and converted to runtime exceptions. Q) How do you switch between relational databases without code changes? A) Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined. Q) If you want to see the Hibernate generated SQL statements on console, what should we do? A) In Hibernate configuration file set as follows: true Q) What are derived properties? A) The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element. People who read this also read: Core Java Questions Spring Questions SCJP 6.0 Certification EJB Interview Questions Servlets Questions Q) What is component mapping in Hibernate? A) * A component is an object saved as a value, not as a reference * A component can be saved directly without needing to declare interfaces or identifier properties * Required to define an empty constructor * Shared references not supported Q) What is the difference between sorted and ordered collection in hibernate? A) sorted collection vs. order collection sorted collection :A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. If your collection is not large, it will be more efficient way to sort it.

52

order collection :Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval. If your collection is very large, it will be more efficient way to sort it . Explain about HibernateTemplate? Ans: The org.springframework.orm.hibernate.HibernateTemplate class simplifies Hibernate data access code, and converts checked HibernateExceptions into unchecked DataAccessExceptions, following the org.springframework.dao exception hierarchy. Uses the same SQLExceptionTranslator mechanism as JdbcTemplate. The central method is execute(), supporting Hibernate access code implementing the HibernateCallback interface. It provides Hibernate Session handling such that neither the HibernateCallback implementation nor the calling code needs to explicitly care about retrieving/closing Hibernate Sessions, or handling Session lifecycle exceptions. What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath? Ans: The settings of the XML configuration file will override the settings used in the properties. What is the use of dynamic-insert and dynamic-update attributes in a class mapping? Ans: You may declare a persistent class using the class element. The dynamic-insert and dynamicupdate attributes are optional attributes. The dynamic-update (defaults value is false), specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed. The dynamic-insert (defaults value is false), specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null. What is Connection pools used for in Hibernate? Ans: Connection pools are a common way to improve application performance. Rather than opening a separate connection to the database for each request, the connection pool maintains a collection of open database connections that are reused. Application servers often provide their own connection pools using a JNDI DataSource, which Hibernate can take advantage of when configured to use a DataSource. When you choose a connection pooling service, you must configure it for your environment. Hibernate supports configuring connection pools from the hibernate.cfg.xml file. The connection.provider_class property sets the pooling implementation: org.hibernate.connection.C3P0ConnectionProvider How will you configure the SessionFactory? Ans: The Configuration class kicks off the runtime portion of Hibernate. It's used to load the mapping files and create a SessionFactory for those mapping files. There are three ways to create and initialize a Configuration object. This first snippet loads the properties and mapping files defined in the hibernate.cfg.xml file and creates the SessionFactory: Configuration cfg =new Configuration(); SessionFactory factory =cfg.configure().buildSessionFactory(); The configure()method tells Hibernate to load the hibernate.cfg.xml file. The Configuration class can also load mapping documents programmatically: Configuration cfg =new Configuration(); cfg.addFile("com/manning/hq/ch03/Event.hbm.xml"); Another alternative is to have Hibernate load the mapping document based on the persistent class. What are the Joined Subclasses in Hibernate? Ans: Joined subclasses are those that are mapped to a table-per-subclass design rather than a table-per-hierarchy.

53

In Hibernate, this could be mapped as follows: ... * JNDI-bound SessionFactory * Logging * Java Management Extensions (JMX) What’s the difference between load() and get()? Ans: Both load() and get() methods used to find out the object in cache or database. Use get() method if you are not sure that the object exists. The get() method will return null if the unique id is not found in the database. The get() will hit the database immediately. Use the load() method if you are sure that the object exists. The load() method will throw an exception if the unique id is not found in the database. The load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. Explain about mapping description file? Ans: Hibernate can be configured with two types of files out of which hibernate.cfg.xml is the mapping description file in which Hibernate uses to configure its functions. This mapping file has an extension *.hbm which instructs mapping between Java class and database tables. The usage of mapping description file rests entirely upon the business entity.

62

Explain about the dirty checking feature of Hibernate? Ans: Dirty checking feature of the Hibernate allows users or developers to avoid time consuming database write actions. This feature makes necessary updations and changes to the fields which require a change, remaining fields are left unchanged or untouched. What is the best application framework for use with Hibernate? Ans: JBoss Seam may be the best application framework for use with Hibernate. The Hibernate team designed and created JBoss Seam as an application framework for use with ORM technology which solves several ORM-specific problems (to do with persistence context management) that are not solved by traditional pure request-oriented application frameworks. Difference between session.update() and session.lock() in Hibernate ? Ans: Both the session.update() and session.lock() are intended for re-attaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update() or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction. How can multiple threads access session factory simulteneously to create session instance? Ans: We know that the session factory is thread-safe, so it is okay to use SessionFactory object by many threads to have session from session factory, but I think session is not thread safe and it should be used by one thread at a time, and after use, session has to be flushed and closed. What are the different types of statistics available in Hibernate 3.2? Ans: Different types of statistics available in Hibernate: * QueryStatistics, * CategorizedStatistics, * CollectionStatistics, * EntityStatistics, etc. What are the different Fetching Strategies available with Hibernate? Ans: There are four different Fetching standards available in Hibernate3.2: * join fetching, * select fetching, * batch fetching, * sub-select fetching. What are the different Transaction Factories available with Hibernate? Ans: There are three different types of Transaction Factoryavailable with Hibenate 3.2 are : * JDBCTransactionFactory, * JTATransactionFactory, and * CMTTransactionFactory. Does Hibernate fully support polymorphism? Ans: Hibernate supports polymorphic queries and associations in all three inheritance mapping strategies (and even allows mixing of the two most important strategies). Aren't stored procedures always faster than dynamic SQL? Ans: No! Hibernate always executes SQL statements using a JDBC PreparedStatement, which allows the

63

database to cache the query plan. There is no reason to avoid the use of generated SQL in modern applications. How can we get access to O/R mapping information such as table and column names at runtime? Ans: This information is available via the Configuration object. For example, entity mappings may be obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory. Does Hibernate implement its functionality using a minimal number of database queries? Ans: Hibernate can make certain optimizations implement its functionality using a minimal number of database queries: * Caching objects * Executing SQL statement when needed. * Never updating unmodified objects. * Efficient Collection Handling. * Updating only the modified columns. * Outer join fetching. * Lazy collection initialization. * Lazy object initialization. Ques: 77 How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects? Ans: The EmptyInterceptor class provides the isTransient() method to check whether the object is transient or deteched. Method signature: java.lang.Boolean isTransient(java.lang.Object obj) What are the benefits of detached objects? Ans: Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs(Data Transfer Objects). You can later on re-attach the detached objects to another session. Explain the various object states in Hibernate? Ans: Hibernate defines and supports the following object states: * Transient :- an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. * Persistent :- a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. * Detached :- a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it persistent again. What are the types of inheritence models in Hibernate? Ans: There are three types of inheritance mapping in hibernate: 1. Table per concrete class with unions. 2. Table per class hierarchy. 3. Table per subclass. What is the general flow of Hibernate communication with RDBMS? Ans: The general flow of Hibernate communication with RDBMS is: * Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files. * Create session factory from configuration object.

64

* Get one session from this session factory * Create HQL Query. * Execute query to get list containing Java objects. What are derived properties? Ans: The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using formula attribute of the element. What are different levels of ORM quality? Ans: There are four levels defined for ORM quality: * Pure relational: The entire application, including the UI is designed around the relational model and SQL based relational operation. * Light Object Mapping: The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. * Medium Object Mapping: The application is designed around an object model. The SQL code is generated at build time, and the association between objects is supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. * Full Object Mapping: Full Object Mapping supports sophisticated object modeling, composition, inheritance, polymorphism and persistence. Ans: There are four levels defined for ORM quality: * Pure relational: The entire application, including the UI is designed around the relational model and SQL based relational operation. * Light Object Mapping: The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. * Medium Object Mapping: The application is designed around an object model. The SQL code is generated at build time, and the association between objects is supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. * Full Object Mapping: Full Object Mapping supports sophisticated object modeling, composition, inheritance, polymorphism and persistence. What role does the Session interface play in Hibernate? Ans: The Session is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not threadsafe. The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create ry objects to retrieve persistent objects. Session session = sessionFactory.openSession(); Session interface play roles in: * Wraps a JDBC connection * Factory for Transaction * Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier. What is Hibernate proxy? Ans: Proxies are the mechanism that allows Hibernate to break up the interconnected cloud of objects in the database into smaller chunks, that can easily fit in memory. Proxies are created dynamically by subclassing your object at runtime. The subclass has all the methods of the parent, and when any of the methods are accessed, the proxy loads up the real object from the DB and calls the method for you. A class can be mapped to a proxy instead to a table. When you actually call load on session it returns you proxy. This proxy may contain actual method to load the data.

65

Object proxies can be defined in one of two ways. First, you can add a proxy attribute to the class element. You can either specify a different class or use the persistent class as the proxy. For example: The second method is to use the lazy attribute. Setting lazy="true"is a shorthand way of defining the persistent class as the proxy. Let's assume the Location class is defined as lazy: ... what is lazy initialisation in hibernate? Ans: Hibernate supports the feature of lazy initilasation for both entities and collections. What this actually means is, the Hibernate engine loads only those objects that we are querying for and doesnt try to fetch other entities(that are associated with the entity we are querying) or collections. Hibernate loads collection elements only when actually you ask for them by saying lazy=true or lazy=false. Example: How to call stored procedure in mysql through hibernate? Ans: If your stored procedure is returning a value you can directly use , otherwise you need to use jdbc connection to call the native sql procedure. Example: Session session = getHibernateTemplate().getSessionFactory().openSession(); /*if you are not using session factory, you can use ur own method to get session.*/ Connection conn = session.connection(); String sqlQuery = "call VersionUpdateProcedure()"; CallableStatement cs = conn.prepareCall(sqlQuery); cs.execute(); conn.close(); session.close(); What are the most common methods of Hibernate configuration? Ans: The two most common methods of Hibernate configuration are: * Programmatic configuration * XML configuration (hibernate.cfg.xml) What Does Hibernate Simplify? Ans: Hibernate simplifies : * Saving and retrieving your domain objects * Making database column and table name changes * Centralizing pre save and post retrieve logic * Complex joins for retrieving related items * Schema creation from object model What is ORM? What does ORM consists of? Ans: ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database. An ORM solution consists of the followig four pieces: * API for performing basic CRUD operations * API to express ries refering to classes

66

* Facilities to specify metadata * Optimization facilities : dirty cecking, lazy associations fetching. What is Persistence? Ans: Persistence is one of the fundamental concepts in application development. In an object-oriented application, persistence allows an object to outlive the process that created it. The state of the object may be stored to disk and an object with the same state re-created at some point in the future. Persistence is the ability of data to outlive an instance of a program, central to modern applications. Hibernate, the most popular Java persistence tool, provides automatic and transparent object/relational mapping so it's a snap to work with SQL databases in Java applications. What is Hibernate? Ans: Hibernate is popular open source object relational mapping tool for Java platform. It provides powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework. 1) Explain about Hibernate? Hibernate solves problems such as Object Relational impedance mismatch, etc. It is commonly used for object and query service. It helps data base developers develop classes which include inheritance, association, composition and polymorphism. A developer or user can express queries either in HQL or SQL. 2) Explain about the primary feature of Hibernate? Primary feature of hibernate is to java classes to database tables. Data query and retrieval is also possible with Hibernate. Application portability is a key feature in Hibernate it allows developers to port applications to almost all SQL databases. 3) Explain about transparent persistence of Hibernate? Transparent persistence is provided for Plain old Java objects or POJOs. For proper functioning of the applications importance should be given to the methods equals () and hash Code methods (). It has a requirement which should be strictly followed in the applications which is a no-argument constructor. 4) Explain about the dirty checking feature of Hibernate? Dirty checking feature of the Hibernate allows users or developers to avoid time consuming data base write actions. This feature makes necessary updations and changes to the fields which require a change, remaining fields are left unchanged or untouched. 5) Brief about the Session factory interface? It creates new hibernate sessions by referencing immutable and thread safe objects. Application using hibernate are usually allowed and desgined to implement single instance of the class using this interface. Only single instance of a class can be used which is using this interface. 6) Explain about session interface? This represents hibernate session which perform the manipulation on the database entities. Some of the activities performed by session interface are as follows they are managing the persistence state, fetching persisted ones and management of the transaction demarcation. 7) Explain the steps involved in creating database applications with Java using Hibernate? Creating Database applications with Java is made simpler with Hibernate. First Plain old java object needs to be written, XML mapping file should be created which shows relationship between database and class attributes. Hibernate APIs can be used to store persistent objects. 8) Explain about hibernate.cfg.xml? Hibernate can be configured with two types of files out of which hibernate.cfg.xmlis widely used and popular feature. Hibernate consults hibernate.cfg.xml file for its operating properties such as database dialect, connection string and mapping files. These files are searched on class path.

67

9) Explain about mapping description file? Mapping description file is the second file which Hibernate uses to configure its functions. This mapping file has an extension *.hbm which instructs mapping between Java class and database tables. The usage of mapping description file rests entirely upon the business entity. 10) Explain about transaction file? Transactions denote a work file which can save changes made or revert back the changes. A transaction can be started by session.beginTransaction() and it uses JDBC connection, CORBA or JTA. When this session starts several transactions may occur. 31) What does it mean to be inverse? A) It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). 34) Explain Criteria API? A) Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like “search” screens where there is a variable number of conditions to be placed upon the result set. Example : List employees = session.createCriteria(Employee.class) .add(Restrictions.like(“name”, “a%”) ) .add(Restrictions.like(“address”, “Boston”)) .addOrder(Order.asc(“name”) ) .list(); 36) What are the benefits does HibernateTemplate provide? A) The benefits of HibernateTemplate are : * HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session. * Common functions are simplified to single method calls. * Sessions are automatically closed. * Exceptions are automatically caught and converted to runtime exceptions. 37) How do you switch between relational databases without code changes? A) Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined. 39) What are derived properties? A) The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element. 40) What is component mapping in Hibernate? A) * A component is an object saved as a value, not as a reference * A component can be saved directly without needing to declare interfaces or identifier properties * Required to define an empty constructor * Shared references not supported Q4. What are the two config files used for Hibernate? The following two files a)hibernate.cfg.xml b)hibernate.properties are used to configure the hibernate service.

68

Q5. Enumerate some common methods of Hibernate configuration? The common methods of Hibernate configuration are: a)Programmatic configuration b)XML configuration Q7. What is the use of Mapping files (*.hbm.xml) in Hibernate? The mapping files Mapping files (*.hbm.xml) are used to map persistent objects to a relational database. Each persistent class should be stored in different mapping files. Q8. What is an Hibernate session? An Hibernate Session is a non-threadsafe object which represents a single unit of work with the application database. Q9. What is the Transparent Persistence in Hibernate? The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence. Hibernate provides transparent persistence. Q10. How can we create java application which interacts with database using Hibernate? Hibernate simplifies the creation database enabled application using Hibernate.First write the simple java object.The create the XML mapping file that shows relationship between database and class attributes. The Hibernate APIs can be used to store persistent objects. How can I count the number of query results without actually returning them? Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult(); How can I find the size of a collection without initializing it? Integer size = (Integer) s.createFilter( collection, "select count(*)" ).uniqueResult(); How can I order by the size of a collection? Use a left join, together with group by select user from User user left join user.messages msg group by user order by count(msg) How can I place a condition upon a collection size? If your database supports subselects: from User user where size(user.messages) >= 1 or: from User user where exists elements(user.messages) If not, and in the case of a one-to-many or many-to-many association: select user from User user join user.messages msg group by user having count(msg) >= 1 Because of the inner join, this form can't be used to return a User with zero messages, so the following form is also useful select user from User as user left join user.messages as msg group by user having count(msg) = 0 How can I query for entities with empty collections? from Box box where box.balls is empty Or, try this: select box from Box box left join box.balls ball where ball is null

69

How can I sort / order collection elements? There are three different approaches: 1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or or . This solution does a sort in memory. 2. Specify an order-by attribute of , or , naming a list of table columns to sort by. This solution works only in JDK 1.4+. 3. Use a filter session.createFilter( collection, "order by ...." ).list() Are collections pageable? Query q = s.createFilter( collection, "" ); // the trivial filter q.setMaxResults(PAGE_SIZE); q.setFirstResult(PAGE_SIZE * pageNumber); List page = q.list(); I have a one-to-one association between two classes. Ensuring that associated objects have matching identifiers is bugprone. Is there a better way? parent

I have a many-to-many association between two tables, but the association table has some extra columns (apart from the foreign keys). What kind of mapping should I use? Use a composite-element to model the association table. For example, given the following association table: create table relationship ( fk_of_foo bigint not null, fk_of_bar bigint not null, multiplicity smallint, created date ) you could use this collection mapping (inside the mapping for class Foo): You may also use an with a surrogate key column for the collection table. This would allow you to have nullable columns. An alternative approach is to simply map the association table as a normal entity class with two bidirectional one-to-many associations. In an MVC application, how can we ensure that all proxies and lazy collections will be initialized when the view tries to access them? One possible approach is to leave the session open (and transaction uncommitted) when forwarding to the view. The session/transaction would be closed/committed after the view is rendered in, for example, a servlet filter (another example would by to use the ModelLifetime.discard() callback in Maverick). One difficulty with this approach is making sure the session/transaction is closed/rolled back if an exception occurs rendering the view. Another approach is to simply force initialization of all needed objects using Hibernate.initialize(). This is often more straightforward than it sounds. How can I bind a dynamic list of values into an in query expression?

70

Query q = s.createQuery("from foo in class Foo where foo.id in (:id_list)"); q.setParameterList("id_list", fooIdList); List foos = q.list(); How can I bind properties of a JavaBean to named query parameters? Query q = s.createQuery("from foo in class Foo where foo.name=:name and foo.size=:size"); q.setProperties(fooBean); // fooBean has getName() and getSize() List foos = q.list(); Can I map an inner class? You may persist any static inner class. You should specify the class name using the standard form ie. eg.Foo$Bar How can I assign a default value to a property when the database column is null? Use a UserType. How can I trucate String data? Use a UserType. How can I trim spaces from String data persisted to a CHAR column? Use a UserType. How can I convert the type of a property to/from the database column type? Use a UserType. How can I get access to O/R mapping information such as table and column names at runtime? This information is available via the Configuration object. For example, entity mappings may be obtained usingConfiguration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory. How can I create an association to an entity without fetching that entity from the database (if I know the identifier)? If the entity is proxyable (lazy="true"), simply use load(). The following code does not result in any SELECTstatement: Item itemProxy = (Item) session.load(Item.class, itemId); Bid bid = new Bid(user, amount, itemProxy); session.save(bid); How can I retrieve the identifier of an associated object, without fetching the association? Just do it. The following code does not result in any SELECT statement, even if the item association is lazy. Long itemId = bid.getItem().getId(); This works if getItem() returns a proxy and if you mapped the identifier property with regular accessor methods. If you enabled direct field access for the id of an Item, the Item proxy will be initialized if you call getId(). This method is then treated like any other business method of the proxy, initialization is required if it is called. How can I manipulate mappings at runtime? You can access (and modify) the Hibernate metamodel via the Configuration object, using getClassMapping(),getCollectionMapping(), etc. Note that the SessionFactory is immutable and does not retain any reference to the Configuration instance, so you must re-build it if you wish to activate the modified mappings. How can I avoid n+1 SQL SELECT queries when running a Hibernate query? Follow the best practices guide! Ensure that all and mappings specify lazy="true" in Hibernate2 (this is the new default in Hibernate3). Use HQL LEFT JOIN FETCH to specify which associations you need to be retrieved in the initial SQL SELECT. A second way to avoid the n+1 selects problem is to use fetch="subselect" in Hibernate3. If you are still unsure, refer to the Hibernate documentation and Hibernate in Action.

71

I have a collection with second-level cache enabled, and Hibernate retrieves the collection elements one at a time with a SQL query per element! Enable second-level cache for the associated entity class. Don't cache collections of uncached entity types. How can I insert XML data into Oracle using the xmltype() function? Specify custom SQL INSERT (and UPDATE) statements using and in Hibernate3, or using a custom persister in Hibernate 2.1. You will also need to write a UserType to perform binding to/from the PreparedStatement. How can I execute arbitrary SQL using Hibernate? PreparedStatement ps = session.connection().prepareStatement(sqlString); Or, if you wish to retrieve managed entity objects, use session.createSQLQuery(). Or, in Hibernate3, override generated SQL using , , and in the mapping document. I want to call an SQL function from HQL, but the HQL parser does not recognize it! Subclass your Dialect, and call registerFunction() from the constructor. HQL: The Hibernate Query Language The Hibernate Query Language is executed using session.createQuery(). This tutorial includes from clause,Associations and joins, Aggregate functions,The order by clause,The group by clause,Subqueries. The from clause from Employee // Employee is class name mapped to EMPLOYEE TABLE or from Employee as e or from Employee e where e.empId = 3; List empList = session.createQuery("from Employee").list(); Associations and joins from Employee e where e.scopeModFlag = 1 and pc.isDeleted != 1 List empList = session.createQuery("from Employee e where e.scopeModFlag = 1 and pc.isDeleted != 1").list(); Aggregate functions select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat) from Cat cat ScrollableResults rs = session.createQuery("select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat) from Cat cat").scroll(); if(rs.next()){ System.out.println(rs.get(0)); System.out.println(rs.get(1)); System.out.println(rs.get(2)); System.out.println(rs.get(3)); } The order by clause from Employee e order by e.name desc List empList = session.createQuery("from Employee e order by e.name desc").list(); asc or desc indicate ascending or descending order respectively. The group by clause select e.dept, sum(e.salary), count(e) Employee e group by cat.dept Subqueries from Employee as e where e.name = some (

72

select name.nickName from Name as name ) Associations and joins from Employee e where e.scopeModFlag = 1 and pc.isDeleted != 1 List empList = session.createQuery("from Employee e where e.scopeModFlag = 1 and pc.isDeleted != 1").list(); Criteria Queries The interface org.hibernate.Criteria represents a query against a particular persistent class. The Session is a factory for Criteria instances. Criteria : Select * from Employee. Criteria criemp = session.createCriteria(Employee.class); List emplist = criemp.list(); Restrictions to narrow result set The class org.hibernate.criterion.Restrictions used to narrow result set. // SELECT * FROM EMPLOYEE WHERE AGE=24; ----SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class).add( Restrictions.eq("age", new Integer(24) ) ).list(); // Not Equal in hibernate criteria // SELECT * FROM EMPLOYEE WHERE AGE !=24; ----SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class).add( Restrictions.ne("age", new Integer(24) ) ).list(); Ordering the results // SELECT * FROM EMPLOYEE WHERE AGE=24 ORDER BY EMP_NAME DESC; ----SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class). add( Restrictions.eq("age", new Integer(24) ) ).addOrder( Order.desc("empname") ).list(); Associations // SELECT e.name FROM EMPLOYEE e , address a where e.address_id=a.address_id and a.country='US'; ----SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class).createAlias("address","add"). add( Restrictions.eq("add.country", "US" ) ).list(); Example queries The class org.hibernate.criterion.Example allows you to construct a query criterion from a given instance. // SELECT * FROM EMPLOYEE e WHERE e.dept='IT'; ----SQL COMMAND criteria query for above query is : Employee emp = new Employee(); cat.setDept('IT'); List emplist = session.createCriteria(Employee.class) .add( Example.create(emp) ) .list(); Criteria Queries : Equal (eq), Not Equal(ne), Less than (lt), Less than or equal(le), greater than (gt),greater than or equal(ge) and Ordering the results The interface

73

org.hibernate.Criteria represents a query against a particular persistent class. The Session is a factory for Criteria instances. In this section it show how to create TABLE and POJO Java class and Mapping with the Query. Create TABLE EMPLOYEE. Create TABLE EMPLOYEE( id number; name varchar; age number; ); Create Employee.java bean class. Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table (Emp.java to EMPLOYEE TABLE). We can configure the variables to map to the database column. public class Employee { private long id; private String name; private int age; public long getId() { return id; } private void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } private void setAge(int age) { this.age = age; } }

Employee.hbm.xml - This mapps EMPLOYEE TABLE and Emp.java // This generates the primary key Equal (eq) Equal (eq) : Is used to check equal in the query. // SELECT * FROM EMPLOYEE WHERE AGE=24; ----SQL COMMAND criteria query for above query is : List empList =

74

session.createCriteria(Employee.class).add( Restrictions.eq("age", new Integer(24) ) ).list(); NotEqual (ne) NotEqual (ne) : Is used to check not equal in the query. // SELECT * FROM EMPLOYEE WHERE AGE !=24; ----SQL COMMAND // Not Equal in hibernate criteria criteria query for above query is : List empList = session.createCriteria(Employee.class).add( Restrictions.ne("age", new Integer(24) ) ).list(); Less than (lt) Less than (lt) : Is used to check less than in the query. // SELECT * FROM EMPLOYEE WHERE AGE < 24; ----SQL COMMAND // Not Equal in hibernate criteria criteria query for above query is : List empList = session.createCriteria(Employee.class).add( Restrictions.lt("age", new Integer(24) ) ).list(); Less than or equal(le) Less than or equal(le) : Is used to check less than or equal in the query. // SELECT * FROM EMPLOYEE WHERE AGE 24; ----SQL COMMAND // Not Equal in hibernate criteria criteria query for above query is : List empList = session.createCriteria(Employee.class).add( Restrictions.gt("age", new Integer(24) ) ).list(); Greater than or equal (gt) Greater than or equal (gt) : Is used to check greater than or equal in the query. // SELECT * FROM EMPLOYEE WHERE AGE >= 24; ----SQL COMMAND // Not Equal in hibernate criteria criteria query for above query is : List empList = session.createCriteria(Employee.class).add( Restrictions.ge("age", new Integer(24) ) ).list(); Ordering the results // SELECT * FROM EMPLOYEE WHERE AGE=24 ORDER BY NAME DESC; ----SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class). add( Restrictions.eq("age", new Integer(24) ) ).addOrder( Order.desc("name") ).list(); Criteria Queries: And OR conditions The interface org.hibernate.Criteria represents a query against a particular persistent class. The Session is a factory for Criteria instances. In this section it show how to create TABLE and POJO Java class and Mapping with the Query. Create TABLE EMPLOYEE. Create TABLE EMPLOYEE( id number;

75

name varchar; age number; ); Create Employee.java bean class. Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table (Emp.java to EMPLOYEE TABLE). We can configure the variables to map to the database column. public class Employee { private long id; private String name; private int age; public long getId() { return id; } private void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } private void setAge(int age) { this.age = age; } }

Employee.hbm.xml - This mapps EMPLOYEE TABLE and Emp.java // This generates the primary key And Condtion This method returns the conjunctions of two expressions. Both conditions are 'true' then it excutes the query otherwise not. // SELECT * FROM EMPLOYEE WHERE AGE=24 AND AGE=28; ----SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class) .add( Restrictions.eq("age", new Integer(24) ) ) .add( Restrictions.eq("age", new Integer(28) ) ) .list(); OR Condtion

76

This method returns the disjuction of two expressions. Any given condition is 'true' then it executes the query. In this tutorial, "or" is used // SELECT * FROM EMPLOYEE WHERE AGE=24 OR AGE=28; ----SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class) .add(Expression.or( Expression.eq("age", new Integer(24) ) ), Expression.eq("age", new Integer(28) ) )) .list(); Prevent concurrent update in Hibernate This tutorial resolve the issue of User think time : ( one user edit the record for update and thinking and changing values , same time other user edit the same record and update. then first user update and 2nd user's data is lost.) You can say this is version checking in Hibernate or perevent slate object updatation in Hibernate. version checking used in hibernate when more then one thread trying to access same data. For example : User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking time) and in the same time User B edit the same record for update and click the update. Then User A click the Update and update done. Chnage made by user B is lost. In hibernate you can perevent slate object updatation using version checking. Check the version of the row when you are upding the row. Get the version of the row when you are fetching the row of the TABLE for update. On the time of updation just fetch the version number and match with your version number ( on the time of fetching). Below steps to prevent concurrent update in Hibernate. Step 1. Declare a variable "versionId" in your bean Class with setter and getter method. public class Writer { private int id; private String name; private long versionId; public void setId(int i) { id = i; } public int getId() { return id; } public void setName(String n) { name = n; } public String getName() { return name; } public long getVersionId() { return versionId; } public void setVersionId(long versionId) { this.versionId = versionId; } } Step 2. Add Extra coulmn name "version" in the WRITER TABLE. create table WRITER ( ID number, //PRIMARY KEY NAME varchar, version number );

77

Step 3. Add property in writer.hbm.xml and optimistic-lock="version" - Which maps to WRITER TABLE. Step 4. add writer.hbm.xml into hibernate.cfg.xml com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/techfaqdb techfaq techfaq 1 4 1800 50 org.hibernate.dialect.MySQLDialect thread org.hibernate.cache.NoCacheProvider true update Step 5. In the Code When you are updating the table just check the version with you and the current version in the table. You can handle StaleObjectStateException() and do what ever you want. You can display error message. Hibernate autumatically create/update the version number when you update/insert any row in the table. In the code session = sf.openSession(); long oldVersion = writer.getVersionId(); // User Think time ::::::::::::::: May be 1 minute then get the current version using load() method below.

78

session.load( writer, writer.getId() ); // current version in the table if ( oldVersion!=writer.getVersionId() ) throw new StaleObjectStateException(); //check the version with you and the current version in the table writer.setName("Das"); session.flush(); session.connection().commit(); session.close(); Advantage of Hibernate over JDBC Advantage are 1) Hibernate is data base independent, same code will work for all data bases like ORACLE,MySQL ,SQLServer etc. In case of JDBC query must be data base specific. 2) As Hibernate is set of Objects , you don't need to learn SQL language. You can treat TABLE as a Object . In case of JDBC you need to learn SQL. 3) Don't need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance. In case of JDBC you need to tune your queries. 4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance. In case of JDBC you need to implement your java cache . 5) Hibernate supports Query cache and It will provide the statistics about your query and database status. JDBC Not provides any statistics. 6) Development fast in case of Hibernate because you don't need to write queries. 7) No need to create any connection pool in case of Hibernate. You can use c3p0. In case of JDBC you need to write your own connection pool. 8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability. 9) You can load your objects on start up using lazy=false in case of Hibernate. JDBC Don't have such support. 10 ) Hibernate Supports automatic versioning of rows but JDBC Not. Hibernate Data Type-Java Data Type - SQL Data Type mapping Java Type

Hibernate Type

SQL Type

Integer, int, long short

integer, long, short

number

char

character

java.math.BigDecimal

big_decimal

float, double

float, double

boolean

java.lang.string

java.util.Date

NUMERIC, NUMBER

float, double

java.lang.Boolean, boolean

Very long strings

char

boolean, int

string

varchar, varchar2

text

CLOB, TEXT

date, time, timestamp

79

DATE, TIME, TIMESTAMP

java.util.Calendar java.util.Locale java.util.TimeZone java.util Currency

calendar, calendar_date locale

TIMESTAMP, DATE varchar,varchar2

timezone

varchar, varchar2

Currency

varchar, varchar2

java.sql.Clob

clob

java.sql.Blob

blob

BLOB

Java object

serializable

binary field

byte array

binary

binary field

java.lang.Class

CLOB

class

varchar, varchar2

1. What is Hibernate? Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks. 2. What is ORM? ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another. 3. What does an ORM solution comprises of? It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes Should have a language or an API for specifying queries that refer to the classes and the properties of classes An ability for specifying mapping metadata It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions 4. What are the different levels of ORM quality? There are four levels defined for ORM quality. Pure relational object mapping Medium object mapping Full object mapping 5. What is a pure relational ORM? The entire application, including the user interface, is designed around the relational model and SQL-based relational operations. 6. Why do you need ORM tools like hibernate? The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits: 1. Improved productivity · High-level object-oriented API · Less Java code to write · No SQL to write 2. Improved performance · Sophisticated caching · Eager loading

80

3. Improved maintainability · A lot less code to write 4. Improved portability · ORM framework generates database-specific SQL for you 7. What is a meant by light object mapping? The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all. 8. What is a meant by medium object mapping? The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time. 9. What is meant by full object mapping? Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application. 10. What are the benefits of ORM and Hibernate? There are many benefits from these. Out of which the following are the most important one. Productivity : Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic. Maintainability :As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC. Performance : Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance. Vendor independence : Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application. 11. What the Core interfaces are of hibernate framework? There are many benefits from these. Out of which the following are the most important one. Session Interface : This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe. SessionFactory Interface : This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads. Configuration Interface : This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents. Transaction Interface : This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction. Query and Criteria Interface : This interface allows the user to perform queries and also control the flow of the query execution. 12. What are Callback interfaces? These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.

81

13. What should SessionFactory be placed so that it can be easily accessed? As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file. 14. What are POJOs? POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather then simple java classes. 15. What is object/relational mapping metadata? ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations. 16. What is HQL? HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL. 17. What are the most common methods of Hibernate configuration? The most common methods of Hibernate configuration are: · Programmatic configuration · XML configuration (hibernate.cfg.xml) 18. What are the important tags of hibernate.cfg.xml? An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest. 19. What are the Core interfaces are of Hibernate framework? People who read this also read: The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions. · Session interface · SessionFactory interface · Configuration interface · Transaction interface · Query and Criteria interfaces 20. What role does the Session interface play in Hibernate? The Session interface is the primary interface used by Hibernate applications. It is a singlethreaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects. Session session = sessionFactory.openSession(); Session interface role: · Wraps a JDBC connection · Factory for Transaction · Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier Ques: 21 What is dirty read in transaction isolation issues? Ans: When one transaction reads changes made by another transaction that hasn't yet been committed is called dirty read. This is very dangerous, because those changes might later be rolled back. Ques: 22 What are the various transaction isolation isssues in Hibernate?

82

Ans: The ANSI SQL standard defines the standart transaction isolation levels in terms of which of these phenomenon are permissible: * Last update * Dirty read * Unrepeatable read * Second lost updates problem * Phantom read Ques: 23 Explain Hibernate Transaction API? Ans: The Transaction interface provides methods for declaring the boundaries of a database transaction. Example: Session s = sessions.openSession(); Transaction t = null; try{ t = s.beginTransaction(); concludeAuction(); t.commit(); } catch(Exception e) { if(t!=null) { try{ t.rollback(); } catch (HibernateException h) { // log h and rethrow e } } throw e; }finally { try{ s.close(); } catch (HibernateException h) { throw h; } } Ques: 24 What auto commint mode should you use in JDBC connection in Hibernate? Ans: A magical setting that is often a source of confusion is the JDBC connection's auto commit mode. If a database connection is in auto commit mode, the database transaction will be committed immediately after each SQL statement, and a new transaction will be started. This can be useful for ad hoc database queries and ad hoc data updates. What is the difference between JDBC and JTA transactions in Hibernate? Ans: In a non-managed environment, the JDBC API is used to mark transaction boundaries. You begin a transaction by calling setAutoCommit(false) on a JDBC connection and end it by calling commit(). You may, at any time, force an intermediate rollback by calling rollback(). In a system that stores data in multiple databases, you can't achieve atomaticity using JDBC alone. You require a transaction manager with support for distributed transactions (two-phase commit). You communicate with the transaction manager using the JTA (Java Transaction API). In a managed environment, JTA is used only for distributed transaction, but also for declarative container managed transaction (CMT). Difference between getCurrentSession() and openSession() in Hibernate ? Ans: A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends. It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs. The getCurrentSession() method looks at the current context to see if a session is stored in there. If there is one, it uses it, and if there isn't a session in the current context, it creates a new one and saves it in there.

83

On the other hand, openSession does not try to store the session, or pull the session from the current context. How will you initialize lazy associations in Hibernate? Ans: A proxy or collection wrapper is automatically initialized when any of its methods are invoked. However it is only possible to initialize a proxy or collection wrapper if it's currently associated with an open session. If you close the session and try to access an uninitialized proxy or collection, Hibernate throws a runtime exception. Beacuase of this behaviour, it's sometimes useful to explicitly initialize an object before closing the session. We use the static method Hibernate.initialize() for manual initialization: Session session = session.openSession(); Transaction t = session.beginTransaction(); Category cat = (Category) session.get(Category.class, id); Hibernate.initialize(cat.getItems()); t.commit(); session.close(); What is Lazy fetching in Hibernate? Ans: When a client request an entity and its association graph of object from the datebase. It isn't usually necessary to retrieve the dwhole graph. Lazy fetching lets you decide how much of the object graph is loaded in the first database hit and which associations should be loaded only when they're first accessed. Lazy fetching is a foundational concept in object persistence and the first step to attaining accetable performance. What is outer join fetching in Hibernate? Ans: Eager or outer join fetching lets you explicitly specify which associated objects should be loaded together with the referencing object. Hibernate can then return the associated objects in a single database request, utilizing an SQL OUTER JOIN. Even though default eager fetching may be declared in the mapping file, it's more common to specify the use of this strategy at runtime for a particular HQL or criteria query.

What are the various fetching strategies from the database in Hibernate? Ans: Hibernate allows you to choose among four fetching strategies for any association, in association and at runtime: * Immediate fetching. * Lazy fetching. * Eager fatching. * Batch fetching. What is Hibernate Query By Example? Ans: The idea behind Query By Example is that the application supplies an instance of the queried class with certain property values set. The query returns all persistent instances with matching property values. QBE isn't a particularly powerful approach, but it can be convenient for some applications. The following code snippet demonstrates a Hibernate QBE: User exampleUser = new User(); exampleUser.setFirstName("Max"); Criteria c = session.createCriteria(User.class); c.add(Example.create(exampleUser)); List r=criteria.list();

84

What is Hibernate QBC (Query By Criteria)? Ans: The Hibernate Query By Criteria API lets you build a query by manipulating criteria objects at runtime. This approach lets you specify constraints dynamically without direct using mainpulations, but it doesn't lose much of the flexibility or power of HQL. Retrieving a user by first name is easy using a Criteria object: Criteria c = session.createCriteria(User.class); c.add(Expression.like("firstname","Max")); List result = c.list(); Explain HQL (Hibernate Query Language)? Ans: The HQL is an object oriented dialect of the familiar relational query language SQL. HQL is not a data manipulation language like SQL. It's used only for object retrieval, not for updating, inserting, or deleting data. HQL supports: * The ability to apply restrictions to properties of associated objects related by reference or held in collections. * The ability to retrieve only properties of an entity or entities. * The ability to order the results of the query. * The ability to paginate the results. * Aggregation with group by, having, and aggregate functions like sum, min, max. * Outer joins when retrieving multiple objects per row. * The ability to cal user-defined SQL functions. * Subqueries. Ques: 35 How will you retrieve an object by Identifier from the database in Hibernate? Ans: The following Hibernate code snippet retrieves a User defined Object form the database: User u = (User) session.get(User.class, userID); The get() method is special because the identifier uniquely identifies a single instance of a class. Hibernate also provides a load() method: User u = (User) session.load(User.class, userID); If laod() method can't find the object in the cache or database, an exception is thrown. The get() method returns null if the object can't be found. The load() method may return a proxy instead of a real persistent instance.

What are the various ways to fetch objects from database in Hibernate? Ans: Hibernate provides the following ways to get objects out of the database: * Navigating the object graph, starting from an already loaded object, by accessing the associated objects through property accessor methods. * Retrieving by Identifier. * Using the Hibernate Query Language (HQL). * Using the Hibernate Criteria API. * Using native SQL Queries. What is the difference between beans and Hibernate? Ans: Hibernate uses POJO classes for handling persistence, these classes need to adhere normal bean writing. Beans are at form (view) level and Hibernate are at database level. JavaBeans are simple reusable component whereas hibernate are supports for the JavaBean object persistency. How will you create a primary key using Hibernate? Ans: The id field in hbm.xml file is used to specify the primary key in database. We can also use generator to specify the way primary key is generated to the database. For example

85

Here Id ="StudentId" act as primary key. What is the main advantage of using Hibernate than sql? Ans: The main advantage of using Hibernate over sql is that Hibernate avoids writing huge queries. Because most of the work is taken care by mapping and also criteria class is very useful for complex joins. We can also avoid JDBC API by using Hibernate. What is the difference between sorted and order collection in Hibernate? Ans: A sorted ordered collection is stored in memory using Java Comparetor, whereas ordered collection is stored at the database level using orderby clause. Caching While working with Hibernate web applications we will face so many problems in its performance due to database traffic. That to when the database traffic is very heavy . Actually hibernate is well used just because of its high performance only. So some techniques are necessary to maintain its performance. Caching is the best technique to solve this problem. In this article we will discuss about, how we can improve the performance of Hibernate webapplications using caching. The performance of Hibernate web applications is improved using caching by optimizing the databaseapplications. The cache actually stores the data already loaded from the database, so that the traffic between ourapplication and the database will be reduced when the application want to access that data again. Maximum theapplication will works with the data in the cache only. Whenever some another data is needed, the database will be accessed. Because the time needed to access the database is more when compared with the time needed to access the cache. So obviously the access time and traffic will be reduced between the application and the database. Here the cache stores only the data related to current running application. In order to do that, the cache must be cleared time to time whenever the applications are changing. Here are the contents.  Introduction. o First-level cache. o Second-level cache.  Cache Implementations. o EHCache. o OSCache. o SwarmCache. o JBoss TreeCache.  Caching Stringategies. o Read-only. o Read-Write. o Nonstriict read-write. o Transactional.  Configuration.  element.  Caching the queries.  Custom Cache. o Configuration. o Implementation :: ExampleCustomCache.  Something about Caching. o Performance. o About Caching.  Conclusion. Hibernate uses two different caches for objects: first-level cache and second-level cache..

86

1.1) First-level cache First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces thenumber of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction. 1.2) Second-level cache Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entireapplication, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it. 2) Cache Implementations Hibernate supports four open-source cache implementations named EHCache (Easy Hibernate Cache), OSCache (Open Symphony Cache), Swarm Cache, and JBoss Tree Cache. Each cache has differentperformance, memory use, and configuration possibilities. 2.1) 2.1 EHCache (Easy Hibernate Cache) (org.hibernate.cache.EhCacheProvider)  It is fast.  lightweight.  Easy-to-use.  Supports read-only and read/write caching.  Supports memory-based and disk-based caching.  Does not support clustering. 2.2)OSCache (Open Symphony Cache) (org.hibernate.cache.OSCacheProvider)  It is a powerful .  flexible package  supports read-only and read/write caching.  Supports memory- based and disk-based caching.  Provides basic support for clustering via either JavaGroups or JMS. 2.3)SwarmCache (org.hibernate.cache.SwarmCacheProvider)  is a cluster-based caching.  supports read-only or nonstrict read/write caching .  appropriate for applications those have more read operations than write operations. 2.4)JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)  is a powerful replicated and transactional cache.  useful when we need a true transaction-capable caching architecture . 3) Caching Stringategies Important thing to remembered while studying this one is none of the cache providers support all of the cache concurrency strategies. 3.1) Read-only  Useful for data that is read frequently but never updated.  It is Simple .  Best performer among the all. Advantage if this one is, It is safe for using in a cluster. Here is an example for using the readonly cache strategy. .... 3.2) Read-Write  Used when our data needs to be updated.  It’s having more overhead than read-only caches.  When Session.close() or Session.disconnect() is called the transaction should be completed in an environment where JTA is no used.

87

 

It is never used if serializable transaction isolation level is required. In a JTA environment, for obtaining the JTA TransactionManager we must specify the propertyhibernate.transaction.manager_lookup_class.  To use it in a cluster the cache implementation must support locking. Here is an example for using the read-write cache stringategy. …. …. 3.3) Nonstrict read-write  Needed if the application needs to update data rarely.  we must specify hibernate.transaction.manager_lookup_class to use this in a JTA environment .  The transaction is completed when Session.close() or Session.disconnect() is called In other environments (except JTA) . Here is an example for using the nonstrict read-write cache stringategy. …. 3.4) Transactional  It supports only transactional cache providers such as JBoss TreeCache.  only used in JTA environment. Hibernate is an Open Source Object Relational mapping tool which provides transparent persistence for POJOs. Object-relational mapping is used to map object-oriented programming objects to relational databases managed by Oracle, DB2, Sybase, and other relational database managers (RDBMSs). Hibernate is evolved from the JBoss core persistence framework.

88

Other popular ORM solutions are iBatis, JDO and TopLink. Advantages of Hibernate:  Retains natural object model (transparent)  Minimizes Code  Does not require a container  Model is not tied to persistence implementation.  Metadata controlled persistence  Transparent - working with the model, not the data access technology  Pooling, Caching, Transactions can all be handled outside of our code Object/relational mappings are defined in an XML document. The mapping document is designed to be readable and hand-editable. The mapping language is Java-centric, meaning that mappings are constructed around persistent class declarations, not table declarations. Even though many Hibernate users choose to define XML mappings be hand, a number of tools exist to generate the mapping document, including XDoclet, Middlegen and AndroMDA. Before we move to hibernate mapping here is a basic JDBC connection configured in hibernate. uid pwd jdbc:mysql://localhost/db com.mysql.jdbc.Driver org.hibernate.dialect.MySQLDialect To use Hibernate-provided JDBC connections, the configuration file requires the following five properties:  connection.driver_class -The JDBC connection class for the specific database  connection.url -The full JDBC URL to the database  connection.username -The username used to connect to the database  connection.password -The password used to authenticate the username  dialect -The name of the SQL dialect for the database

89

A typical hibernate component mapping looks as this: The mapping definition starts with the hibernate-mapping element. The package attribute sets the default package for unqualified class names in the mapping. With this attribute set, you need only give the class name for other persistent classes listed in the mapping file, such as the Speaker and Attendee classes. To refer to a persistent class outside the given package, you must provide the fully qualified class name within the mapping document. If Hibernate has trouble locating a class because of a missing package on, for instance, a many-toone element, Hibernate throws a MappingException. This doesn't mean that Hibernate can't find the actual class file, but that it isn't able to navigate from one mapping definition to another. Immediately after the hibernate-mapping tag, you encounter the class tag. The class tag begins the mapping definition for a specific persistent class. The table attribute names the relational table used to store the state of the object. The class element has a number of attributes available, altering how Hibernate persists instances of the class. The id element describes the primary key for the persistent class as well as how the key value is generated. Each persistent class must have an id element declaring the primary key for the relational table. Let's look at the id element: The name attribute defines the property in your persistent class that will be used to store the primary key value. The id element implies that the Event class has a property also named id: public Long getId(){ return this.id; } public void setId(Long id){ this.id =id; } If the column for the primary key has a different name than your object property, the column attribute is used. For our example's purposes, this column name is uid . The values of the type and unsaved-value attributes depend on the generator used. The generator creates the primary key value for the persistent class. Hibernate provides multiple generator implementations that use various methods to create primary key values. Some implementations increment a value stored in a shared database table, whereas others create hexadecimal strings. Another generator, called assigned , lets you generate and assign the object ID. The assigned generator allows applications to reuse legacy code, such as the UUID generator from an EJB application. A recent introduction is the select generator, which retrieves the primary

90

key value by selecting a value from a database trigger. The generator type you choose determines its behavior based on the underlying database. You've used the native generator class in mapping definitions. native generators provide portability for mapping documents since the framework can determine the generator method supported by the database. Generators using the native class will use identity or sequence columns depending on available database support. If neither method is supported, the native generator falls back to a high/low generator method to create unique primary key values. Databases supporting identity columns include Sybase, MySQL, Microsoft SQL Server, and IBM DB2. Oracle, PostgreSQL, and SAP DB support sequence columns. The native generator returns a short, integer, or long value. You've set the type attribute to long, and the id property in the Event object has a type of java.lang.Long. The value of the type attribute and the property type in the object must be the same. The different types of Id generators supported by hibernate are: 1. increment: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment. 2. identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int. 3. sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int 4. hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection. 5. seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence. 6. uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32. 7. guid: It uses a database-generated GUID string on MS SQL Server and MySQL. 8. native: It picks identity, sequence or hilo depending upon the capabilities of the underlying database. 9. assigned: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no element is specified. 10. select: retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value. 11. foreign: uses the identifier of another associated object. Usually used in conjunction with a primary key association. The unsaved-value attribute describes the value of the id property for transient instances of this class. The unsaved-value attribute affects how objects are stored. We'll discuss the impact of this attribute later in the article. Properties Property elements for the Event object are similar to the id element: Each property element corresponds to a property in the Event object. The name attribute contains the property name, whereas the type attribute specifies the property object type. The column used to store the property value defaults to the property name. The column attribute overrides this default behavior, as shown in the startDate property. If the type attribute is omitted, Hibernate determines the type using runtime reflection. In certain cases, you must provide the property type, since reflection may not be able to determine the desired type (such as differentiating between the Hibernate DATE and TIMESTAMP types). Valid property types include the Hibernate basic types, such as integer, string, and timestamp, as well as the corresponding Java objects and primitives. However, you aren't limited to basic data types. The property element may also contain the name of a serializable Java class or a user-defined type.

91

You create a new user-defined type by implementing either the org.hibernate.UserType or org.hibernate. CompositeUserType interface. The fully qualified class name of the user type or the serializable Java class is used as the property type value. Hibernate supports different types of association and collection mappings. Download the sample source for each of the following mappings here. 1. Simple Association (one to one) 2. Simple Reference (many to one) 3. Proxies 4. Basic Collection (one to many) 5. Collection (many to many) 6. Collection (raw data) 7. Top-level Collections 8. Map 9. Entity Map 10. Subclasses 11. Joined Subclasses 12. Components 13. Collections of Components 14. Composite Id 15. Composite Index 16. Ternary Associations Cascades If you've worked with relational databases, you've no doubt encountered cascades. Cascades propagate certain operations on a table (such as a delete) to associated tables. (Remember that tables are associated through the use of foreign keys.) Suppose that when you delete an Event, you also want to delete each of the Speaker instances associated with the Event. Instead of having the application code perform the deletion, Hibernate can manage it for you. Hibernate supports ten different types of cascades that can be applied to many-to-one associations as well as collections. The default cascade is none. Each cascade strategy specifies the operation or operations that should be propagated to child entities. The cascade types that you are most likely to use are the following:  all -All operations are passed to child entities: save , update , and delete.  save-update -Save and update ( and UPDATE , respectively) are passed to child entities.  delete -Deletion operations are passed to child entities.  delete-orphan -All operations are passed to child entities, and objects no longer associated with the parent object are deleted. The cascade element is added to the desired many-to-one or collection element. For example, the following configuration instructs Hibernate to delete the child Speaker elements when the parent Event is deleted: That's all there is to configuring cascades. It's important to note that Hibernate doesn't pass the cascade off to the database. Instead, the Hibernate service manages the cascades internally. This is necessary because Hibernate has to know exactly which objects are saved, updated, and deleted. Fetching associated objects When an object has one or more associated objects, it's important to consider how associated objects will be loaded. Hibernate 3 offers you two options. You can either retrieve associated objects using an outer join or by using a separate SELECT statement. The fetch attribute allows you to specify which method to use: When an Event instance is loaded, the associated Location instance will be loaded using an outer join. If you wanted to use a separate select, the many-to-one element would look like this:

92

This also applies to child collections, but you can only fetch one collection using a join per persistent object. Additional collections must be fetched using the SELECT strategy. If you're using Hibernate 2, the fetch attribute is not available. Instead, you must use the outerjoin attribute for many-to-one associations. (There is no support for retrieving collections using a SELECT in Hibernate 2.) The outer-join attribute takes either a true or false value. Building the SessionFactory Hibernate's SessionFactory interface provides instances of the Session class, which represent connections to the database. Instances of SessionFactory are thread-safe and typically shared throughout an application. Session instances, on the other hand, aren't thread-safe and should only be used for a single transaction or unit of work in an application. Configuring the SessionFactory The Configuration class kicks off the runtime portion of Hibernate. It's used to load the mapping files and create a SessionFactory for those mapping files. Once these two functions are complete, the Configuration class can be discarded. Creating a Configuration and SessionFactory instance is simple, but you have some options. There are three ways to create and initialize a Configuration object. This first snippet loads the properties and mapping files defined in the hibernate.cfg.xml file and creates the SessionFactory: Configuration cfg =new Configuration(); SessionFactory factory =cfg.configure().buildSessionFactory(); The configure()method tells Hibernate to load the hibernate.cfg.xml file. Without that, only hibernate.properties would be loaded from the classpath. The Configuration class can also load mapping documents programmatically: Configuration cfg =new Configuration(); cfg.addFile("com/manning/hq/ch03/Event.hbm.xml"); Another alternative is to have Hibernate load the mapping document based on the persistent class. This has the advantage of eliminating hard-coded filenames in the source code. For instance, the following code causes Hibernate to look for a file named com/manning/hq/ Event.hbm.xml in the classpath and load the associated class: Configuration cfg =new Configuration(); cfg.addClass(com.manning.hq.ch03.Event.class); Since applications can have tens or hundreds of mapping definitions, listing each definition can quickly become cumbersome. To get around this, the hibernate.cfg.xml file supports adding all mapping files in a JAR file. Suppose your build process creates a JAR file named application.jar, which contains all the classes and mapping definitions required. You then update the hibernate.cfg.xml file: Of course, you can also do this programmatically with the Configuration class: Configuration.addJar(new java.io.File("application.jar")); Keep in mind that the JAR file must be in the application classpath. If you're deploying a web application archive (WAR) file, your application JAR file should be in the /WEB-INF/lib directory in the WAR file. The four methods used to specify mapping definitions to the Hibernate runtime can be combined, depending the requirements for your project. However, once you create the SessionFactory from the Configuration instance, any additional mapping files added to the Configuration instance won't be reflected in the SessionFactory . This means you can't add new persistent classes dynamically. You can use the SessionFactory instance to create Session instances: Session session =factory.openSession(); Instances of the Session class represent the primary interface to the Hibernate framework. They let you persist objects, query persistent objects, and make persistent objects transient. Let's look at persisting objects with Hibernate. Persisting objects Persisting a transient object with Hibernate is as simple as saving it with the Session instance:

93

Event event =new Event(); //populate the event Session session =factory.openSession(); session.save(event); session.flush(); Calling save(...)for the Event instance assigns a generated ID value to the instance and persists the instance. (Keep in mind that Hibernate doesn't set the ID value if the generator type is assigned.) The flush() call forces persistent objects held in memory to be synchronized to the database. Session’s don't immediately write to the database when an object is saved. Instead, the Session queues a number of database writes to maximize performance. If you would like to update an object that is already persistent, the update(...)method is available. Other than the type of SQL operation executed, the difference between save(...)and update(...)is that update(...)doesn't assign an ID value to the object. Because of this minor difference, the Session interface provides the saveOrUpdate(...) methods, which determine the correct operation to execute on the object. How does Hibernate know which method to call on an object? When we described the mapping document, we mentioned the unsaved-value attribute. That attribute comes into play when you use the saveOrUpdate(...)method. Suppose you have a newly created Event instance. The id property is null until it's persisted by Hibernate. If the value is null, Hibernate assumes that the object is transient and assigns a new id value before saving the instance. A non-null id value indicates that the object is already persistent; the object is updated in the database, rather than inserted. You could also use a long primitive to store the primary key value. However, using a primitive type also means that you must update the unsaved-value attribute value to 0, since primitive values can't be null. Here's the necessary code to persist an Event instance: Configuration cfg =new Configuration(); SessionFactory factory =cfg.buildSessionFactory(); Event event =new Event(); //populate the Event instance Session session =factory.openSession(); session.saveOrUpdate(event); session.flush(); session.close(); The first two lines create the SessionFactory after loading the configuration file from the classpath. After the Event instance is created and populated, the Session instance, provided by the SessionFactory , persists the Event. The Session is then flushed and closed, which closes the JDBC connection and performs some internal cleanup. That's all there is to persisting objects. Once you've persisted a number of objects, you'll probably want to retrieve them from the database. Retrieving persistent objects is the topic of the next section. Retrieving objects Suppose you want to retrieve an Event instance from the database. If you have the Event ID, you can use a Session to return it: Event event =(Event)session.load(Event.class,eventId); session.close(); This code tells Hibernate to return the instance of the Event class with an ID equal to eventId. Notice that you're careful to close the Session, returning the database connection to the pool. There is no need to flush the Session, since you're not persisting objects-only retrieving them. What if you don't know the ID of the object you want to retrieve? This is where HQL enters the picture. The Session interface allows you to create Query objects to retrieve persistent objects. (In Hibernate 2, the Session interface supported a number of overloaded find methods. They were deprecated in Hibernate 3.) HQL statements are object-oriented, meaning that you query on object properties instead of database table and column names. Let’s look at some examples using the Query interface. This example returns a collection of all Event instances. Notice that you don't need to provide a select ...clause when returning entire objects: Query query =session.createQuery("from Event"); List events =query.list();

94

This query is a little more interesting since we're querying on a property of the Event class: Query query =session.createQuery("from Event where name ="+ "'Opening Presentation'"); List events =query.list(); We've hardcoded the name value in the query, which isn't optimal. Let's rewrite it: Query query =session.createQuery("from Event where name =?", "Opening Presentation"); query.setParameter(0,"Opening Presentation",Hibernate.STRING); List events =query.list(); The question mark in the query string represents the variable, which is similar to the JDBC PreparedStatement interface. The second method parameter is the value bound to the variable, and the third parameter tells Hibernate the type of the value. (The Hibernate class provides constants for the built-in types, such as STRING , INTEGER , and LONG , so they can be referenced programmatically.) One topic we haven't touched on yet is the cache maintained by the Session. The Session cache tends to cause problems for developers new to Hibernate, so we'll talk about it next. The Session cache One easy way to improve performance within the Hibernate service, as well as your applications, is to cache objects. By caching objects in memory, Hibernate avoids the overhead of retrieving them from the database each time. Other than saving overhead when retrieving objects, the Session cache also impacts saving and updating objects. Let's look at a short code listing: Session session =factory.openSession(); Event e =(Event)session.load(Event.class,myEventId); e.setName("New Event Name"); session.saveOrUpdate(e); //later,with the same Session instance Event e =(Event)session.load(Event.class,myEventId); e.setDuration(180); session.saveOrUpdate(e); session.flush(); This code first retrieves an Event instance, which the Session caches internally. It then does the following: updates the Event name, saves or updates the Event instance, retrieves the same Event instance (which is stored in the Session cache), updates the duration of the Event,and saves or updates the Event instance. Finally, you flush the Session. All the updates made to the Event instance are combined into a single update when you flush the Session. This is made possible in part by the Session cache. The Session interface supports a simple instance cache for each object that is loaded or saved during the lifetime of a given Session. Each object placed into the cache is keyed on the class type, such as The Session cache com.manning.hq.ch03.Event, and the primary key value. However, this cache presents some interesting problems for unwary developers. A common problem new developers run into is associating two instances of the same object with the same Session instance, resulting in a NonUniqueObjectException. The following code generates this exception: Session session =factory.openSession(); Event firstEvent =(Event)session.load(Event.class,myEventId); //...perform some operation on firstEvent Event secondEvent =new Event(); secondEvent.setId(myEventId); session.save(secondEvent); This code opens the Session instance, loads an Event instance with a given ID, creates a second Event instance with the same ID, and then attempts to save the second Event instance, resulting in the Non-UniqueObjectException. Any time an object passes through the Session instance, it's added to the Session’s cache. By passes through, we're referring to saving or retrieving the object to and from the database. To see whether an object is contained in the cache, call the Session.contains()method. Objects can be evicted from the cache by calling the Session.evict() method. Let's revisit the previous code, this time evicting the first Event instance:

95

Session session =factory.openSession(); Event firstEvent =(Event)session.load(Event.class,myEventId); //...perform some operation on firstEvent if (session.contains(firstEvent)){ session.evict(firstEvent); } Event secondEvent =new Event(); secondEvent.setId(myEventId); session.save(secondEvent); The code first opens the Session instance and loads an Event instance with a given ID. Next, it determines whether the object is contained in the Session cache and evicts the object if necessary. The code then creates a second Event instance with the same ID and successfully saves the second Event instance. If you simply want to clear all the objects from the Session cache, you can call the aptly named Session.clear()method. Connection pools Connection pools are a common way to improve application performance. Rather than opening a separate connection to the database for each request, the connection pool maintains a collection of open database connections that are reused. Application servers often provide their own connection pools using a JNDI DataSource, which Hibernate can take advantage of when configured to use a DataSource. If you're running a standalone application or your application server doesn't support connection pools, Hibernate supports three connection pooling services: C3P0, Apache's DBCP library, and Proxool. C3P0 is distributed with Hibernate; the other two are available as separate distributions. When you choose a connection pooling service, you must configure it for your environment. Hibernate supports configuring connection pools from the hibernate.cfg.xml file. The connection.provider_class property sets the pooling implementation: org.hibernate.connection.C3P0ConnectionProvider Once the provider class is set, the specific properties for the pooling service can also be configured from the hibernate.cfg.xml file: 5 ... 1000 As you can see, the prefix for the C3P0 configuration parameters is c3p0. Similarly, the prefixes for DBCP and Proxool are dbcp and proxool, respectively. Specific configuration parameters for each pooling service are available in the documentation with each service. Table 1 lists information for the supported connection pools. Hibernate ships with a basic connection pool suitable for development and testing purposes. However, it should not be used in production. You should always use one of the available connection pooling services, like C3P0, when deploying your application to production.

If your preferred connection pool API isn't currently supported by Hibernate, you can add support for it by implementing the org.hibernate.connection.ConnectionProvider interface. Implementing the interface is straightforward. Connection pooling services Pooling Service C3PO

Provider Class Apache DBCP

Configuration Prefix Proxool

org.hibernate.connecorg.hibernate.connecorg.hibernate.connection.C3P0ConnectionProvider tion.ProxoolConnectionProvider tion.DBCPConnectionProvider

96

c3p0

Dbcp

proxool

There isn't much to using a connection pool, since Hibernate does most of the work behind the scenes. The next configuration topic we’ll look at deals with transaction management with the Hibernate Transaction API. Transactions Transactions group many operations into a single unit of work. If any operation in the batch fails, all of the previous operations are rolled back, and the unit of work stops. Hibernate can run in many different environments supporting various notions of transactions. Standalone applications and some application servers only support simple JDBC transactions, whereas others support the Java Transaction API (JTA). Hibernate needs a way to abstract the various transaction strategies from the environment. Hibernate has its own Transaction class that is accessible from the Session interface, demonstrated here: Session session =factory.openSession(); Transaction tx =session.beginTransaction(); Event event =new Event(); //...populate the Event instance session.saveOrUpdate(event); tx.commit(); In this example, factory is an initialized SessionFactory instance. This code creates an instance of the org.hibernate.Transaction class and then commits the Transaction instance. Notice that you don't need to call session.flush(). Committing a transaction automatically flushes the Session object. The Event instance is persisted to the database when the transaction is committed. The transaction strategy you use (JDBC or JTA) doesn't matter to the application codeit's set in the Hibernate configuration file. The transaction.factory_class property defines the transaction strategy that Hibernate uses. The default setting is to use JDBC transactions since they're the most common. To use JTA transactions, you need to set the following properties in hibernate.cfg.xml: org.hibernate.transaction.JTATransactionFactory java:comp/UserTransaction The transaction.factory_class property tells Hibernate that you'll be using JTA transactions. Currently, the only other option to JTA is JBDC transactions, which is the default. JTA transactions are retrieved from a JNDI URI, which is specified using the jta.User-Transaction property. If you don't know the URI for your specific application server, the default value is java:comp/UserTransaction. There is some confusion about another property related to JTA transactions: transaction.manager_lookup_class. You only need to specify the manager lookup class when you're using a transactional cache. (We discuss caches in the next section–don't worry.) However, if you don't define the jta.UserTransaction property and transaction.manager_lookup_class is defined, the user transaction name in the lookup factory class is used. If neither of the properties are used, Hibernate falls back to java:comp/UserTransaction. What's the benefit of using JTA transactions? JTA transactions are useful if you have multiple transactional resources, such as a database and a message queue. JTA allows you to treat the disparate transactions as a single transaction. Combining multiple transactions also applies within Hibernate. If you attempt to create multiple transactions from the same Session instance, all of the operations are batched into the first transaction. Let's look at an example that includes two transactions: Transaction tx0 =session.beginTransaction(); Event event =new Event(); //...populate the event instance session.saveOrUpdate(event); Transaction tx1 =session.beginTransaction(); Location location =new Location(); //...populate the Location instance

97

session.saveOrUpdate(location); tx0.commit(); tx1.commit(); This example begins by creating a new transaction. The second use of session.beginTransaction()just returns the first transaction instance. session.saveOrUpdate(location)commits the first transaction, and tx0.commit()recommits the first transaction. Although you explicitly create two Transaction objects, only one is used. Of course, this creates a problem. Let's assume you have a Session object being used by two application threads. The first application thread begins the JTA transaction and starts adding objects. Meanwhile, the second thread, using the same transaction, deletes an object and commits the transaction. Where does this leave the first thread? The first thread won't be committed, which is what you'd expect. The problem is that this issue can be hard to debug, bringing up an important point: Sessions should be used by only one application thread at a time. This is a common concern in web applications, which are multithreaded by their very nature. Cache providers As we mentioned earlier, caching is a common method used to improve application performance. Caching can be as simple as having a class store frequently used data, or a cache can be distributed among multiple computers. The logic used by caches can also vary widely, but most use a simple least recently used (LRU) algorithm to determine which objects should be removed from the cache after a configurable amount of time. Before you get confused, let's clarify the difference between the Session–level cache, also called the first–level cache, and what this section covers. The Session–level cache stores object instances for the lifetime of a given Session instance. The caching services described in this section cache data outside of the lifetime of a given Session. Another way to think about the difference is that the Session cache is like a transactional cache that only caches the data needed for a given operation or set of operations, whereas a second–level cache is an application-wide cache. By default, Hibernate supports four different caching services. EHCache (Easy Hibernate Cache) is the default service. If you prefer to use an alternative cache, you need to set the cache.provider_class property in the hibernate.cfg.xml file: org.hibernate.cache.OSCacheProvider

This snippet sets the cache provider to the OSCache caching service. Caching Services Supported by Hibernate Caching Service

Provider Class

Type

EHCache

org.hibernate.cache.EhCacheProvider

Memory,disk

OSCache

org.hibernate.cache.OSCacheProvider

Memory,disk

SwarmCache

org.hibernate.cache.SwarmCacheProvider Clustered

TreeCache

org.hibernate.cache.TreeCacheProvider

Clustered

The caching services support the caching of classes as well as collections belonging to persistent classes. For instance, suppose you have a large number of Attendee instances associated with a particular Event instance. Instead of repeatedly fetching the collection of Attendee s, you can cache it. Caching for classes and collections is configured in the mapping files, with the cache element: ... Collections can also be cached:

98

... Once you've chosen a caching service, what do you, the developer, need to do differently to take advantage of cached objects? Thankfully, you don't have to do anything. Hibernate works with the cache behind the scenes, so concerns about retrieving an outdated object from the cache can be avoided. You only need to select the correct value for the usage attribute. The usage attribute specifies the caching concurrency strategy used by the underlying caching service. The previous configuration sets the usage to read–write , which is desirable if your application needs to update data. Alternatively, you may use the nonstrict–read–write strategy if it's unlikely two separate transaction threads could update the same object. If a persistent object is never updated, only read from the database, you may specify set usage to read-only. Some caching services, such as the JBoss TreeCache, use transactions to batch multiple operations and perform the batch as a single unit of work. If you choose to use a transactional cache, you may set the usage attribute to transactional to take advantage of this feature. If you happen to be using a transactional cache, you'll also need to set the transaction.manager_lookup_class mentioned in the previous section.

The supported caching strategies differ based on the service used. Supported Caching Service Strategies Caching Service

Readonly

Readwrite

Nonstrict-readTransactional write

EHCache

Y

Y

Y

N

OSCache

Y

Y

Y

N

SwarmCache

Y

Y

Y

N

TreeCache

Y

N

N

Y

Clearly, the caching service you choose will depend on your application requirements and environment. Next, let's look at configuring EHCache. Configuring EHCache By now you're probably tired of reading about configuring Hibernate, but EHCache is pretty simple. It's a single XML file, placed in a directory listed in your classpath. You'll probably want to put the ehcache.xml file in the same directory as the hibernate.cfg.xml file. ehcache.xml file In this example, the diskStore property sets the location of the disk cache store. Then, the listing declares two caches. The defaultCache element contains the settings for all cached objects that don't have a specific cache element: the number of cached objects held in memory, whether objects in the cache expire (if eternal is true , then objects don't expire), the number of seconds an object should remain the cache after it was last accessed, the number of seconds an object should remain in the cache after it was created, and whether objects exceeding maxElementsInMemory should be spooled to the diskStore. Next, for custom settings based on the class, the code defines a cache element with the fully qualified class name listed in the name attribute. (This listing only

99

demonstrates a subset of the available configuration for EHCache. Please refer to the documentation found at http:// ehcache.sf.net for more information.) Inheritance Inheritance is a fundamental concept of object-oriented languages. Through inheritance, objects can inherit the state and behavior of their ancestor, or superclass. The most common use of object inheritance in applications is to create a generic base type with one or more specialized subclasses. Persisting a class hierarchy can be difficult, since each hierarchy can have its own unique requirements. To address the problems found in hierarchy persistence, Hibernate supports three different inheritance persistence strategies:  Table per class hierarchy  Table per subclass  Table per concrete class Each mapping strategy is incrementally more complicated. In the following sections, we‘ll discuss the first two inheritance strategies. We've never needed to use the third, and most complicated, strategy. Table per class hierarchy This strategy is the most basic and easiest to use. All the classes in the hierarchy are stored in a single table. Suppose you have the base Event class, with ConferenceEvent and NetworkingEvent as subclasses. The mapping definition for this hierarchy is shown in listing 6. Listing 6. Table per class hierarchy mapping ... ... ... We've introduced a few new features in the mapping definition. The most important is the inclusion of the discriminator element. The discriminator column is what Hibernate uses to tell the different sub-classes apart when retrieving classes from the database. If you don't specify a discriminator value, Hibernate uses the object's class name. The discriminator element in the example mapping tells Hibernate to look in the event_type column for a string describing the class type. The discriminator is only a column in the relational table-you don't need to define it as a property in your Java object. The subclass element contains the properties and associations belonging to the subclass. Any association element is allowed between sub- class tags. You can't have an id element or a nested subclass element. The table per class hierarchy strategy requires a single table, events, to store the three types of Event instances. As you can see, one table contains the fields for all the objects in the hierarchy. The only obvious limitation is that your subclasses can‘t have columns declared as NOT NULL. Subclasses can't have non-null attributes because inserting the superclass, which doesn‘t even have the non-null attribute, will cause a null column violation when it‘s inserted into the database. The next inheritance strategy, table per sub-class, doesn't have this limitation. Table per subclass Instead of putting all the classes into a single table, you can choose to put each subclass into its own table. This approach eliminates the discriminator column and introduces a one-to-one mapping from the sub-class tables to the superclass table. The mapping definition for this strategy is shown in listing 7. Table-per-subclass mapping

100

... ... The joined-subclass element can contain the same elements as the subclass element. The key element contains the primary key associa-tion to the superclass, Event. Table per concrete class Since this association can refer to any class in the Event hierarchy, the association is referred to as a polymorphic association. You can also create a concrete association by giving the name of the specific subclass: How To Enable Second Level Caching In Hibernate First level cache will be enabled by default, but for enable second level cache we need to follow somesettings, let us see few points regarding this..  Second level cache was introduced in hibernate 3.0  When ever we are loading any object from the database, then hibernate verify whether that object is available in the local cache memory of that particular session [ means first level cache ], if not available then hibernate verify whether the object is available in global cache or factory cache [second level cache ], if not available then hibernate will hit the database and loads the object from there, and then first stores in the local cache of the session [ first level ] then in the global cache [ second level cache ]  When another session need to load the same object from the database, then hibernate copies that object from global cache [ second level cache ] into the local cache of this new session Second level cache in the hibernate is of from 4 vendors…  Easy Hibernate [EHCache] Cache from hibernate framework  Open Symphony [OS] cache from Open Symphony  SwarmCache  TreeCache from JBoss How to enable second level cache in hibernate We need one provider class, hear we are going to see hibernate provider class that is EHCache Changes required To enable second level cache in the hibernate, then the following 3 changes are required Add provider classin hibernate configuration file like… 1 2 org.hibernate.cache.EhCacheProvider 3 Configure cache elementfor a class in hibernate mapping file… 1 Note: this must write soon after create xml file called ehcache.xml and store in at class path location [ no confusions, i mean in the place where you have mapping and configuration XML's ] in web application. Important points on this second level cache

101

Lets take an example, we have 2 pojo classes in our application like Student, Employee.  If we load student object from the database, then as its the first time hibernate will hits the database and fetch this student object data and stores in the session1 cache memory [ First level cache ], then in the global cache [ second level cache ] provided if we write in the student mapping file  I mean hibernate will stores in the local session memory by default, but it only stores in the global cache [ second level cache ] only if we write in the student mapping file, if not so hibernate wont stores in the global cache  Now take another session like session 2 for example, if session 2 also load the student object then hibernate will loads from the global cache [ second level cache ] as student object is available at global [Actually when ever we want to load any object hibernate first will checks at local, then global then database right hope you remembered this ], now if session 3 modify that student object then hibernate will thorows an error because we have written in student mapping file  We can avoid this by writing  so remember element has that much importance Difference between HQL and Criteria Query in Hibernate Let us see the main differences between HQL and Criteria Query  HQL is to perform both select and non-select operations on the data, but Criteria is only for selecting the data, we cannot perform non-select operations using criteria  HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries  HQL doesn’t support pagination concept, but we can achieve pagination with Criteria  Criteria used to take more time to execute then HQL  With Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection. -------------------------Hibernate---------------------------

1.what is the advantage of Hibernate over jdbc? There are so many 1) Hibernate is data base independent, your code will work for all ORACLE,MySQL ,SQLServer etc. In case of JDBC query must be data base specific. So hibernate based persistance logic is database independent persistance logic and JDBC based persistance logic is database dependent logic. 2) As Hibernate is set of Objects , 3) No need to learn SQL language.You can treat TABLE as a Object . Only Java knowledge is need. In case of JDBC you need to learn SQL. 3) Dont need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance. In case of JDBC you need to tune your queries. 4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance. In case of JDBC you need to implement your java cache . 5) Hibernate supports Query cache and It will provide the statistics about your query and database status. JDBC Not provides any statistics. 6) Development fast in case of Hibernate because you dont need to write queries 7) No need to create any connection pool in case of Hibernate. You can use c3p0. In case of JDBC you need to write your own connection pool 8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability. 9) You can load your objects on start up using lazy=false in case of Hibernate. JDBC Dont have such support. 10 ) Hibernate Supports automatic versioning of rows but JDBC Not.

102

2.What is Hibernate? Hibernate is an open source, light weight Object Relational Mapping tool to develop the database independent persistence login in java and j2ee based applications. Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration and mapping files. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks 3.What is ORM ? ORM stands for object/relational mapping, means providing the mapping between class with table and member variables with columns is called ORM. ORM is the automated persistence of objects in a Java application to the tables in a relational database. 4.hat does ORM consists of ? An ORM solution consists of the following four pieces:    

API for performing basic CRUD operations API to express queries referring to classes Facilities to specify metadata Optimization facilities : dirty checking,lazy associations fetching

5.What are the ORM levels ? The ORM levels are:    

Pure relational (stored procedure.) Light objects mapping (JDBC) Medium object mapping Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

. 6.Why do you need ORM tools like hibernate? The main advantage of ORM like hibernate is that it can develop the database independent persistence logic. Apart from this, ORM provides following benefits: 



  

Improved productivity o High-level object-oriented API o Less Java code to write o No SQL to write Improved performance o Sophisticated caching o Lazy loading o Eager loading Improved maintainability o A lot less code to write Improved portability ORM framework generates database-specific SQL for you

7.What Does Hibernate Simplify? Hibernate simplifies:     

Saving and retrieving your domain objects Making database column and table name changes Centralizing pre save and post retrieve logic Complex joins for retrieving related items Schema creation from object model

8.What is the main difference between Entity Beans and Hibernate ? 1)In Entity Bean at a time we can interact with only one data Base. Where as in Hibernate we can able to establishes the connections to more than One Data Base. Only thing we need to write one

103

more configuration file. 2) EJB need container like Weblogic, WebSphare but hibernate don't nned. It can be run on tomcat. 3) Entity Beans does not support OOPS concepts where as Hibernate does. 4) Hibernate supports multi level cacheing, where as Entity Beans doesn't. 5) In Hibernate C3P0 can be used as a connection pool. 6) Hibernate is container independent. EJB not. 9.What are the Core interfaces and classes of Hibernate framework? The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.     

Configuration class (org.hibernate.cfg package) Session interface (org.hibernate package) SessionFactory interface (org.hibernate package) Transaction interface (org.hibernate package) Query and Criteria interfaces (org.hibernate package)

10.What is the general flow of Hibernate communication with RDBMS? The general flow of Hibernate communication with RDBMS is :     

Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files because mapping file can be configured in configuration file. Create session factory from configuration object Get one session from this session factory Create HQL Query Execute query to get list containing Java objects.

13.What role does the Session interface play in Hibernate? The main runtime interface between a Java application and Hibernate The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states: transient: never persistent, not associated with any Session persistent: associated with a unique Session detached: previously persistent, not associated with any Session Session session = sessionFactory.openSession(); Session interface role:   

Wraps a JDBC connection Factory for Transaction Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

14.What role does the SessionFactory interface play in Hibernate? SessionFactorys are immutable. The behaviour of a SessionFactory is controlled by properties supplied at configuration time. These properties are defined on Environment. The application obtains Session instances from a SessionFactory. There is typically a single

104

SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work Implementors must be threadsafe. SessionFactory sessionFactory = configuration.buildSessionFactory(); 15.What are the most common ways to specify the Hibernate configuration properties? The most common methods of Hibernate configuration are: 

Programmatic configuration By using setProperty(-) method of org.hibernate.cfg.Configuration.

  

XML configuration (hibernate.cfg.xml) By using .properties file By Using annotaions.(from Hibernate 3.3 on words)

16.How do you map Java Objects with Database tables?  

First we need to write Java domain objects (beans with setter and getter). Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example : 17.How do you define sequence generated primary key algorithm in hibernate? By using , tags we can configure the primary key and primary key generation algorithm. Example: SEQ_NAME 18.What is component mapping in Hibernate?    

A component is an object saved as a value, not as a reference A component can be saved directly without needing to declare interfaces or identifier properties Required to define an empty constructor Shared references not supported

19 . Difference between getCurrentSession() and openSession() in Hibernate ? getCurrentSession() : Obtains the current session. The "current session" refers to a Hibernate Session bound by Hibernate behind the scenes, to the transaction scope. A Session is opened when getCurrentSession() is called for the first time and closed when the

105

transaction ends. It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs. Only the Session that you obtained with sf.getCurrentSession() is flushed and closed automatically. openSession() : If you decide to use manage the Session yourself the go for sf.openSession() , you have to flush() and close() it. It does not flush and close() automatically. Example : Transaction tx =session.berginTransaction(); Session session = factory.openSession(); try { tx.begin(); // Do some work session.createQuery(...); session.persist(...); session.flush(); // Extra work you need to do tx.commit(); } catch (RuntimeException e) { tx.rollback(); throw e; // or display error message } finally { session.close(); // Extra work you need to do } 20.What are the types of Hibernate instance states ? Three types of instance states:   

Transient -The instance is not associated with any persistence context Persistent -The instance is associated with a persistence context Detached -The instance was associated with a persistence context which has been closed – currently not associated

21.What are the types of inheritance models in Hibernate? There are three types of inheritance models in Hibernate:   

Table per class hierarchy Table per subclass Table per concrete class

22.What is Hibernate Query Language (HQL)? Hibernate Query Language is query language which is used to develop the data independent query language in the application. This HQL queries are not related to any database. Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an objectoriented extension to SQL. 23.What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins:  

An implicit association join An ordinary join in the FROM clause A fetch join in the FROM clause.

106



A theta-style join in the WHERE clause.

24 . Transaction with plain JDBC in Hibernate ? If you don't have JTA and don't want to deploy it along with your application, you will usually have to fall back to JDBC transaction demarcation. Instead of calling the JDBC API you better use Hibernate's Transaction and the built-in session-per-request functionality: To enable the thread-bound strategy in your Hibernate configuration: set hibernate.transaction.factory_class to org.hibernate.transaction.JDBCTransactionFactory set hibernate.current_session_context_class to thread Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); // Do some work session.load(...); session.persist(...); tx.commit(); // Flush happens automatically } catch (RuntimeException e) { tx.rollback(); throw e; // or display error message } finally { session.close(); } 25 . What are the general considerations or best practices for defining your Hibernate persistent classes? 1.You must have a default no-argument constructor for your persistent classes and there should be getXXX()and setXXX() methods for all your persistable instance variables. 2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object. 3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster. 4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects. 26 . Difference between session.update() and session.lock() in Hibernate ? The session.update method is used to update the persistence object in the in the database. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction. 27.What are the Collection types in Hibernate ?

107

    

Set List Array Map Bag

28.What is the difference between sorted and ordered collection in hibernate? sorted collection vs. order collection :-

sorted collection

order collection

A sorted collection is sorting a collection by utilizing the sorting features provided by the Order collection is sorting a collection by Java collections framework. The sorting occurs specifying the order-by clause for sorting this in the memory of JVM which running Hibernate, collection when retrieval. after the data being read from database using java comparator. If your collection is not large, it will be more efficient way to sort it.

If your collection is very large, it will be more efficient way to sort it .

29.What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins:   

An implicit association join An ordinary join in the FROM clause A fetch join in the FROM clause. A theta-style join in the WHERE clause.

30.What do you mean by Named – SQL query? Named SQL queries are defined in the mapping xml document and called wherever required. Example: SELECT emp.EMP_ID AS {emp.empid}, emp.EMP_ADDRESS AS {emp.address}, emp.EMP_NAME AS {emp.name} FROM Employee EMP WHERE emp.NAME LIKE :name Invoke Named Query : List people = session.getNamedQuery("empdetails") .setString("TomBrady", name) .setMaxResults(50) .list(); 31.How do you invoke Stored Procedures? { ? = call selectAllEmployees() }

108



32.Explain Criteria API The interface org.hibernate.Criteria represents a query against a particular persistent class. The Session is a factory for Criteria instances. Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. Example : List employees = session.createCriteria(Employee.class) .add(Restrictions.like("name", "a%") ) .add(Restrictions.like("address", "Boston")) .addOrder(Order.asc("name") ) .list();

33.What’s the difference between load() and get()? get() load() Only use the load() method if you are sure that the If you are not sure that the object exists, object exists. then use one of the get() methods. load() method will throw an exception if the unique get() method will return null if the unique id id is not found in the database. is not found in the database. load() just returns a proxy by default and database get() will hit the database immediately. won’t be hit until the proxy is first invoked.

34.What is the difference between and merge and update ? Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

35.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

36.Define HibernateTemplate? org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions. 37.What are the benefits does HibernateTemplate provide? The benefits of HibernateTemplate are :    

HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session. Common functions are simplified to single method calls. Sessions are automatically closed. Exceptions are automatically caught and converted to runtime exceptions.

109

38. How do you switch between relational databases without code changes? Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

39.If you want to see the Hibernate generated SQL statements on console, what should we do? By using “show_sql” property of the hibernate configuration file In Hibernate configuration file set as follows: true

40.What are derived properties? The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

41.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

42 . Explain about transaction file? Transactions denote a work file which can save changes made or revert back the changes. A transaction can be started by session.beginTransaction() and it uses JDBC connection, CORBA or JTA. When this session starts several transactions may occur. 43 . Difference between session.save() , session.saveOrUpdate() and session.persist()? All methods are used to store the data in to database session.save() : save() method uSave does an insert and will fail if the primary key is already persistent. session.saveOrUpdate() : saveOrUpdate() insert the data in the database if that primary key data not available and it update the data if primary key data not availabt session.persist() :it is the same like session.save(). But session.save() return Serializable object but session.persist() return void. For Example : if you do :System.out.println(session.save(question)); This will print the generated primary key. if you do :System.out.println(session.persist(question)); Compile time error because session.persist() return void. 44 . Explain about the id field? This id field is used to configure the primary key in the mapping file, and also we can configure primary key generation algorithm.

110

45.What is the use of dynamic-insert and dynamic-update attributes in a class mapping? Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.  

dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

46.What is automatic dirty checking? Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

47.What are Callback interfaces? Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality. 48.What is Hibernate proxy? The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked. 49.How can Hibernate be configured to access an instance variable directly and not through a setter method ? By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object. 50.How can a whole class be mapped as immutable? Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application. 51 . Explain about transparent persistence of Hibernate? Transparent persistence is provided for Plain old Java objects or POJOs. For proper functioning of the applications importance should be given to the methods equals () and hash Code methods (). It has a requirement which should be strictly followed in the applications which is a no-argument constructor. 52 . Explain about the dirty checking feature of Hibernate? Dirty checking feature of the Hibernate allows users or developers to avoid time consuming data base write actions. This feature makes necessary updations and changes to the fields which require a change, remaining fields are left unchanged or untouched. 53 . What is the effect when a transient mapped object is passed onto a Sessions save? When a Sessions save () is passed to a transient mapped object it makes the method to become more persistent. Garbage collection and termination of the Java virtual machine stays as long as it is deleted explicitly. It may head back to its transient state. 54 . Explain about addClass function? This function translates a Java class name into file name. This translated file name is then loaded as an input stream from the Java class loader. This addClass function is important if you want efficient usage of classes in your code.

111

112

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF