Hibernate tutorial with HSQLDB
This tutorial is basically an extension to the "simple" Java and JDBC tutorials. Hibernate is an ORM (Object to Relational Mapping) tool.
Step 1: First step is to bring in the relevant Hibernate framework jar files like hibernate-xxx.jar, hibernate-annotations-xxxx.jar, and other dependent jar files that are transitively brought in from hibernate framework's pom.xml file. Here is the pom.xml file for simple Java project extended for hibernate.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mytutorial</groupId> <artifactId>simple</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>simple</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- jar that contains the HSQLDB driver class --> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.2.8</version> </dependency> <!-- GA means General Availability --> <!-- Hibernate framework JARS--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.2.6.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.3.1.GA</version> </dependency> </dependencies> </project>Now, if you select the "simple" project and then right-mouse-click and select "Maven --> Update Dependencies".
Step 2: Hibernate uses the hibernate.cfg.xml file to configure the session factory with the database connectivity details and define your domain classes that map to to the relational database tables. This file needs to be defined in the src/main/resources folder and be in the classpath.
Create a new folder named "resources" under the "src/main" folder and then right-mouse-click on "resources" folder and then select "Build Path --> Use as Source Folder".
The contents of the hibernate.cfg.xml will include configuring the session factory to connect to the HSQLDB that we set up in the "SQL tutorial with HSQDB" tutorial.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="connection.url">jdbc:hsqldb:hsql://localhost/mytestdb</property> <property name="connection.username">sa</property> <property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.HSQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout useful for debugging if set to true--> <property name="show_sql">false</property> <property name="hbm2ddl.auto">validate</property> <mapping class="com.mytutorial.domain.Course"/> </session-factory> </hibernate-configuration>
Step 3: The next step is to define the HibernateUtil class that bootstraps the hibernate by loading the SessionFactory via the hibernate.cfg.xml.
import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml file return new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }Step 4: Next step is to define the domain Course class that maps to the "Course" database table that was created in the "SQL with HSQLDB" tutorial. Annotations are used for the object to relational mapping
package com.mytutorial.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="Course") public class Course { @Id @GeneratedValue @Column(name="course_id") private Integer id; @Column(name="name") private String name; @Column(name="course") private String course; public Course() {} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCourse() { return course; } public void setCourse(String course) { this.course = course; } }Step 5: Define the data access layer interface and the implementation class. The CourseDao is the interface and CourseDaoImpl is the implementation class that retrieves data from the database.
Define the interface.
package com.mytutorial.dao; public interface CourseDao { abstract void readAllCourses(); }
Define the implementation class.
package com.mytutorial.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.mytutorial.HibernateUtil; import com.mytutorial.domain.Course; public class CourseDaoImpl implements CourseDao { public void readAllCourses() { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); Query q = session.createQuery("from Course"); @SuppressWarnings("unchecked") List<Course> courses = q.list(); for (Course course : courses) { System.out.println(course.getName() + " - " + course.getCourse()); } } }
Step 6: This step is to define a class with a main method that makes use of the CourseDao.
package com.mytutorial; import com.mytutorial.dao.CourseDaoImpl; import com.mytutorial.dao.CourseDao; public class HibernateTutorial { public static void main(String[] args) { CourseDao cDao = new CourseDaoImpl(); cDao.readAllCourses(); } }You should now have the required Java files defined.
Step 7: Before you can run the HibernateTutorial.java, you need to make sure that the HSQL database is running with the Course database as demonstrated in the "SQL tutorial with HSQLDB".
c:\Tools\hsqldb-2.2.9\hsqldb>java -cp ./lib/hsqldb.jar org.hsqldb.server.Server
[Server@79616c7]: [Thread[main,5,main]]: checkRunning(false) entered [Server@79616c7]: [Thread[main,5,main]]: checkRunning(false) exited [Server@79616c7]: Startup sequence initiated from main() method [Server@79616c7]: Loaded properties from [C:\Tools\hsqldb-2.2.9\hsqldb\server.properties] [Server@79616c7]: Initiating startup sequence... [Server@79616c7]: Server socket opened successfully in 198 ms. [Server@79616c7]: Database [index=0, id=0, db=file:mydatabases/tutorialdb, alias=mytestdb] opened sucessfully in 1073 ms . [Server@79616c7]: Startup sequence completed in 1277 ms. [Server@79616c7]: 2012-10-09 11:35:07.347 HSQLDB server 2.2.9 is online on port 9001 [Server@79616c7]: To close normally, connect and execute SHUTDOWN SQL [Server@79616c7]: From command line, use [Ctrl]+[C] to abort abruptly
Step 8: The final step is to right-mouse-click on HibernateTutorial.java and then select "Run As --> Java Application".
You should get an output like:
Sam - Java peter - J2EE paul - JSF jonathan - Hibernate james - Spring Lewis - JDBCYou should also see, hibernate logs as shown below
INFO: configuring from resource: /hibernate.cfg.xml ... INFO: autocommit mode: false 09/10/2012 11:37:30 AM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: using driver: org.hsqldb.jdbcDriver at URL: jdbc:hsqldb:hsql://localhost/mytestdb 09/10/2012 11:37:30 AM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: connection properties: {user=sa, password=****} .... INFO: Using dialect: org.hibernate.dialect.HSQLDialect 09/10/2012 11:37:31 AM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory INFO: Using default transaction strategy (direct JDBC transactions) .... INFO: fetching database metadata 09/10/2012 11:37:31 AM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: table found: PUBLIC.PUBLIC.COURSE 09/10/2012 11:37:31 AM org.hibernate.tool.hbm2ddl.TableMetadata <init> INFO: columns: [course, name, course_id]
In the Spring 3.0 tutorial, I will extend this tutorial to show how we can use Spring to inject CourseDao into HibernateTutorial.
Labels: Hibernate Tutorial
6 Comments:
Does not work, maven update complains that hibernate 3.2.6.ga does not exist
Pck a version that is available at the Maven 2 repository. http://download.java.net/maven/2
Try the repository http://search.maven.org/ for the relevant version number. In your settings.xml file you can configure additionalmrepositories.
Try 3.2.3.GA.
Thanks for your posting.It was very easy to understand.
Can you post some material that throws some light on drawback of hibernate as compared to JPA. Also how can we achieve loose coupling without using spring.
Thanks in advance
great for helping people learn hibernate quickly. love tutorials with snippets code
Post a Comment
Subscribe to Post Comments [Atom]
<< Home