-------------------------
Beans .java file
-------------------------
package my.beans;
/**
*
* @author raj
*/
public class Pen {
private int id;
private String penName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPenName() {
return penName;
}
public void setPenName(String penName) {
this.penName = penName;
}
}
---------------------------------------------------------------------
Methods To Store and Display Data of Pens
---------------------------------------------------------------------
//default package
public class MyHIbernateBasics{
public static void main(String rk[]){
MyHIbernateBasics start=new MyHIbernateBasics();
start.storePenData("PinkPen");
start.showPensData();
start.updatePensData();
}
public void storePenData(String penName) {
Session mySession = HibernateUtil.getSessionFactory().getCurrentSession();
mySession.beginTransaction();
Pen pen= new Pen();
pen.setPenName(penName);
mySession.save(pen);
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
public void showPensData(){
Session mySession = HibernateUtil.getSessionFactory().getCurrentSession();
mySession.beginTransaction();
System.out.println(".............PENS DATA..........");
List pensList = session.createQuery("from Pens").list();
for (int i = 0; i < pensList.size(); i++) {
Pen myPen = pensList .get(i);
System.out.println("Id : " + myPen.getId() + " Name : " + myPen.getPenName() );
}
mySession.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
public void updatePensData(){
//UPDATIND DATA INTO Pens TABLE
Session mySession = HibernateUtil.getSessionFactory().getCurrentSession();
mySession.beginTransaction();
System.out.println("..............Pens Data..................");
Vector
allPens= new Vector(session.createQuery("from Pens").list()); for (Pen p : allPens) {
if (p.getPenName().equals("PinkPen")) {
p.setPenName("RK");
mySession.update(p);
}
}
//DISPLAYING DATA OF THE Pens TABLE
for (Pen myPen : allPens) {
System.out.println("Id : " + myPen.getId() + " Name : " + myPen.getPenName() );
}
mySession.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
}
----------------------------------------------------------
Java Class file to Get SessionFactory
----------------------------------------------------------
package my.utils;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
public static SessionFactory sessionFactory=null;
static
{
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
}
catch(Throwable e){
System.out.println(" :-( Error Message: "+e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}