Add to Google Reader or Homepage

Hibernate. How to Count Records

Easy as ABC, you may answer, and you will be absolutely right! It is not rocket science, yet some code looks quite complicated to complete this simplest task.

Today I watched a new episode of the Bones tv show and browsed some open source code. I found the following method:

public int getCount(Class clazz) {
	Integer rowCount  = new Integer(0);
	Criteria criteria = getCurrentSession().createCriteria(SomeEntity.class);

	List results = criteria.list();

        if(results != null && !results.isEmpty()){
        rowCount = results.size();
	} else {
		rowCount = new Integer(0);
	return rowCount;

Okay, 11 “readable” lines of code so far. Read the rest of this entry »

Hibernate Many-to-Many Mapping (JPA)

A few months ago, I wrote an article how to map the one-to-one bi-directional relations between two entities and now is the time for a simple example how to map many-to-many relation. You can find what Many-to-Many relation means in Wikipedia, and the following article only shows how it looks like in Db and how it can be mapped in Hibernate. Ready? Read the rest of this entry »

Hibernate One-to-One Bi-Directional Mapping

In the following article, I would like to show an approach how to map one-to-one bi-directionall two entities in Hibernate.
First of all, let’s take a look at the relation between two tables in a database:


As you can see, there is the one-to-one relation between user and user_profile tables and the user_profile table has a primary key that in fact, it is a foreign key to the id property of the user table. In other words, there is a simple use-case: one user record can have only one related user_profile record.

What the mapping looks like?

There are two classes. Read the rest of this entry »