2 problems to resolve before running FirstExample,
January 17, 2008 at 1:34 PM
I believe there are 2 errors in this tutorial.
1) You have to create the "hibernatetutorial" database in MySQL. The command is "create database hibernatetutorial" The hibernatetutorial database is referenced in file hibernate.cfg.xml in line "<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetutorial</property>".
2) Since this tutorial was written a while ago, I'm using a different version of MySQL than the author of this tutorial, and the default behavior of MySQL may have changed since then. At first executing FirstExample.java would create tables Contact, Book, and Insurance, but no records were inserted in any of the tables. The problem is that we need to begin a transaction, then save the session, and then commit the transaction.
As posted by nidhin:
The following line need to be added right after session open in try block of FirstExample.java
/** * @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; org.hibernate.Transaction tx = null;
try { // This step will read hibernate.cfg.xml and prepare hibernate for use SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); session =sessionFactory.openSession(); tx = session.beginTransaction();
//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(6); // Primary key has to be unique for every record inserted! contact.setFirstName("John"); contact.setLastName("Doe"); contact.setEmail("noemail@yahoo.com"); session.save(contact); tx.commit(); System.out.println("Done"); }catch(Exception e){ System.out.println(e.getMessage()); e.printStackTrace(); if (tx != null) { System.out.println("Rolling back transaction"); tx.rollback(); } } finally { try { // Actual contact insertion will happen at this step session.flush(); session.close(); } catch (Exception e){ e.printStackTrace(); }