Only Institute
to provide recording daily after class to students. you can practice whole day under faculty guidance. where test and mockup tests are taken regularly. provides all mobile nos of old students on website.

Hibernate Interview Question Answer Part 2

Bi-DireCtional One to Many Relation- EXAMPLE
PROCESS_TYPE_LOV (PROCESS_TYPE_ID number, PROCESS_TYPE_NAME varchar) - TABLE
PROCESS (PROCESS_ID number,PROCESS_NAME varchar,PROCESS_TYPE_ID number)- TABLE


public class ProcessTypeBean {

private Long processTypeId;
private String processTypeName;
private List processes = null;

/**
* @return Returns the processes.
*/
public List getProcesses() {
return processes;
}
/**
* @param processes The processes to set.
*/
public void setProcesses(List processes) {
this.processes = processes;
}

/**
* @return Returns the processTypeId.
*/
public Long getProcessTypeId() {
return processTypeId;
}
/**
* @param processTypeId The processTypeId to set.
*/
public void setProcessTypeId(Long processTypeId) {
this.processTypeId = processTypeId;
}
/**
* @return Returns the processTypeName.
*/
public String getProcessTypeName() {
return processTypeName;
}
/**
* @param processTypeName The processTypeName to set.
*/
public void setProcessTypeName(String processTypeName) {
this.processTypeName = processTypeName;
}
}

public class ProcessBean {

private Long processId;
private String processName = "";
private ProcessTypeBean processType;

public Long getProcessId() {
return processId;
}
/**
* @param processId The processId to set.
*/
public void setProcessId(Long processId) {
this.processId = processId;
}
/**
* @return Returns the processName.
*/
public String getProcessName() {
return processName;
}
/**
* @param processName The processName to set.
*/
public void setProcessName(String processName) {
this.processName = processName;
}
/**
* @return Returns the processType.
*/
public ProcessTypeBean getProcessType() {
return processType;
}
/**
* @param processType The processType to set.
*/
public void setProcessType(ProcessTypeBean processType) {
this.processType = processType;
}
}



< class name="com.bean.ProcessBean"
table="PROCESS" >
< id name="processId" type="long" column="PROCESS_ID" />
length="50" />




< class name="com.bean.ProcessTypeBean"
table="PROCESS_TYPE_LOV" >
< id name="processTypeId" type="long" column="PROCESS_TYPE_ID" />
< property name="processTypeName" column="PROCESS_TYPE_NAME"
type="string" length="50" />

< bag name="processes" inverse="true" cascade="delete" lazy="false">

class="com.bean.ProcessBean" />



WRITER (ID INT,NAME VARCHAR) - TABLE
STORY (ID INT,INFO VARCHAR,PARENT_ID INT) - TABLE
One writer can have multiple stories..

-------------------------------------------------------------
Mapping File...


< ?xml version="1.0" encoding="UTF-8"? >
< !DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

< hibernate-mapping >
< class name="Writer" table="WRITER" >
< id name="id" unsaved-value="0" >
< generator class="increment" />
< /id >

< list name="stories" cascade="all" >
< key column="parent_id" />
< one-to-many class="Story" />

< property name="name" type="string" />

< class name="Story"
table="story" >
< id name="id" unsaved-value="0" >
< generator class="increment" />

< property name="info" />



public class Writer {
private int id;
private String name;
private List stories;

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 void setStories(List l) {
stories = l;
}

public List getStories() {
return stories;
}
}



public class Story {
private int id;
private String info;

public Story(){
}

public Story(String info) {
this.info = info;
}

public void setId(int i) {
id = i;
}

public int getId() {
return id;
}

public void setInfo(String n) {
info = n;
}

public String getInfo() {
return info;
}
}


Save Example ..

Writer wr = new Writer();
wr.setName("Das");

ArrayList list = new ArrayList();
list.add(new Story("Story Name 1"));
list.add(new Story("Story Name 2"));
wr.setStories(list);

Transaction transaction = null;

try {
transaction = session.beginTransaction();
session.save(sp);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
throw e;
}
} finally {
session.close();
}



