Hibernate persist method example

Hibernate persist method example

Employee.java

package com.smgc;

public class Employee {
private int id;
private String name;
private String designation;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {
this.designation = designation;
}
}


hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

  
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<mapping resource="Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>


Employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?> 
<!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  

<hibernate-mapping>
<class name="com.smgc.Employee" table="employee">
<id name="id">
<generator class="assigned"></generator>
</id>

<property name="name"></property>
<property name="designation"></property>

</class>

</hibernate-mapping>  


EmpMain.java

package com.smgc;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class EmpMain {

public static void main(String[] args) {
// TODO Auto-generated method stub
// creating configuration object
Configuration cfg = new Configuration();

cfg.configure("hibernate.cfg.xml");// populates the data of the
// configuration file

// creating seession factory object
SessionFactory factory = cfg.buildSessionFactory();

// creating session object
Session session = factory.openSession();

// creating transaction object
Transaction t = session.beginTransaction();

Employee e1 = new Employee();
e1.setId(111);
e1.setName("Piyush");
e1.setDesignation("Lecturer");
session.persist(e1); // Persistent Object since it is attached to hibernate
// session

System.out.println("successfully saved");

t.commit();
// here we can say it is detached object as it went to DB now.
session.close();
}
}


Comments

Popular posts from this blog

પટેલ સમાજનો ઈતિહાસ જાણો : કોણ અને ક્યાંથી આવ્યા હતા પાટીદારો

Python HTML Generator using Yattag Part 1

Java Event Delegation Model, Listener and Adapter Classes