HibernateでDBアクセスするにはorg.hibernate.Sessionを取得する必要がある。
そのための手順は、次のようになる。
- Configuration configration = new Configuration().configure();
- ServiceRegistryBuilder builder = new ServiceRegistryBuilder().applySettings(configration.getProperties());
- ServiceRegistry serviceRegistry = builder.buildServiceRegistry();
- SessionFactory sessionFactory = configration.buildSessionFactory(serviceRegistry);
- Session session = sessionFactory.openSession();
- DBアクセス処理
- session.close()
HibernateConfigServiceクラス
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; */ public class HibernateConfigService { private static HibernateConfigService instance = null; private Configuration configration = null; private SessionFactory sessionFactory = null; private ConnectionProvider connProvider = null; protected HibernateConfigService() { String configFileName = System.getenv("hibernateConfig"); if (configFileName == null) { configration = new Configuration().configure(); } else { configration = new Configuration().configure(configFileName); } } public static HibernateConfigService getInstance() { if(instance == null) { instance = new HibernateConfigService(); } return instance; } /** * <p>[ユニットテスト用]{@link HibernateConfigService}インスタンスを取得する</p> * @param pConnectionProvider {@link ConnectionProvider}インスタンス * @return {@link HibernateConfigService}インスタンス */ public static HibernateConfigService getInstance(final ConnectionProvider pConnectionProvider) { if(instance == null) { instance = new HibernateConfigService(); } instance.setConnProvider(pConnectionProvider); return instance; } @SuppressWarnings("deprecation") public SessionFactory getSessionFactory() { if(sessionFactory == null) { ServiceRegistryBuilder builder = new ServiceRegistryBuilder() .applySettings(configration.getProperties()); if (connProvider != null) { builder = builder.addService(ConnectionProvider.class, connProvider); } ServiceRegistry serviceRegistry = builder.buildServiceRegistry(); sessionFactory = configration.buildSessionFactory(serviceRegistry); } return sessionFactory; } private void setConnProvider(ConnectionProvider pConnProvider) { this.connProvider = pConnProvider; } public Configuration getConfigration() { return this.configration; } }
0 件のコメント:
コメントを投稿