1 22 23 package org.jboss.test.hibernate.model.v2; 24 25 import java.util.List ; 26 import javax.ejb.SessionBean ; 27 import javax.ejb.SessionContext ; 28 import javax.naming.InitialContext ; 29 import javax.naming.NamingException ; 30 31 import org.hibernate.HibernateException; 32 import org.hibernate.SessionFactory; 33 import org.hibernate.Session; 34 import org.hibernate.tool.hbm2ddl.SchemaExport; 35 import org.hibernate.cfg.Configuration; 36 37 40 public class PersonBean implements SessionBean 41 { 42 private SessionContext context; 43 44 public void ejbCreate() 45 { 46 } 47 48 public void ejbActivate() 49 { 50 } 51 52 public void ejbPassivate() 53 { 54 } 55 56 public void ejbRemove() 57 { 58 } 59 60 public void setSessionContext(SessionContext context) 61 { 62 this.context = context; 63 } 64 65 public void init( ) 66 throws HibernateException 67 { 68 Configuration cfg = new Configuration().configure(); 69 SchemaExport se = new SchemaExport(cfg); 70 se.create(true, true); 71 } 72 public void sessionInit( ) 73 throws HibernateException 74 { 75 Configuration cfg = new Configuration().configure(); 76 SessionFactory sf = cfg.buildSessionFactory(); 77 System.out.println("Initialized session: "+sf); 78 } 79 80 public Person loadUser(long id) throws HibernateException 81 { 82 return loadUser( new Long (id) ); 83 } 84 85 public Person loadUser(Long id) throws HibernateException 86 { 87 return (Person) getSession().load(Person.class, id); 88 } 89 90 public List listPeople() throws HibernateException 91 { 92 return getSession() 93 .createQuery("from Person") 94 .list(); 95 } 96 97 public Person loadUser(String name) throws HibernateException 98 { 99 return (Person) getSession() 100 .createQuery("from Person as p where p.name = :name") 101 .setString("name", name) 102 .uniqueResult(); 103 } 104 105 public Person storeUser(Person user) throws HibernateException 106 { 107 getSession().saveOrUpdate(user); 108 getSession().flush(); 109 return user; 110 } 111 112 private Session getSession() 113 { 114 try 115 { 116 InitialContext ctx = new InitialContext (); 117 String sessionName = (String ) ctx.lookup("java:/comp/env/HibernateFactory"); 118 SessionFactory sf = (SessionFactory) ctx.lookup(sessionName); 119 return sf.getCurrentSession(); 120 } 121 catch( HibernateException e ) 122 { 123 throw e; 124 } 125 catch( NamingException e ) 126 { 127 throw new HibernateException(e); 128 } 129 } 130 131 } 132 | Popular Tags |