HelloWorld with JPA, Hibernate and MySql

An earlier entry shows how to write a simple java application using Java Persistence API (JPA), Toplink and MySql. Now let's try Hibernate Entity Manager.

Entity class and main class remain the same. persistence.xml is different since we will need to specify Hibernate-specific properties:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="hello-world" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.foo.Greeting</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
Compile classpath is different, since we need to use Hibernate jars. Strictly speaking, javac only needs JPA API classes in the classpath. But just to be consistent with runtime, it does't hurt to include all 17 Hibernate jar files.

To save some typing, I decided to use * wildcard in classpath, a new feature in JDK 6 (see my previous post):
C:\ws\nb\scrap\src\com\foo> javac
-d C:\ws\nb\scrap\build\classes
-classpath "C:\tools\hibernate-em\*"
Greeting.java HelloWorld.java
Note that the "" around the classpath element is needed. Otherwise, you will get javac error: invalid flag.

You also need to have a log4j.properties file in classpath. I have it in build/classes/log4j.properties:
log4j.rootCategory=WARN, dest1
log4j.appender.dest1=org.apache.log4j.ConsoleAppender
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
Unlike TopLink, Hibernate doesn't use -javaagent: option. First start MySql on localhost, then
C:\ws\nb\scrap\build\classes> java -cp
C:\tools\hibernate-em\*;C:\tools\mysql-java\mysql-connector-java-3.1.13-bin.jar;.
com.foo.HelloWorld
createDDL.jdbcO-:-Ofalse
dropDDL.jdbcO-:-Ofalse
log4j.propertiesO-:-Ofalse
META-INF/persistence.xmlO-:-Ofalse
No configuration found. Configuring ehcache from ehcache-failsafe.xml found in
the classpath: jar:file:/C:/tools/hibernate-em/ehcache-1.2.jar!/ehcache-failsafe.xml
Query returned: Greeting id=1, message=hello world, language=en
The 17 jars used by Hibernate Entity Manager are:
antlr-2.7.6.jar, commons-collections-2.1.1.jar, hibernate-annotations.jar, jta.jar, asm-attrs.jar, commons-logging-1.0.4.jar, hibernate-entitymanager.jar, log4j-1.2.11.jar, asm.jar, dom4j-1.6.1.jar, hibernate3.jar, c3p0-0.9.0.jar, ehcache-1.2.jar, javassist.jar, cglib-2.1.3.jar, ejb3-persistence.jar, jboss-archive-browsing.jar


This blog talks about doing all these in NetBeans 5.5 beta 2, very helpful.

Followers

Pageviews Last 7 Days