Code for updating database using hibernate framework in java
Written by Ankur Goel
This program will try to connect to the mysql database with the username and password given the xml file.
Include the following
· Hibernate framework
· Commons-lang-2.4.jar
· Mysql-connector-java-5.1.5-bin.jar
Make a package hibernate1
Save this file as Main.java
package hibernate1;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
Session session = null;
try{
// This step will read hibernate.cfg.xml
//Session sess=HibernateUtil.currentSession();
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
//Create new instance of Contact and set
System.out.println("Inserting Record");
Contact contact = new Contact();
long a=1;
contact.setId("5");
contact.setFirstName("Deepak1");
contact.setLastName("Kumar");
//contact.setEmail("deepak");
System.out.println(contact.getFirstName());
Transaction tr = session.beginTransaction();
//Contact ins = (Contact)session.get(Contact.class, "1");
//ins.setFirstName("Jivan Dhara");
//ins.setInvestementDate(new Date());
//session.update(ins);
session.save(contact);
tr.commit();
session.close();
//session.save(contact);
System.out.println("Done");
//session.flush();
//session.close();
}catch(Exception e){
//System.out.println(e.getMessage());
e.printStackTrace();
}finally{
// Actual contact insertion will happen at this step
}
}
}
Now make a xml file outside the package directory and save it as hibernate.cfg.xml
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
Now make a Contact.java
package hibernate1;
public class Contact {
private String firstName;
private String lastName;
private String id;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String string) {
firstName = string;
}
public void setLastName(String string) {
lastName = string;
}
public String getId() {
return id;
}
public void setId(String l) {
id = l;
}
}
Now make a corresponding xml file for Contact and save in the same directory as Contact.java
Save the xml file as Contact.hbm.xml
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
















Comments