This post might seem out of place but it is part of my life after all ^_^
INTRODUCTION
I
followed the Complete Hibernate 3.0 Tutorial at the roseindia site http://www.roseindia.net/hibernate/index.shtml. You can visit the site at roseindia.net to
get a more detailed explanation of the Hibernate concepts.
The
tutorial at roseindia.net used Eclipse while the IDE I’m using is NetBeans. Also, this exercise is done on Windows XP.
This
exercise aims to set up the tutorial in NetBeans and impart some of the
difficulties I came across with while setting up Hibernate.
REQUIREMENTS
Download
the following files:
· Hibernate
· MySQL
· MySQL Connector/J
For
this exercise, I used the following versions
· Hibernate 3.2.1
· MySQL 5.0.27
I got my MySQL from XAMPP and running the MySQL service
only. I’m too lazy to set up MySQL from
scratch. For XAMPP, I used the 1.5.5
version.
· Mysql-connector-java-3.1.14
For some strange reason, the mysql-connector-java-5.0.4
doesn’t work with MySQL 5.0.27. I’ve
been around it for days trying to debug the problem but it didn’t work. I searched through Google and I came across
two forums having the same problem as I but there were no solutions posted
there. I’m not sure if the MySQL
community has addressed this issue yet. It seems they haven’t still. While waiting for the fix, I used the older version of the connector
instead, which is the 3.1.14.
In case you’re wondering what error came out when I
used the version 5 of the connector, I posted it below. You might have encountered the same problem.
Exception in thread "main"
org.hibernate.exception.GenericJDBCException: Cannot open connection
at
org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
at
org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at
org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:94)
at
org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:87)
at
org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:218)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2174)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2610)
at
org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:52)
at
org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:232)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
at
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at
org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at FirstExample.main(FirstExample.java:53)
Caused by: java.sql.SQLException: Unknown initial
character set index ‘48′ received from server. Initial client character set can
be forced via the ‘characterEncoding’ property.
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
at
com.mysql.jdbc.Connection.configureClientCharacterSet(Connection.java:2345)
at
com.mysql.jdbc.Connection.initializePropsFromServer(Connection.java:3913)
at
com.mysql.jdbc.Connection.createNewIO(Connection.java:2683)
at
com.mysql.jdbc.Connection.<init>(Connection.java:1531)
at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at
java.sql.DriverManager.getConnection(DriverManager.java:525)
at
java.sql.DriverManager.getConnection(DriverManager.java:140)
at
org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at
org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
… 14
more
SETUP
1. Add the JAR files
to your library at NetBeans. At the Projects window, right-click Libraries. Choose Add
JAR/Folder. Add the following:
o For hibernate:
§ hibernate3.jar
§ lib/antlr-2.7.6.jar
§ lib/asm-attrs.jar
§ lib/asm.jar
§ lib/c3p0-0.9.0.jar
§ lib/cglib-2.1.3.jar
§ lib/commons-collections-2.1.1.jar
§ lib/commons-logging-1.0.4.jar
§ lib/concurrent-1.3.2.jar
§ lib/dom4j-1.6.1.jar
§ lib/ehcache-1.2.3.jar
§ lib/log4j-1.2.11.jar
o mysql-connector-java-3.1.14-bin.jar
2. Run the MySQL
service.
3. At the MySQL
server
> CREATE DATABASE hibernatetutorial
> USE hibernatetutorial;
> CREATE TABLE contact (
id INT
NOT NULL,
firstName
VARCHAR(50),
lastName
VARCHAR(50),
email VARCHAR(100),
PRIMARY
KEY(id)
) Type=MyISAM;
4. To test the MySQL
connection:
o At the Runtime window, expand the Database node. Right-click the Drivers node and select New
Driver. Click Add on the New JDBC Driver pop-up window and select the mysql-connector-java-3.1.14-bin.jar
then click OK. Right-click MySQL
(Connector/J driver) under the Drivers node then select Connect Using… Replace the
following variables with the appropriate values:
jdbc:mysql://<HOST>:<PORT>/<DB>
e.g. jdbc:mysql://<localhost>:<3306>/<hibernateturial>
THE
APPLICATION
Create
the following XML files.
hibernate.cfg.xml
<?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>
<property
name="connection.url">jdbc:mysql://localhost/hibernatetutorial?useOldUTF8Behavior=true</property>
<property
name="connection.username">root</property>
<property
name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property
name="connection.password"></property>
<property
name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!– thread is the short name for
org.hibernate.context.ThreadLocalSessionContext
and let Hibernate bind the session
automatically to the thread
–>
<property
name="current_session_context_class">thread</property>
<!– this will show us all sql
statements –>
<property
name="hibernate.show_sql">true</property>
<!– mapping files –>
<mapping
resource="contact.hbm.xml" />
</session-factory>
</hibernate-configuration>
contact.hbm.xml
<?xml
version="1.0"?>
<!DOCTYPE
hibernate-mapping PUBLIC
"-//Hibernate/Hibernate
Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Contact"
table="CONTACT">
<id name="id"
type="long" column="ID" >
<generator class="assigned"/>
</id>
<property name="firstName">
<column name="FIRSTNAME"
/>
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
</class>
</hibernate-mapping>
Create
the following java files.
Contact.java
/**
* @author Deepak Kumar
*
* Java Class to map to the datbase Contact
Table
*/
public
class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
/**
* @return Email
*/
public String getEmail() {
return email;
}
/**
* @return First Name
*/
public String getFirstName() {
return firstName;
}
/**
* @return Last name
*/
public String getLastName() {
return lastName;
}
/**
* @param string Sets the Email
*/
public void setEmail(String string) {
email = string;
}
/**
* @param string Sets the First Name
*/
public void setFirstName(String string) {
firstName = string;
}
/**
* @param string sets the Last Name
*/
public void setLastName(String string) {
lastName = string;
}
/**
* @return ID Returns ID
*/
public long getId() {
return id;
}
/**
* @param l Sets the ID
*/
public void setId(long l) {
id = l;
}
}
FirstExample.java
import
org.hibernate.Session;
import
org.hibernate.SessionFactory;
import
org.hibernate.cfg.Configuration;
/**
* @author Deepak Kumar
*
* http://www.roseindia.net
* Hibernate example to inset data into Contact
table
*/
public
class FirstExample {
public static void main(String[] args) {
Session session = null;
try{
// This step will read hibernate.cfg.xml
and prepare hibernate for use
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
if(session.isConnected()) {
System.out.println("connected");
} else {
System.out.println("not
connected");
}
//Create new instance of Contact and
set values in it by reading them from form object
System.out.println("Inserting
Record");
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak_38@yahoo.com");
session.save(contact);
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen
at this step
session.flush();
session.close();
}
}
}
Sample Output
init:
deps-jar:
compile-single:
run-single:
log4j:WARN
No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN
Please initialize the log4j system properly.
connected
Inserting
Record
Done
Hibernate:
insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)
BUILD
SUCCESSFUL (total time: 1 second)
RECOMMENDATIONS
This
exercise is just an initial step to learning Hibernate. It can be further extended to include more
tables and SQL operations. A lot of
Hibernate tutorials are available on the net for additional references.