/** * Configuration of session factory with Fabric integration. */ public static SessionFactory createSessionFactory(String fabricUrl, String username, String password, String fabricUser, String fabricPassword) throws Exception { // creating this here allows passing needed params to the constructor FabricMultiTenantConnectionProvider connProvider = new FabricMultiTenantConnectionProvider(fabricUrl, "employees", "employees", username, password, fabricUser, fabricPassword); ServiceRegistryBuilder srb = new ServiceRegistryBuilder(); srb.addService(org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider.class, connProvider); srb.applySetting("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect"); Configuration config = new Configuration(); config.setProperty("hibernate.multiTenancy", "DATABASE"); config.addResource("com/mysql/fabric/demo/employee.hbm.xml"); return config.buildSessionFactory(srb.buildServiceRegistry()); }
public void saveByOpenSession(T t) { //读取配置文件 configuration = new Configuration().configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); Session session = null; try { session = sessionFactory.openSession(); //开启事务 session.beginTransaction(); session.save(t); //提交事务 session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); //回滚事务 session.getTransaction().rollback(); } finally { if (session != null) { if (session.isOpen()) { //关闭session session.close(); } } } }
/** * Inits the. */ private static void init() { //Change the path to your deployed config file ! File configFile = new File("/Users/matthiasivantsits/git/AnSoMia/AnSoMnia/src/hibernate.cfg.xml"); //File configFile = new File("/Users/matthiasivantsits/git/AnSoMia/AnSoMnia/src/hibernate.cfg.xml"); Configuration configuration = new Configuration(); //add all classes you want to annotate configuration.addAnnotatedClass(Index.class); configuration.addAnnotatedClass(Company.class); configuration.addAnnotatedClass(MarketValue.class); configuration.addAnnotatedClass(KeyPerformanceIndicator.class); configuration.addAnnotatedClass(News.class); configuration.addAnnotatedClass(NewsDetail.class); configuration.addAnnotatedClass(SentenceInformation.class); configuration.addAnnotatedClass(IndustrySector.class); configuration.addAnnotatedClass(CompanyInformation.class); configuration.addAnnotatedClass(EntityInformation.class); configuration.configure(configFile); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); }
public static void main(String[] args) throws Exception { // set up a Hibernate Session final Configuration configuration = new Configuration(); configuration.addAnnotatedClass(PersonNst.class); configuration.configure(); final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); final SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); final Session session = sessionFactory.openSession(); session.beginTransaction(); new HibernateSessionExample().run(new DbSessionHibernateImpl(session)); session.getTransaction().commit(); session.close(); sessionFactory.close(); }
public static void main(String[] args) throws Exception { // set up a Hibernate Session final Configuration configuration = new Configuration(); configuration.addAnnotatedClass(PersonCtt.class); configuration.addAnnotatedClass(PersonOrganisationalTreePath.class); configuration.addAnnotatedClass(PersonFunctionalTreePath.class); configuration.configure(); final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); final SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); final Session session = sessionFactory.openSession(); session.beginTransaction(); new HibernateSessionExample().run(new DbSessionHibernateImpl(session)); session.getTransaction().commit(); session.close(); sessionFactory.close(); }
/** * Abstract: Build SessionFactory object */ public static void rebuildSessionFactory() { try { // Initial application using configuration file configuration = new Configuration(); configuration.configure(configFile); // Create SessionFactory object according to the configuration // Data model can be created in MySQL automatically after execute // this method ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder(); ServiceRegistry serviceRegistry = serviceRegistryBuilder.applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.configure().buildSessionFactory(serviceRegistry); } catch (Exception e) { e.printStackTrace(); } }
@BeforeClass public static void setUpBeforeClass() throws Exception { // service commonServiceImpl = new CommonServiceImpl(); // dao commonDaoImpl = new CommonDaoImpl(); // 建構HibernateTemplate,因HibernateDaoSupporter需要 HibernateTemplate hibernateTemplate = new HibernateTemplate(); Configuration config = new Configuration().configure("hibernate.cfg.xml"); // SessionFactory sessionFactory = config.buildSessionFactory(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()) .buildServiceRegistry(); SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); hibernateTemplate.setSessionFactory(sessionFactory); commonDaoImpl.setHibernateTemplate(hibernateTemplate); // commonServiceImpl.setCommonDao(commonDaoImpl); commonServiceImpl.start(); }
@Test public void openSession() throws Exception { Configuration config = new Configuration().configure("hibernate.cfg.xml"); // SessionFactory sessionFactory = config.buildSessionFactory(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()) .buildServiceRegistry(); SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); System.out.println("sessionFactory: " + sessionFactory); Session session = sessionFactory.openSession(); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { System.out.println("connection: " + connection); System.out.println("getAutoCommit: " + connection.getAutoCommit()); System.out.println("getTransactionIsolation: " + connection.getTransactionIsolation()); } }); }
/** * 生成一个新的SessionFactory,将模块的的model解析. * 这里将来可以做成从资源配置文件中动态解析生成. * @param entityClasses * @return */ private SessionFactory obtainSessionFactory(Collection<Class> entityClasses){ LocalSessionFactoryBean localSessionFactoryBean =(LocalSessionFactoryBean) SpringContextUtil.getBean("&defaultSessionFactory"); Configuration configuration = localSessionFactoryBean.getConfiguration(); synchronized(configuration){//避免并发操作导致configuration重复添加相同的entityClass for(Class entityClass:entityClasses){ if(configuration.getClassMapping(entityClass.getName())==null){ configuration.addAnnotatedClass(entityClass); } } } Thread.currentThread().setContextClassLoader(this);//设置当前的Classloader不然会报找不到类的错误 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory newSessionFactory = configuration.buildSessionFactory(serviceRegistry); log.info("为模块中{}个类重新生成一个新的SessionFactory",entityClasses.size()); Map<String,SessionFactory> sessionFactoryMap =(Map<String,SessionFactory>) SpringContextUtil.getBean("sessionFactoryMap"); sessionFactoryMap.put(getModulesBean().getName(),newSessionFactory); return newSessionFactory; }
public DNEHibernateSessionFactory(String configFile) { if ((configFile == null) || (configFile.equals(""))) { LOG.info("Inicializando a DNE sem conexão com o banco de dados."); this.customFactory = null; } else { try { LOG.debug("Carregando DNE no Hibernate pelo arquivo: "+configFile); Configuration config = new Configuration(); config .configure("dne.hibernate.mappings.xml") .configure(configFile) ; ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder() .applySettings(config.getProperties()); this.customFactory = config.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry()); } catch (Exception ex) { LOG.error("Um erro ocorreu ao tentar estabelecer a conexão com a DNE pelo arquivo: " +configFile,ex); LOG.info("Inicializando a DNE sem conexão com o banco de dados devido à erros."); this.customFactory = null; } } }
public static synchronized void buildSessionFactory(String configFile_) throws HibernateException { try { File configFile = new File(configFile_); // Create the SessionFactory from hibernate.cfg.xml Configuration config = new Configuration(); ServiceRegistry serviceRegistry; MetadataSources metadataSources; config.configure(configFile); serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); _sessionFactory = config.buildSessionFactory(serviceRegistry); } catch(HibernateException e) { throw e; } }
/** * Connect to the database and create a sessionFactory object * * @return the newly created session factory */ private static SessionFactory buildSessionFactory() { try { Configuration configuration = new Configuration(); // avoid slow startup: http://stackoverflow.com/questions/10075081/hibernate-slow-to-acquire-postgres-connection // configuration.setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false"); configuration.configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
/** * Initializes the hibernate system. */ public static void init() { logger.debug("Initializing hibernate..."); Configuration configuration = new Configuration().configure(); logger.debug("Performing schema update"); new SchemaUpdate(configuration).execute(true, true); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); logger.debug("Hibernate initialized"); }
@Override public void start( ) throws StartException { try { File file = new File("/"); File[] files = file.listFiles(); for ( File f : files ) { logger.debug(f.getAbsolutePath()); } Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); factory = configuration.buildSessionFactory(serviceRegistry); } catch ( HibernateException ex ) { throw new StartException("Exception while starting hibernate", ex); } }
private static SessionFactory configureSessionFactory() throws HibernateException { Configuration configuration = new Configuration(); configuration.configure(); Properties properties = configuration.getProperties(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder(). applySettings(properties).buildServiceRegistry(); SessionFactory sessionFactory = configuration. buildSessionFactory(serviceRegistry); return sessionFactory; }
@Before public void start() throws Exception { TestEnvironment.configureFromClassResource("/dwr.xml"); Configuration config = new Configuration(); config.configure("hibernate.cfg.xml"); sessionFactory = config.buildSessionFactory( new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry()); Assert.assertNotNull(sessionFactory); }
@Override public void init() { boolean testing = Boolean.parseBoolean(System.getProperty("testing")); Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); configuration.setInterceptor(new HibernateInterceptor()); if (!testing) { configuration.setProperty("hibernate.connection.username", Reference.getEnvironmentProperty("db.username")); configuration.setProperty("hibernate.connection.password", Reference.getEnvironmentProperty("db.password")); String url = "jdbc:mysql://" + Reference.getEnvironmentProperty("db.host") + ":" + Reference.getEnvironmentProperty("db.port") + "/devwars"; configuration.setProperty("hibernate.connection.url", url); } else { configuration.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver"); configuration.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:testdb"); configuration.setProperty("hibernate.connection.username", "sa"); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); } ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); EventListenerRegistry registry = ((SessionFactoryImpl) DatabaseManager.sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class); registry.getEventListenerGroup(EventType.POST_LOAD).appendListener(postLoadEvent -> { HibernateInterceptor.postLoadAny(postLoadEvent.getEntity()); HibernateInterceptor.invokeMethodWithAnnotation(postLoadEvent.getEntity(), PostLoad.class); }); }
private static void init() { String hibernateConfigLocation; try { hibernateConfigLocation = MetaConfiguration.getConfiguration().getString(HIBERNATE_CONFIGURATION_PROPERTY); } catch (Exception e) { hibernateConfigLocation = null; } try { Configuration configuration = new Configuration(); if (hibernateConfigLocation == null) { configuration.configure(); } else { configuration.configure(new File(hibernateConfigLocation)); } // // Add server connection details // DatabaseServer databaseServer = ServerConfigurationService.Factory.getInstance().getOrdsDatabaseServer(); configuration.setProperty("hibernate.connection.url", databaseServer.getUrl()); configuration.setProperty("hibernate.connection.username", databaseServer.getUsername()); configuration.setProperty("hibernate.connection.password", databaseServer.getPassword()); addMappings(configuration); serviceRegistry = new ServiceRegistryBuilder().applySettings( configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception he) { System.err.println("Error creating Session: " + he); throw new ExceptionInInitializerError(he); } }
public static void rebuildSessionFactory() { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } }
private static SessionFactory buildSessionFactory(String configFileName) { try { Configuration cfg = new Configuration().configure(configFileName); cfg.addAnnotatedClass(Actor.class); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry(); return cfg.buildSessionFactory(serviceRegistry); } catch (HibernateException e) { throw new ExceptionInInitializerError(e); } }
public static synchronized void buildSessionFactory() { if (sessionFactory == null) { Configuration configuration = new Configuration(); configuration.configure("/persistencia/hibernate.cfg.xml"); configuration.setProperty( "hibernate.current_session_context_class", "thread"); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()) .buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } }
/** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } }
void setUp() throws Exception { final Configuration configuration = new Configuration(); for (Class<?> persistenceClass : persistenceClasses) configuration.addAnnotatedClass(persistenceClass); configuration.configure(); final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); session = sessionFactory.openSession(); }
/** * @param igniteInstanceName Name of the grid providing caches. * @return Session factory. */ private SessionFactory startHibernate(String igniteInstanceName) { Configuration cfg = hibernateConfiguration(igniteInstanceName); ServiceRegistryBuilder builder = new ServiceRegistryBuilder(); builder.applySetting("hibernate.connection.url", CONNECTION_URL); builder.applySetting("hibernate.show_sql", false); return cfg.buildSessionFactory(builder.buildServiceRegistry()); }
/** * @param accessType Cache access typr. * @param igniteInstanceName Name of the grid providing caches. * @return Session factory. */ private SessionFactory startHibernate(AccessType accessType, String igniteInstanceName) { Configuration cfg = hibernateConfiguration(accessType, igniteInstanceName); ServiceRegistryBuilder builder = new ServiceRegistryBuilder(); builder.applySetting("hibernate.connection.url", CONNECTION_URL); builder.applySetting("hibernate.show_sql", false); return cfg.buildSessionFactory(builder.buildServiceRegistry()); }
/** * @return Hibernate registry builder. */ protected ServiceRegistryBuilder registryBuilder() { ServiceRegistryBuilder builder = new ServiceRegistryBuilder(); builder.applySetting("hibernate.connection.url", CONNECTION_URL); return builder; }
protected static void createSessionFactory() { if (sessionFactory != null) { return; } createConfiguration(); // ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()) .buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); System.out.println(sessionFactory); }
protected static void createSessionFactory() { if (sessionFactory != null) { return; } createConfiguration(); // ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); System.out.println(sessionFactory); }
/** * 直接使用hibernate.cfg.xml, s並非由spring注入 */ public static void createCommonServiceImpl() { try { // service commonServiceImpl = new CommonServiceImpl(); // dao CommonDaoImpl commonDaoImpl = new CommonDaoImpl(); // 建構HibernateTemplate,因HibernateDaoSupporter需要 HibernateTemplate hibernateTemplate = new HibernateTemplate(); Configuration config = new Configuration().configure("hibernate.cfg.xml"); // SessionFactory sessionFactory = config.buildSessionFactory(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()) .buildServiceRegistry(); SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); // System.out.println("sessionFactory: " + sessionFactory); // hibernateTemplate.setSessionFactory(sessionFactory); commonDaoImpl.setHibernateTemplate(hibernateTemplate); // commonServiceImpl.setCommonDao(commonDaoImpl); // listener serviceBeanListener = new CommonBeanAdapter(); commonServiceImpl.addBeanListener(serviceBeanListener); assertNotNull(commonServiceImpl); commonServiceImpl.start(); System.out.println("---------------------------"); System.out.println("createCommonServiceImpl [success]"); System.out.println("---------------------------"); } catch (Exception ex) { System.out.println("---------------------------"); System.out.println("createCommonServiceImpl [fail]"); System.out.println("---------------------------"); ex.printStackTrace(); } }
public static SessionFactory createSessionFactory() { Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; }
private SessionFactory register(Configuration configuration) { if (!this.mapping.isEmpty()) { for (Class<?> clazz : this.mapping) { configuration.addAnnotatedClass(clazz); } } ServiceRegistry service = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()) .buildServiceRegistry(); return configuration.buildSessionFactory(service); }
public static Session getSession() { if (sessionFactory == null) { Configuration cfg = getConfiguration(null); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings( cfg.getProperties()).buildServiceRegistry(); sessionFactory = cfg.buildSessionFactory(serviceRegistry); } return sessionFactory.getCurrentSession(); }
static public Session getSession(Map<String, String> map) { Configuration cfg = getConfiguration(map); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings( cfg.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry); return sessionFactory.getCurrentSession(); }