You are on page 1of 5

Hibernate operations(Insert,Delete,Retrieve and Update data) with Mysql.

Filed under: Hibernate 7 Comments 2011/12/25

5 Votes

Firstly you should want to create a database.It may be can do using Mysql server or Eclipse IDE. Window>Open Perspective>Other>Database Development.In that window has Database Connection link.Right click it and select NEW.After that select MYSQL and give the DATABASE NAME.After that select NEXT. In that window you should want to select MYSQL JDBC DRIVER(download it) for Drivers.And also give USERNAME and PASSWORD.After completed all of those you can test your connection using TEST CONNECTION button.If you can see PING SUCCESSFULLy you have not any errors.Now you can click FINISH Button. Now your package has two files.Those are hibernate.cfg.xml and log4j.properties. hibernate.cfg.xml file should want to edit like this.
<?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> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/MilindaFirst</property> <property name="connection.username">UserName</property> <property name="connection.password">PassWord</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">2</property> <!-- SQL dialect -->

<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's current session context --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> </session-factory> </hibernate-configuration>

Secoundly you want create Persistence class.


import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Person { private int id; private String name; private int age; @Id 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } }

Data Insertion
import import import import org.hibernate.SessionFactory; org.hibernate.cfg.AnnotationConfiguration; org.hibernate.classic.Session; org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson { public static void main(String[] args) { //create configurations for Person class AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Person.class); config.configure("hibernate.cfg.xml"); //create new schema(db and table) new SchemaExport(config).create(true, true);//comment this line if you already created the table Person SessionFactory factory = config.buildSessionFactory(); Session session = factory.getCurrentSession(); session.beginTransaction();//begin the db operations //Insertion to the table Person person = new Person();//create the object from persistent class //set data that you want to store in db person.setId(1); person.setName("Sandun"); person.setAge(22); session.save(person);//save the object to db session.getTransaction().commit();//save permanently to db(end of db operations) }

Data Deletion.
import import import import org.hibernate.SessionFactory; org.hibernate.cfg.AnnotationConfiguration; org.hibernate.classic.Session; org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson { public static void main(String[] args) { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Person.class); config.configure("hibernate.cfg.xml"); SessionFactory factory = config.buildSessionFactory(); //beginning of the session Session session = factory.openSession(); session.beginTransaction();//beginning of the transaction String searchId = "1";//this is the key id for field being updated //create the delete query String query = "delete from Person as p where p.id = :key";

session.createQuery(query).setString("key", searchId).executeUpdate(); session.getTransaction().commit();//end of transaction session.close();//end of session } }

Data Updating.
import import import import org.hibernate.SessionFactory; org.hibernate.cfg.AnnotationConfiguration; org.hibernate.classic.Session; org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson { public static void main(String[] args) { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Person.class); config.configure("hibernate.cfg.xml"); SessionFactory factory = config.buildSessionFactory(); //beginning of the session Session session = factory.openSession(); session.beginTransaction();//beginning of the transaction String name = "New_Milinda";//this is new name for 'id' String id = "1";//this is the key id for field being updated //create the update query String query = "update Person as p set p.name = :newName where p.id = :keyId"; session.createQuery(query) .setString("newName", name)//this will set the string 'newName' to name variable .setString("keyId", id) .executeUpdate(); session.getTransaction().commit();//end of transaction session.close();//end of session } }

Data Retreive.
import java.util.Iterator; import java.util.List;import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.classic.Session; //import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson { public static void main(String[] args) { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Person.class); config.configure("hibernate.cfg.xml"); SessionFactory factory = config.buildSessionFactory(); Session session = factory.getCurrentSession(); session.beginTransaction(); String searchId = "1"; String query = "from Person as p where p.id = :sId"; List list = session.createQuery(query) .setString("sId", searchId).list(); Iterator iterator = list.iterator(); while (iterator.hasNext()) {//is next data exist? then loop Person obj = (Person) iterator.next();//cast and assign next data to Person type object System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n"); } session.close();

You might also like