1 17 18 package org.objectweb.jac.aspects.hibernate; 19 20 import net.sf.hibernate.HibernateException; 21 import net.sf.hibernate.MappingException; 22 import net.sf.hibernate.Session; 23 import net.sf.hibernate.SessionFactory; 24 import net.sf.hibernate.Transaction; 25 import net.sf.hibernate.cfg.Configuration; 26 import net.sf.hibernate.tool.hbm2ddl.SchemaExport; 27 28 36 public class HibernateHelper { 37 38 private static HibernateHelper singleton = new HibernateHelper(); 39 40 43 public static HibernateHelper get() { 44 return singleton; 45 } 46 47 52 private Configuration cfg = new Configuration(); 53 54 59 public void addClass( Class cl ) throws MappingException { 60 cfg.addClass(cl); 61 rebuildsf = true; 62 } 63 64 67 public void schemaExport() throws HibernateException { 68 new SchemaExport(cfg).create(false,true); 69 } 70 71 75 private boolean rebuildsf = true; 76 private SessionFactory sf; 77 78 81 private SessionFactory getSessionFactory() throws HibernateException { 82 if (rebuildsf) { 83 sf = cfg.buildSessionFactory(); 84 rebuildsf = false; 85 } 86 return sf; 87 } 88 89 95 public void openSessionAndBeginTx() throws HibernateException { 96 SessionFactory sf = getSessionFactory(); 97 session = sf.openSession(); 98 tx = session.beginTransaction(); 99 } 100 101 102 private Session session; 103 public Session getSession() { 104 if ( session == null || !session.isOpen() ) 105 throw new RuntimeException ("openSessionAndBeginTx() should have been called first"); 106 return session; 107 } 108 109 110 private Transaction tx; 111 public Transaction getTx() throws HibernateException { 112 if ( tx == null || tx.wasCommitted() || tx.wasRolledBack() ) 113 throw new RuntimeException ("openSessionAndBeginTx() should have been called first"); 114 return tx; 115 } 116 } 117 | Popular Tags |