You are here

MyEclipse+Hibernate 1--Get start and add record

First of all, I strongly recommand you to use MyEclispe 5.0.1GA and Eclipse 3.2M2, because Hibernate seems do not like the old version of MyEclipse(4.0 or 4.1) and Eclispe 3.1, many boring and stupid exceptions were thrown during the database operation test, such as "cannot connect to database","primery-key error". After 2 days of suffering this, I begin to use the new version, this makes Hibernate very very happy, and it works very fine till now.

Requirement:
1. Eclipse 3.2M2     free for downloading
2. MyEclispe 5.0.1 GA  free to test
3. J2EE Environment.
4. MySql

Ok, begin the travel:
1. create new web project in Myeclipse





2. Create one new database in MySQL using such SQL query:

CREATE DATABASE `test`
BS&i IRGuestUSE `test`;MyPlaces(自我空间 自由展现)0ek"Cm?kE*o;O3_ ~Pv

B[8^v#r FGuestCREATE TABLE `user` (
r5E#X.r%d G'UGuest`id` int(11) NOT NULL auto_increment,
!mC;mMz&zt0qGuest`username` varchar(30) NOT NULL default '',
#h VB4xeGuest`password` varchar(30) default '',MyPlaces(自我空间 自由展现)8x@,mn^Q$sr
PRIMARY KEY (`id`)
v:FqU/nAdGuest) ;

And select Window->Open Perspective->Other->MyEclispe Hibernate


In DB Browse, click new icon to create a new connection.


Click Configure database driver:


Add new drivers:


And please download database driver mysql-connector-java-5.0.4-bin.jar from MySQL site.
http://dev.mysql.com/downloads/connector/j/5.0.html
And fill as following, the driver should be add through Add JARs/


Add user name and password and connect it.


And you will have such overview of database:



3. right click the project , MyEclispe->add Hibernate capabilities


I am also newbie and I am not clear which library should be needed, so the two were chosen. And select Copy checked library jars to the Project folder:


Create new hibernate config file:


Select the database you have selected:


I havnt createn SessionFactory here and finished.


4. Generate hibernate mapping file and java class:
Goto DB Browse and right click the table user, and select hibernate reserve energeering:


Select the java src folder, input user(or others you like) in the java package and click next:


Select native for ID generator, because in mysql, the id is auto_increment, we should set it to native. Click Finish:


And your Package Explorer should be like this:


5. Create test class and operate the database.
create new class test in package test.


And input the following code:

package test;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import user.User;

public class test {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

          try {           
               SessionFactory sf = new Configuration().configure().buildSessionFactory();
               Session session = sf.openSession();
               Transaction tx = session.beginTransaction();

               User user = new User();
              
               user.setUsername("mway");
               user.setPassword("mway");

               session.save(user);
               tx.commit();

               session.flush();
               session.close();
               sf.close();
              } catch (HibernateException e) {
               e.printStackTrace();
              }
       
    }

}

And run it as java application, these are 2 warining about log4j, dont care it. If successful, open Window: Table/Object Info->Preview, you will find a new record was add into the database.



Notice: Maybe you have googled about how to use hibernate and find the test code is different from mine.  Please notice that those articles are discribing the old version of hibernate, for example, Hibernate 2.0, those codes maybe like this, it is not wrong, but for the old version!
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import user.User;

public class test {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
//         Create a configuration based on the properties file we
//         have put in the standard place
        Configuration config = new Configuration();
        //config.addFile("vo//User.hbm.xml");
//         Tell it about the classes we want mapped, taking advantage
//         of the way we have named their mapping documents
         config.addClass(User.class);
       
//         A SessionFactory is Hibernate's concept of a single datastore
//         Get the sesion factory we can use for persistence
        SessionFactory sf = config.buildSessionFactory();

//         Hibernate's Session, is the persistence manager interface,
//         we use it to store and retrieve MyUsers to and from the database
//         Ask for a session using the JDBC information we have configured
        Session session = sf.openSession();

          try {            
               //SessionFactory sf = new Configuration().configure().buildSessionFactory();
               //Session session = sf.openSession();
               Transaction tx = session.beginTransaction();

               User user = new User();
               //System.out.println(user.getUsername());

               user.setUsername("mway");
               user.setPassword("mway");

               session.save(user);
               tx.commit();

               session.flush();
               session.close();
               sf.close();
              } catch (HibernateException e) {
               e.printStackTrace();
              }
              finally
              {
//                 close our session and release resources
                session.flush();
                session.close();
                }

//                 Clean up after ourselves
                sf.close();
                }
       
    }

}


Ref:
1 myeclipse-jsf-spring-hibernate
http://joeyta.blogspot.com/2006/06/myeclipse-jsf-spring-hibernate.html
2 使用myeclipse集成struts,hibernate,spring的一个示例程序
3. Working with Hibernate in Eclipse
http://www.onjava.com/pub/a/onjava/2004/06/23/hibernate.html?page=1
Blog: 

Comments

{:)} Hi,

I am very happy for posting this site to us.I have done above program using myclipse 7.I would like to see an output if you provide sample ouput for hiberate with spring.
Once again i want to say thanks.

{:)}

Thank you sooooooooooooooooo much. This example really works!!!!!!!!!!! Little dance, little dance.

hello all,

i just need a sample web project which should get input from the user and after submit the details should be saved in the database.. by using Struts+Hibernate+MyEclipse6.6 and MySQL as database... plz help..

hi all,

I just need a web project which should get input from a user and the datas should be saved in database using Struts+hibernate+MyEclipse and MySQL as database...

plz help me....!!!