Best Example..for Many to Many in Hibernate ..

EVENTS ( uid int, name VARCHAR) Table
SPEAKERS ( uid int, firstName VARCHAR) Table
EVENT_SPEAKERS (elt int, event_id int, speaker_id int) Table


import java.util.Set;
import java.util.HashSet;

public class Speaker{

private Long id;
private String firstName;
private Set events;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public Set getEvents() {
return this.events;
}

public void setEvents(Set events) {
this.events = events;
}

private void addEvent(Event event) {
if (events == null) {
events = new HashSet();
}
events.add(event);
}
}





import java.util.Date;
import java.util.Set;

public class Event{

private Long id;
private String name;
private Set speakers;

public void setId(Long id) {
this.id = id;
}

public Long getId() {
return id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void setSpeakers(Set speakers) {
this.speakers = speakers;
}

public Set getSpeakers() {
return speakers;
}
}


Event.hbm.xml


< ?xml version="1.0"? >
< !DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

< hibernate-mapping >
< class name="Event" table="events" >
< id name="id" column="uid" type="long" unsaved-value="null" >
< generator class="increment" />

< property name="name" type="string" length="100" />
< set name="speakers" table="event_speakers" cascade="all" >
< key column="event_id" />
< many-to-many class="Speaker" />


Speaker.hbm.xml

< ?xml version="1.0"? >
< !DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

< hibernate-mapping >
< class name="Speaker" table="speakers" >
< id name="id" column="uid" type="long" >
< generator class="increment" />

< property name="firstName" type="string" length="20" />
< set name="events" table="event_speakers" cascade="all" >
< key column="speaker_id" />
< many-to-many class="Event" />


Save and Fetch Example

Event event = new Event();
event.setName("Inverse test");
event.setSpeakers(new HashSet());
event.getSpeakers().add(new Speaker("Ram", event));
event.getSpeakers().add(new SpeakerManyToMany("Syam", event));
event.getSpeakers().add(new SpeakerManyToMany("Jadu", event));
session.save(event); /// Save All the Data

event = (Event) session.load(Event.class, event.getId());
Set speakers = event.getSpeakers();

for (Iterator i = speakers.iterator(); i.hasNext();) {
Speaker speaker = (Speaker) i.next();
System.out.println(speaker.getFirstName());
System.out.println(speaker.getId());
}


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



session.close() don't call session.flush() before closing the session.

This is the session.close() code in hibernate.jar

public Connection close() throws HibernateException {
log.trace( "closing session" );
if ( isClosed() ) {
throw new SessionException( "Session was already closed" );
}

if ( factory.getStatistics().isStatisticsEnabled() ) {
factory.getStatisticsImplementor().closeSession();
}

try {
try {
if ( childSessionsByEntityMode != null ) {
Iterator childSessions = childSessionsByEntityMode.values().iterator();
while ( childSessions.hasNext() ) {
final SessionImpl child = ( SessionImpl ) childSessions.next();
child.close();
}
}
}
catch( Throwable t ) {
// just ignore
}

if ( rootSession == null ) {
return jdbcContext.getConnectionManager().close();
}
else {
return null;
}
}
finally {
setClosed();
cleanup();
}
}


By default Hibernate creates a proxy for each of the class you map in mapping file. This class contain the code to invoke JDBC. This class is created by hibernate using CGLIB.

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. Very nice in simple cases with no object hierarchy. Typecasting and instanceof work perfectly on the proxy in this case since it is a direct subclass.
SessionFactory (org.hibernate.SessionFactory) A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level.

Session (org.hibernate.Session)
A single-threaded, short-lived object representing a conversation between the application and the persistent store. 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. Persistent objects and collections

Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer (e.g. directly as data transfer objects to and from presentation). Transient and detached objects and collections

Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session. Transaction (org.hibernate.Transaction)

(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction, is never optional!

Architecture
Hibernate 3.0.2 9
ConnectionProvider (org.hibernate.connection.ConnectionProvider)
(Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer. TransactionFactory (org.hibernate.TransactionFactory) (Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/ implemented by the developer. Extension Interfaces
Hibernate offers many optional extension interfaces you can implement to customize the behavior of your persistence layer. See the API documentation for details.



SessionFactory sf = new Configuration()
.addFile("Item.hbm.xml")
.addFile("Bid.hbm.xml")
.buildSessionFactory();


Equal and Not Equal criteria query- Example


< class name="com.bean.Organization" table="ORGANIZATION" >

< id name="orgId" column="ORG_ID" type="long" >

< property name="organizationName" column="ORGANISATION_NAME" type="string" length="500" />

< property name="town" column="TOWN" type="string" length="200" />


List of organisation where town equals to pune.

List organizationList = session.createCriteria(Organization.class).add(Restrictions.eq("town","pune")).list();

List of organisation where town not equals pune.

List organizationList = session.createCriteria(Organization.class).add(Restrictions.ne("town","pune")).list();
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.

Each interaction with the persistent store occurs in a new Session. However, the same persistent instances are reused for each interaction with the database. The application manipulates the state of detached instances originally loaded in another Session and then "reassociates" them using Session.update() or Session.saveOrUpdate().


// foo is an instance loaded by a previous Session
foo.setProperty("bar");
session = factory.openSession();
session.saveOrUpdate(foo);
session.flush();
session.connection().commit();
session.close();


You may also call lock() instead of update() and use LockMode.READ (performing a version check, bypassing all caches) if you are sure that the object has not been modified.
Filter in Hibernate ------
USER ( ID INT, USERNAME VARCHAR, ACTIVATED BOOLEAN) - TABLE


public class User
{
private int id;
private String username;
private boolean activated;

public boolean isActivated()
{
return activated;
}
public void setActivated(boolean activated)
{
this.activated = activated;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}





< ?xml version='1.0' encoding='utf-8'? >
< !DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

< hibernate-mapping >
< class name="User" >
< id name="id" type="int" >
< generator class="native" />


< property name="username" type="string" length="32" />
< property name="activated" type="boolean" />
< filter name="activatedFilter" condition=":activatedParam = activated" />

< filter-def name="activatedFilter" >
< filter-param name="activatedParam" type="boolean" />


Save and Fetch using filter example


User user1 = new User();
user1.setUsername("name1");
user1.setActivated(false);

session.save(user1);

User user2 = new User();
user2.setUsername("name2");
user2.setActivated(true);

session.save(user2);

User user3 = new User();
user3.setUsername("name3");
user3.setActivated(true);

session.save(user3);

User user4 = new User();
user4.setUsername("name4");
user4.setActivated(false);

session.save(user4);

//All the four user saved to Data Base User Table.

//Now Fetch the User using Filter..

Filter filter = session.enableFilter("activatedFilter");
filter.setParameter("activatedParam",new Boolean(true));
Query query = session.createQuery("from User");
Iterator results = query.iterate();
while (results.hasNext())
{
User user = (User) results.next();
System.out.print(user.getUsername() + " is ");
}


Guess the Result :
name2
name3
Because Filer is filtering ( only true value) data before query execute.



Double max = (Double) sess.createSQLQuery("select max(cat.weight) as maxWeight from cats cat")
.addScalar("maxWeight", Hibernate.DOUBLE);
.uniqueResult();


addScalar() method confirm that maxWeight is always double type.
This way you don't need to check for it is double or not.
User Session.connection() method to get JDBC Connection.
transient
The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value).

persistent
The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context, Hibernate guarantees that persistent identity is equivalent to Java identity (in-memory location of the object).

detached
The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corrsponding row in the database. For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity.
getCurrentSession() :
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 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.

To enable this strategy in your Hibernate configuration:
set hibernate.transaction.manager_lookup_class to a lookup strategy for your JEE container
set hibernate.transaction.factory_class to org.hibernate.transaction.JTATransactionFactory


Only the Session that you obtained with sf.getCurrentSession() is flushed and closed automatically.

Example :


try {
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");

tx.begin();

// Do some work
sf.getCurrentSession().createQuery(...);
sf.getCurrentSession().persist(...);

tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}

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 :
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");

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
}