Thursday, August 12, 2010

Hibernate JPA 2.0 on glassfish v3 with Netbeans IDE setup tutorial

After it took me almost a day to get Hibernate working properly on GF I thought I'd write here how it's done.

In this tutorial I used the following products:
  • NetBeans 6.9.1 - get the JEE version at least
  • Glassfish 3.0.1
  • Mysql
and libraries:
  • Hibernate 3.5.3
  • Slf4j-1.5.8 (you need to get the same version as the API module distributed with hibernate - in this case  slf4j-api-1.5.8.jar)
  • Log4j 1.2.16
  • mysql-connector-java-5.1.11-bin.jar - this is used in GF to connect to MySQL databases.
Make sure you get all of the above before proceding.
From now on I'll assume you have NetBeans, Glassfish & MySql installed and working properly.

Creating a database
Use the following sql dump to create a test database:

/*
SQLyog Ultimate v8.3 
MySQL - 5.0.77 : Database - tutorial
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`tutorial` /*!40100 DEFAULT CHARACTER SET latin1 */;

USE `tutorial`;

/*Table structure for table `employee` */

DROP TABLE IF EXISTS `employee`;

CREATE TABLE `employee` (
  `employeeId` int(11) NOT NULL auto_increment,
  `employeeName` varchar(100) default NULL,
  PRIMARY KEY  (`employeeId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

/*Data for the table `employee` */

insert  into `employee`(`employeeId`,`employeeName`) values (1,'John Doe'),(2,'Frank Bates'),(3,'Alex Smith');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;


Also, don't forget to create a user with full access to this DB.