EzDevInfo.com

hibernate interview questions

Top hibernate frequently asked interview questions

What's the Hi/Lo algorithm?

What's the Hi/Lo algorithm?

I've found this in the NHibernate documentation (it's one method to generate unique keys, section 5.1.4.2), but I haven't found a good explanation of how it works.

I know that Nhibernate handles it, and I don't need to know the inside, but I'm just curious.


Source: (StackOverflow)

In a bidirectional JPA OneToMany/ManyToOne association, what is meant by "the inverse side of the association"?

In these examples on TopLink JPA Annotation Reference:

Example 1-59 @OneToMany - Customer Class With Generics

@Entity
public class Customer implements Serializable {
    ...
    @OneToMany(cascade=ALL, mappedBy="customer")
    public Set<Order> getOrders() { 
        return orders; 
    }
    ...
}

Example 1-60 @ManyToOne - Order Class With Generics

@Entity
public class Order implements Serializable {
    ...
    @ManyToOne
    @JoinColumn(name="CUST_ID", nullable=false)
    public Customer getCustomer() { 
        return customer; 
    }
    ...
}

It seems to me that the Customer entity is the owner of the association. However, in the explanation for the mappedBy attribute in the same document, it is written that:

if the relationship is bidirectional, then set the mappedBy element on the inverse (non-owning) side of the association to the name of the field or property that owns the relationship as Example 1-60 shows.

However, if I am not wrong, it looks like in the example, the mappedBy is actually specified on the owning side of the association, rather than the non-owning side.

So my question is basically:

  1. In a bidirectional (one-to-many/many-to-one) association, which of the entities is the owner? How can we designate the One side as the owner? How can we designate the Many side as the owner?

  2. What is meant by "the inverse side of the association"? How can we designate the One side as the inverse? How can we designate the Many side as the inverse?


Source: (StackOverflow)

Advertisements

How to install Hibernate Tools in Eclipse?

What is the proper way to install Hibernate Tools in Eclipse as a plugin? The Hibernate site doesn't really give any instructions.

Looking at the Hibernate Tools binary HibernateTools-3.2.4.Beta1-R200810311334.zip, it appears that I can just unzip this in my eclipse directory. Do I just unzip it in my eclipse directory? This seems like a hacky was to install it.


Source: (StackOverflow)

Converting Hibernate proxy to real object

During Hibernate session I am loading some objects and some of them are loaded as proxies due to lazy loading. It's all OK and I don't want to turn lazy loading off.

But later I need to send some of the objects (actually one object) to the GWT client via RPC. And it happens that this concrete object is a proxy. So I need to turn it to real object. I can't find a method like "materialize" in Hibernate.

How can I turn some of the objects from proxies to reals knowing their class and ID?

At the moment the only solution I see is to evict that object from Hibernate's cache and reload it, but it is really bad for many reasons.


Source: (StackOverflow)

How do we count rows using Hibernate?

For example, if we have a table Books, how would we count total number of book records with hibernate?

Thanks


Source: (StackOverflow)

Making a OneToOne-relation lazy

In this application we are developing, we noticed that a view was particularly slow. I profiled the view and noticed that there was one query executed by hibernate which took 10 seconds even if there only were two object in the database to fetch. All OneToMany and ManyToMany relations were lazy so that wasn't the problem. When inspecting the actual SQL being executed, I noticed that there were over 80 joins in the query.

Further inspecting the issue, I noticed that the problem was caused by the deep hierarchy of OneToOne and ManyToOne relations between entity classes. So, I thought, I'll just make them fetched lazy, that should solve the problem. But annotating either @OneToOne(fetch=FetchType.LAZY) or @ManyToOne(fetch=FetchType.LAZY) doesn't seem to work. Either I get an exception or then they are not actually replaced with a proxy object and thus being lazy.

Any ideas how I'll get this to work? Note that I do not use the persistence.xml to define relations or configuration details, everything is done in java code.


Source: (StackOverflow)

What is the proper way to re-attach detached objects in Hibernate?

I have a situation in which I need to re-attach detached objects to a hibernate session, although an object of the same identity MAY already exist in the session, which will cause errors.

Right now, I can do one of two things.

  1. getHibernateTemplate().update( obj ) This works if and only if an object doesn't already exist in the hibernate session. Exceptions are thrown stating an object with the given identifier already exists in the session when I need it later.

  2. getHibernateTemplate().merge( obj ) This works if and only if an object exists in the hibernate session. Exceptions are thrown when I need the object to be in a session later if I use this.

Given these two scenarios, how can I generically attach sessions to objects? I don't want to use exceptions to control the flow of this problem's solution, as there must be a more elegant solution...


Source: (StackOverflow)

How do synchronized static methods work in Java?

If I have a util class with static methods that will call Hibernate functions to accomplish basic data access. I am wondering if making the method synchronized is the right approach to ensure thread-safety.

I want this to prevent access of info to the same DB instance. However, I'm now sure if the following code are preventing getObjectById being called for all Classes when it is called by a particular class.

public class Utils {
     public static synchronized Object getObjectById (Class objclass, Long id) {
           // call hibernate class
         Session session = new Configuration().configure().buildSessionFactory().openSession();
         Object obj = session.load(objclass, id);
         session.close();
         return obj;
     }

