Grails with Hibernate (Part 1)

Welcome Guys, This is the series of the blog posts on Hibernate with grails. I have divided it into parts.

On Part 1 you will see how to map a simple POJO class with the Relational database using hibernate.

Step 1) Create a new project by grails create-app myApp or use existing project.
Step 2) Create hibernate.cfg.xml file inside the grails/config/hibernate directory and add these line of code on it.

<!DOCTYPE hibernate-configuration SYSTEM
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
      
   </session-factory>
</hibernate-configuration>

Step 3) Now create a new Class in src/groovy or src/java directory with a package name. For example I have created a groovy class name as UserDTO.groovy.

package org.neeraj

public class UserDTO {
Integer id   
String username
   
} 

Step 4) Now add @Entity annotation on the class and @Id on the id property.

 
package org.neeraj

@Entity
@Table(name="USER")
public class UserDTO {
@Id
Integer id   
String username   
} 

Step 5) Add

<mapping class="org.neeraj.UserDTO"/>

in the hibernate.cfg.xml file.

<hibernate-configuration>
    <session-factory>
      <mapping class="org.neeraj.UserDTO"/>      
   </session-factory>
</hibernate-configuration>

Step 5) And last step run the application by “grails runApp” command. Open the url “http://localhost:8080/myApp/dbconsole” browser. You can see a table in the database with name “USER”.

In the next part you will see the how to save data to the database and retrieve data from the database. So please stay tuned.