So far,we have written a User class that we want to persist and a mapping file that describes the relationship of each of the attributes of the class to the database columns. We have also configured the Hibernate SessionFactory (hibernate.cfg.xml) to use the User.hbm.xml. Now it is the time to write a business component that can perform different operations on the User object.


7.1 Session


 Before writing the business component,we need to understand a hibernate 'session'. As discussed in section 1.5,a hibernate session is an instance of org.hibernate.SessionopenSession() of SessionFactory. Every database operation begins and ends with a Session. For example,we can beginTransaction(),save(),update() or delete() an object with the help of a Session. and is obtained by calling


Our business component will use the Session to perform its business operations.


package com.visualbuilder.hibernate.client; import org.hibernate.Session; import com.visualbuilder.hibernate.User; /**  * UserManager  * @author VisualBuilder  */ public class UserManager { private Session session = null; public UserManager(Session session) { if(session == null) throw new RuntimeException("Invalid session object. Cannot instantiate the UserManager"); this.session = session; } public void saveUser(User user) { session.save(user); } public void updateUser(User user) { session.update(user); } public void deleteUser(User user) { session.delete(user); } } 
                    

Copyright © 2010 VisualBuilder. All rights reserved