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