Wednesday, March 2, 2011

Configuring Hibernate with MySql

Requirement for:
Hibernate 3.6.1
hibernate-commons-annotations.jar
ejb3-persistence.jar
hibernate-annotations.jar

import all the jar file to your project by:
*Right Click your project.
*Build Path->Configuration Build Path
*Add External Jar then go to the location of all the jar you need to import then select it and ok.
*then Okey.

List of all the jar you need to import:
#hibernate3.jar
#ejb*-persistence.jar
#jta-*.jar
#javassist-*.jar
#antlr-*.jar
#common-collections.*.jar
#dom4j-*.jar
#slf4j-api-*.jar
#hibernate-jpa-*-api*.Final.jar
#mysql-connector-java-*-bin.jar

Create a Student that will be used for connecting to MySQL using Hibernate:


package hibernate; //the package where you class belong

/* all this class is located inside ejb*-persistence.jar */
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity //use to define a table that will use the class name as it entity name
public class Student {
//member variable definition
private String userId;
private String password;

@Id //use to define a primary key if your PK is generated (example: autoincrement) you can use @GeneratedValue Annotation
@Column //use to define a column uses PropertyName as column name (in here column name is userid
public String getUserId() //retrieve value for userid
{
return userId;
}
public void setUserId(String userId)//set value for userid
{
this.userId = userId;
}

@Column
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
//there are many other annotation you can use, you see them go to ejb3-persistance.jar then javax.persistence
}
Now let's create the hibernate.cfg.xmlfile. It must be located on the root file of your classes folder.






com.mysql.jdbc.Driver
jdbc:mysql://localhost/yourdatabasename
your_mysql_user_name
your_mysql_user_for_that_username
10
org.hibernate.dialect.MySQLDialect
true
create



Create a class that will use the Student class:

use the classes: org.hibernate.Session, org.hibernate.SessionFactory, org.hibernate.cfg.Configuration.

To insert data to a table:


SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
//get the configuration of the hibernate.cfg.xml
Session session = sessionFactory.openSessionFactory();
session.beginTransaction();
Student student = new Student();
student.setUserId("001");
student.setPassword("dynamicobjx");
session.save(student);
session.getTransaction().commit();
session.close();

No comments:

Post a Comment