• No results found

What are the Core interfaces are of Hibernate framework? People who read this also read:

In document Hibernate Notes (Page 82-87)

Can I map an inner class?

Step 2. Add Extra coulmn name "version" in the WRITER TABLE create table WRITER (

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

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?

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.

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

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.

<id name="StudentId" type="string" > <column name="columnId" length="30"/> <generator class="IdGenerator"/>

</id>

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.  <cache> element.  Caching the queries.  Custom Cache.

o Configuration.

o Implementation :: ExampleCustomCache.  Something about Caching.

o Performance. o About Caching.  Conclusion.

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.

In document Hibernate Notes (Page 82-87)