• +91 9971497814
  • info@interviewmaterial.com

Computer Interview Questions Answers

Hibernate Interview Questions Answers

Question - 21 : - How can I execute arbitrary SQL using Hibernate?

Answer - 21 : - 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 <sql-insert>, <sql-update>, <sql-delete> and <loader> 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.

Question - 22 : - What is a SessionFactory? Is it a thread-safe object?

Answer - 22 : - 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();

Question - 23 : -  What are the benefits of detached objects?

Answer - 23 : - 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.

Question - 24 : - How can I create an association to an entity without fetching that entity from the database (if I know the identifier)?

Answer - 24 : - If the entity is proxyable (lazy="true"), simply use load(). The following code does not result in any SELECT statement: Item itemProxy = (Item) session.load(Item.class, itemId);Bid bid = new Bid(user, amount, itemProxy);session.save(bid);

Question - 25 : - How can I insert XML data into Oracle using the xmltype() function?

Answer - 25 : - Specify custom SQL INSERT (and UPDATE) statements using <sql-insert> and <sql-update> 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.  

Question - 26 : - Query Criteria Equal

Answer - 26 : - import java.util.*; import org.hibernate.*; import org.hibernate.criterion.*; public class SimpleRetrieveTest { public static void main(String[] args) { HibernateUtil.setup("create table EVENTS ( uid int, name VARCHAR, start_Date date, duration int, location_id int);"); HibernateUtil.setup("create table locations ( uid int, name VARCHAR, address VARCHAR);"); // hibernate code start Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); Location location = new Location(); location.setName("USA"); location.setAddress("Address"); session.save(location); Event e= new Event(); e.setId(11111L); e.setName("testSave"); e.setStartDate(new Date()); e.setLocation(location); session.save(e); Criteria crit = session.createCriteria(Event.class); crit.add( Expression.eq( "name", "testSave" ) ); crit.setMaxResults(1); List results = crit.list(); System.out.println(results.size()); tx.commit(); HibernateUtil.closeSession(); HibernateUtil.sessionFactory.close(); // hibernate code end } }   ///////////////////////////////////////////////////////////////////////// <?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="Location" table="locations" lazy="true"> <id name="id" column="uid" type="long"> <generator class="native"/> </id> <property name="name" type="string"/> <property name="address" type="string"/> </class> </hibernate-mapping>     ///////////////////////////////////////////////////////////////////////// public class Location { private Long id; private String name; private String address; publi

Question - 27 : - Does Hibernate implement its functionality using a minimal number of database queries?

Answer - 27 : - Hibernate can make certain optimizations all the time: Caching objects. The session is a transaction-level cache of persistent objects. You may also enable a JVM-level/cluster cache to memory and/or local disk. Executing SQL statements later, when needed. The session never issues an INSERT or UPDATE until it is actually needed. So if an exception occurs and you need to abort the transaction, some statements will never actually be issued. Furthermore, this keeps lock times in the database as short as possible (from the late UPDATE to the transaction end). Never updating unmodified objects. It is very common in hand-coded JDBC to see the persistent state of an object updated, just in case it changed.....for example, the user pressed the save button but may not have edited any fields. Hibernate always knows if an object's state actually changed, as long as you are inside the same (possibly very long) unit of work. Efficient Collection Handling. Likewise, Hibernate only ever inserts/updates/deletes collection rows that actually changed. Rolling two updates into one. As a corollary to (1) and (3), Hibernate can roll two seemingly unrelated updates of the same object into one UPDATE statement. Updating only the modified columns. Hibernate knows exactly which columns need updating and, if you choose, will update only those columns. Outer join fetching. Hibernate implements a very efficient outer-join fetching algorithm! In addition, you can use subselect and batch pre-fetch optimizations. Lazy collection initialization. Lazy object initialization. Hibernate can use runtime-generated proxies (CGLIB) or interception injected through bytecode instrumentation at build-time. A few more (optional) features of Hibernate that your handcoded JDBC may or may not currently benefit from second-level caching of arbitrary query results, from HQL, Criteria, and even native SQL queries efficient PreparedStatement caching (Hibernate always uses PreparedStatement for calls to the database) JDBC 2 style batch updates Pluggable connection pooling Hopefully you will agree that Hibernate approaches the parsimony of the best hand-coded JDBC object persistence. As a subscript I would add that I have rarely seen JDBC code that approaches the efficiency of the "best possible" code. By co

Question - 28 : - How would you reatach detached objects to a session when the same object has already been loaded into the session?

Answer - 28 : - You can use the session.merge() method call.

Question - 29 : - I have a one-to-one association between two classes. Ensuring that associated objects have matching identifiers is bugprone. Is there a better way?

Answer - 29 : - <generator class="foreign">     <param name="property">parent</param></generator>

Question - 30 : - Middlegen 2.1 Released!

Answer - 30 : - Overview of changes/fixes: Hibernate plugin - various fixes and patches. Torque plugin (new) - generate Torque config files. XMI plugin (new) - generate some XMI diagrams from the generated code. Adapter plugin (new) - making it easier to switch persistence layer for generated Struts/JSP code. Many core/plugin bugs fixed.

Computer Contributors

krishan
Rajeev Katiyar
Yes Baroda

Share your email for latest updates

Name:
Email:

Our partners