Saturday, August 20, 2016

HIBERNATE: Save & Retrieve an Entity in Hibernate

 //HOW TO SAVE  
 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); //Don't create this object too often since it's heavyweight and takes up a lot of resources to create...  
 Session session = sessionFactory.openSession();  
 session.beginTransaction();  
 session.save(user); //or whatever object that needs to be persisted  
 session.getTransaction().commit();  
 session.close();  //Always close a session after use

 //HOW TO RETREIVE USING PRIMARY KEY OR ID  
 session = sessionFactory.openSession(); //previous session is destroyed, so a new session is being generated  
 session.beginTransaction(); //transaction needs to be started again  
 user = (User) session.get(User.class, 1); //Type-casting is necessary upon retrieval  
 session.close();

No comments:

Post a Comment