     // other static methods
}

Source: (StackOverflow)

Creation timestamp and last update timestamp with Hibernate and MySQL

For a certain Hibernate entity we have a requirement to store its creation time and the last time it was updated. How would you design this?

  • What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)? Will the data types be timezone-aware?

  • What data types would you use in Java (Date, Calendar, long, ...)?

  • Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?

  • What annotations would you use for the mapping (e.g. @Temporal)?

I'm not only looking for a working solution, but for a safe and well-designed solution.


Source: (StackOverflow)

Weaknesses of Hibernate [closed]

I would like to know which are the weak points of Hibernate 3. This is not pretended to be a thread against Hibernate. I think it will be a very useful knowledge for decide if Hibernate is the best option for a project or for estimating its time.

A weakness can be:

  • A bug
  • Where JDBC or PLSQL are better
  • Performance issues
  • ...

Also, can be useful to know some solutions for that problems, better ORM or techniques, or it will be corrected in Hibernate 4.

For example, AFAIK, Hibernate will have a very bad performance updating 10000 rows comparing to JDBC in this query:

update A set state=3 where state=2

Source: (StackOverflow)

How do you do a limit query in HQL?

In Hibernate 3, is there a way to do the equivalent of the following MySQL limit in HQL?

select * from a_table order by a_table_column desc limit 0, 20;

I don't want to use setMaxResults if possible. This definitely was possible in the older version of Hibernate/HQL, but it seems to have disappeared.


Source: (StackOverflow)

The JPA hashCode() / equals() dilemma

There have been some discussions here about JPA entities and which hashCode()/equals() implementation should be used for JPA entity classes. Most (if not all) of them depend on Hibernate, but I'd like to discuss them JPA-implementation-neutrally (I am using EclipseLink, by the way).

All possible implementations are having their own advantages and disadvantages regarding:

  • hashCode()/equals() contract conformity (immutability) for List/Set operations
  • Whether identical objects (e.g. from different sessions, dynamic proxies from lazily-loaded data structures) can be detected
  • Whether entities behave correctly in detached (or non-persisted) state

As far I can see, there are three options:

  1. Do not override them; rely on Object.equals() and Object.hashCode()
    • hashCode()/equals() work
    • cannot identify identical objects, problems with dynamic proxies
    • no problems with detached entities
  2. Override them, based on the primary key
    • hashCode()/equals() are broken
    • correct identity (for all managed entities)
    • problems with detached entities
  3. Override them, based on the Business-Id (non-primary key fields; what about foreign keys?)
    • hashCode()/equals() are broken
    • correct identity (for all managed entities)
    • no problems with detached entities

My questions are:

  1. Did I miss an option and/or pro/con point?
  2. What option did you choose and why?



UPDATE 1:

By "hashCode()/equals() are broken", I mean that successive hashCode() invocations may return differing values, which is (when correctly implemented) not broken in the sense of the Object API documentation, but which causes problems when trying to retrieve a changed entity from a Map, Set or other hash-based Collection. Consequently, JPA implementations (at least EclipseLink) will not work correctly in some cases.

UPDATE 2:

Thank you for your answers -- most of them have remarkable quality.
Unfortunately, I am still unsure which approach will be the best for a real-life application, or how to determine the best approach for my application. So, I'll keep the question open and hope for some more discussions and/or opinions.


Source: (StackOverflow)

Hibernate vs JPA vs JDO - pros and cons of each? [closed]

I'm familiar with ORM as a concept, and I've even used nHibernate several years ago for a .NET project; however, I haven't kept up with the topic of ORM in Java and haven't had a chance to use any of these tools.

But, now I may have the chance to begin to use some ORM tools for one of our applications, in an attempt to move away from a series of legacy web services.

I'm having a hard time telling the difference betweeen the JPA spec, what you get with the Hibernate library itself, and what JDO has to offer.

So, I understand that this question is a bit open-ended, but I was hoping to get some opinions on:

  • What are the pros and cons of each?
  • Which would you suggest for a new project?
  • Are there certain conditions when it would make sense to use one framework vs the other?

Source: (StackOverflow)

Is buildSessionFactory() deprecated in hibernate 4?

When I updated version of Hibernate from 3.6.8.final to 4.0.0.final I got a warning about deprecated method buildSessionFactory() in this line:

private static final SessionFactory sessionFactory =
         new Configuration().configure().buildSessionFactory();

the javadoc recommends use of another method

buildSessionFactory(ServiceRegistry serviceRegistry)

but in the documentation I found deprecated variant :(

Can you help me with this little misunderstanding ?


Source: (StackOverflow)

Hibernate show real SQL [duplicate]

This question already has an answer here:

if I set

<property name="show_sql">true</property>

in my hibernate.cfg.xml configuration file in the console I can see the SQL.

But it's not real SQL... Can I see the SQL code that will be passed directly to database?

Example:

I see

select this_.code from true.employee this_ where this_.code=?

Can I see

select employee.code from employee where employee.code=12

the real SQL?


Source: (StackOverflow)