Labsheet 5
Labsheet 5
It provides an API enabling us to create .read ,update and delete persistent objects
(Persistent objects are instances of POJO classes that you create that represent rows in the table in
the database.).
Commit: It automatically flushes the session. (It is used to permanently saves the changes done in
transaction in tables or databases.)
Student.java
package com.pu.test123;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Student {
@Id
private int roll;
private String name;
private int marks;
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
}
To create hibernate configuration file
Hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driv
er</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/
god?characterEncoding=latin1</property>
<property
name="hibernate.connection.username">root</property>
<property
name="hibernate.connection.password">admin123</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect<
/property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update </property>
<mapping resource="com.pu.student.hbm.xml" />
</session-factory>
</hibernate-configuration>
App.java
package com.pu.test123;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
Student student = new Student();
student.setRoll(1);
student.setName("god");
student.setMarks(100);
//1. create Configuration object
Configuration configuration=new
Configuration().configure().addAnnotatedClass(Student.class)
;
//2. create Session Factroy object
SessionFactory
sessionFactory=configuration.buildSessionFactory();
//3. Create Session object
Session session=sessionFactory.openSession();
//4. Begin your transaction
Transaction transaction=session.beginTransaction();
//5.Save your object to database
session.save(student);
//6/ Commit your transaction
transaction.commit();
session.close();
sessionFactory.close();
}
}