wood burning stoves 2.0*
The moose likes Object Relational Mapping and the fly likes Hibernate - How to retrieve data from the database Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Hibernate - How to retrieve data from the database" Watch "Hibernate - How to retrieve data from the database" New topic

Hibernate - How to retrieve data from the database

Sethu Raman

Joined: Oct 18, 2007
Posts: 14
Hi all

Am just started learning hibernate. i tried all insert, update and delete except select. Some body help me in retrieve data from the database table. There are methods like save,update,delete in session object, whatsover for select?

Thanks in advance
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336


Welcome to JavaRanch!

Could you please update your display name so it complies with our naming policy. You can do this here.

[ October 23, 2007: Message edited by: Paul Sturrock ]

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

If you want to load an entity by its id, use the get or load methods of the Session class. If you want to find a list of objects based on some search criteria, you can do that again from the Session class with a Query, a set of Criteria or a native SQLQuery.

Does this make sense?

(And thank you for updating your display name)
[ October 24, 2007: Message edited by: Paul Sturrock ]
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper

Joined: Aug 26, 2006
Posts: 4968

Here's a little class I call my CrudRunner. It demonstrates how to use Hibernate to do the basic Create Retrieve Update and Delete (destroy?) methods.

Here's the very simple table it works with:

Here is the entity that uses JPA annotations to map to the table:

And here's the CrudRunner with all of the basic CRUD operations:

The retrieve method starts off with some redundant and repetitive code that basically initialized the Hibernate framework and gets our program ready to interact with the database. Again, you will notice that a Hibernate session is obtainined from the SessionFactory. This session then begins a transaction for interacting with the database. We�ll eventually look at factoring this repetitive code out into a helper method or something, but for now, we�ll leave it in, just for the sake of simplicity.

/* your standard Hibernate connection code */
AnnotationConfiguration config =
new AnnotationConfiguration();
SessionFactory factory;
factory = config.configure().buildSessionFactory();
Session session = factory.getCurrentSession();

Querying the Database
After the Hibernate session is obtained, we declare an object of type java.util.List called allUsers. Basically, when we do a standard, non-unique query of the database, we can expect a resultset to be returned to us in the form of a java.util.List. The allUsers list will hold the results of our query.

java.util.List allUsers;

From there, and this is a pretty important point, the createQuery method is invoked on the Hibernate session, with the argument �from User� being passed in as an argument.

Query queryResult=session.createQuery("from User");
allUsers = queryResult.list();

Say Hello to Hibernate Query Language (HQL)
As you have probably guessed, the String statement �from User�, which is passed into the Hibernate session�s createQuery method, is a special type of SQL statement. The �from User� String can be thought of as the equivalent to issuing an SQL query of SELECT * FROM USER.

Query queryResult=session.createQuery("from User");
allUsers = queryResult.list();

However, don�t be fooled by what may appear on the surface to be great similarity between standard SQL and the query language used by Hibernate. The Hibernate Query Language, HQL, is actually an object-oriented data query language, meaning that HQL understands object oriented concepts such as association, inheritance, aggregation and polymorphism. The power of HQL will become increasingly evident when we move away from simple SELECT * queries.
Execution of the createQuery(�from User�) method returns a Hibernate object called a Query, which when populated, contains all of the data returned from executing the HQL statement, all of which is stored as a collection of JavaBeans. These JavaBeans can be easily accessed by asking the Query object to provide its encapsulated data as either a java.util.Iterator or a java.util.List. The Query�s methods to do so are accordingly named iterate() and list(). In our example, we obtain the results of the Query as a list.

allUsers = queryResult.list();

Looping through the List
So, after executing an HQL query, we get ourselves a Query object, and this Query object can spill its contents out in the form of a java.util.List object. I guess the big question is: what does this java.util.List contain?
Well, it contains instances of the User class we created to represent the data in the user table of the database. Looping through the list, and extracting the User class out of the List, with a combination of the List�s get(int) method and a handy cast, gives us access to our very own User object!

User user = (User) allUsers.get(i);

Once you have the User object extracted from the List, and cast into the appropriate type, it is completely up to the you with regards to what you want to do with it. In this example, we simply print out the name of the user instance to the console, which, given the fact that I�m looping through every instance in the List, will provide me the names of all of the entries in the user table of the database. Here�s the for loop that does it:

for (int i = 0; i < allUsers.size(); i++) {
User user = (User) allUsers.get(i);

And that�s pretty much it! To retrieve data from the database, you simply leverage the Hibernate session�s createQuery method, pass in some HQL, convert the guts of the returned Query object into an easy to use List, and then loop through the collection of your POJOs contained in the List. It�s just that easy!

-Cameron McKenzie
[ October 24, 2007: Message edited by: Cameron McKenzie ]
Anthony Bailey

Joined: Sep 11, 2008
Posts: 9
What does the hibernate config file look like? I am getting the following error when using your retrieve example. I have not used any other methods yet.

Here is mine.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
<property name="connection.url">jdbc:postgresql:CORMDBASE</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.username">postgres</property>
<property name="connection.password">admin</property>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->

<!-- SQL Dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>

<!-- Bean Mapping -->
<mapping class="org.christianassistant.persistance.MembersEntity"/>

I agree. Here's the link: http://aspose.com/file-tools
subject: Hibernate - How to retrieve data from the database