Hibernate, lesson2 – Queries

In the last post I have showed you a very basic example of usage in Hibernate. In this post I would like to show you all the different ways of executing a query while using Hibernate. The examples in this post use the same example from the last post. 1. Using the session functions The session object itself gives you methods to persist objects to the DB. For example: This code will fetch a row from the DB with primary key=111 and convert it to Contact object. Which is the equivalent to this SQL code: Another example: This code will insert a new row to the table. In other words this is the equivalent to this SQL code: Another example: This code will update a row in the table where the primary key is 111. In other words this is the equivalent to this SQL code: But as you probably noticed, the possibilities here are vary narrow. But there are other and better ways creating queries in Hibernate. 2. Using a Query object with HQL HQL is a query language designed by Hibernate It resembles SQL but has more options to it. Example: This will return a single result. That Continue reading Hibernate, lesson2 – Queries

Hibernate, lesson 1 – first encounter

Hibernate is one of the most popular java technologies there is and it seems it is not going anywhere for at least 10 years. If you are a java developer you can’t afford not to know it, at least on the surface. This post is for those of you who never used hibernate, or used it and just want to start from scratch. If hibernate seems like a tech-monster for you, you’ll come to the right place. I’ll show you how to get hibernate to work in a very short time. What do you need? DB connection Basic SQL knowledge Java knowledge + IDE Step 1 – Download Hibernate Download Hibernate Core¬† zip file form http://www.hibernate.org/6.html. Unzip it. The most impotent file is hibernate3.jar. Locate it under the root. Other important jars can be found under the lib folder Step 2 – Start a new java project with your IDE Add the hibernate3.jar to the classpath. Also add these jars: dom4j, log4j, slf4j-api,¬† slf4j-jcl, commons-logging, commons-collection, javassist, jta, antlr (most of them come with hibernate) Add also the driver jar + license to the classpath. Step 3 – Create a java bean A bean is a java class with a Continue reading Hibernate, lesson 1 – first encounter