List of usage examples for org.hibernate.boot.registry StandardServiceRegistryBuilder StandardServiceRegistryBuilder
public StandardServiceRegistryBuilder()
From source file:org.web4thejob.module.JobletInstallerImpl.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public <E extends Exception> List<E> install(List<Joblet> joblets) { List<E> exceptions = new ArrayList<E>(); try {//from w w w . j a va2 s. c o m final Configuration configuration = new Configuration(); configuration.setProperty(AvailableSettings.DIALECT, connInfo.getProperty(DatasourceProperties.DIALECT)); configuration.setProperty(AvailableSettings.DRIVER, connInfo.getProperty(DatasourceProperties.DRIVER)); configuration.setProperty(AvailableSettings.URL, connInfo.getProperty(DatasourceProperties.URL)); configuration.setProperty(AvailableSettings.USER, connInfo.getProperty(DatasourceProperties.USER)); configuration.setProperty(AvailableSettings.PASS, connInfo.getProperty(DatasourceProperties.PASSWORD)); final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); if (StringUtils.hasText(connInfo.getProperty(DatasourceProperties.SCHEMA_SYNTAX))) { String schemaSyntax = connInfo.getProperty(DatasourceProperties.SCHEMA_SYNTAX); Connection connection = serviceRegistry.getService(ConnectionProvider.class).getConnection(); for (Joblet joblet : joblets) { for (String schema : joblet.getSchemas()) { Statement statement = connection.createStatement(); statement.executeUpdate(schemaSyntax.replace("%s", schema)); statement.close(); } } if (!connection.getAutoCommit()) { connection.commit(); } } for (Joblet joblet : joblets) { for (Resource resource : joblet.getResources()) { configuration.addInputStream(resource.getInputStream()); } } SchemaExport schemaExport = new SchemaExport(serviceRegistry, configuration); schemaExport.execute(Target.EXPORT, SchemaExport.Type.CREATE); exceptions.addAll(schemaExport.getExceptions()); } catch (Exception e) { exceptions.add((E) e); } return exceptions; }
From source file:org.web4thejob.orm.CreateSchemaTest.java
License:Open Source License
@Test public void schemaExportTest() throws IOException, SQLException { Log4jConfigurer.initLogging("classpath:org/web4thejob/conf/log4j.xml"); Properties datasource = new Properties(); datasource.load(new ClassPathResource(DatasourceProperties.PATH).getInputStream()); final Configuration configuration = new Configuration(); configuration.setProperty(AvailableSettings.DIALECT, datasource.getProperty(DatasourceProperties.DIALECT)); configuration.setProperty(AvailableSettings.DRIVER, datasource.getProperty(DatasourceProperties.DRIVER)); configuration.setProperty(AvailableSettings.URL, "jdbc:hsqldb:mem:mydb"); configuration.setProperty(AvailableSettings.USER, datasource.getProperty(DatasourceProperties.USER)); configuration.setProperty(AvailableSettings.PASS, datasource.getProperty(DatasourceProperties.PASSWORD)); final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); Connection connection = serviceRegistry.getService(ConnectionProvider.class).getConnection(); Statement statement = connection.createStatement(); statement.executeUpdate("CREATE SCHEMA w4tj;"); statement.close();//w ww.ja v a 2 s .c o m PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { for (Resource resource : resolver.getResources("classpath*:org/web4thejob/orm/**/*.hbm.xml")) { if (resource.getFile().getName().equals("AuxiliaryDatabaseObjects.hbm.xml")) continue; configuration.addFile(resource.getFile()); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } SchemaExport schemaExport = new SchemaExport(serviceRegistry, configuration); schemaExport.execute(Target.EXPORT, SchemaExport.Type.CREATE); if (!schemaExport.getExceptions().isEmpty()) { throw new RuntimeException((Throwable) schemaExport.getExceptions().get(0)); } }
From source file:org.web4thejob.orm.CustomSessionFactoryBean.java
License:Open Source License
private void createSchemata(LocalSessionFactoryBuilder sfb) { if (!applicationContext.getResource(SCHEMA_FILE).exists()) { return;// w w w .j a va2 s . com } try { final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(sfb.getProperties()).build(); ConnectionHelper connectionHelper = new MyManagedProviderConnectionHelper(sfb.getProperties()); connectionHelper.prepare(true); MyDatabaseExporter myDatabaseExporter = new MyDatabaseExporter(connectionHelper, serviceRegistry.getService(JdbcServices.class).getSqlExceptionHelper()); for (String schema : FileUtils.readLines(applicationContext.getResource(SCHEMA_FILE).getFile())) { if (StringUtils.hasText(schema)) { myDatabaseExporter.export(schema); } } LOG.info("SCHEMA creation completed successfully."); } catch (Exception e) { e.printStackTrace(); LOG.error("Rename or remove file " + SCHEMA_FILE + " so that you don't get previous error."); } }
From source file:org.wildfly.extras.db_bootstrap.DbBootstrapScanDetectorProcessor.java
License:Apache License
/** * Create a {@link Session} based on the provided configuration file. * * @param bootstrapDatabaseAnnotation - bootstrap configuration source * @param classLoader - class loader to use with the session factory * @return {@link Session}/*from w w w . j a va 2 s.com*/ * @throws Exception */ private Session createSession(final BootstrapDatabase bootstrapDatabaseAnnotation, final ClassLoader classLoader) throws Exception { URL resource = classLoader.getResource(bootstrapDatabaseAnnotation.hibernateCfg()); DbBootstrapLogger.ROOT_LOGGER.tracef("Using hibernate configuration file %s", bootstrapDatabaseAnnotation.hibernateCfg()); Configuration configuration = new Configuration(); configuration.configure(resource); // configures settings from hibernate.cfg.xml configureSettingsFromSystemProperties(bootstrapDatabaseAnnotation, configuration); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory.openSession(); }
From source file:org.wso2.appserver.hibernate.jndi.sample.listener.HibernateSessionFactoryListener.java
License:Open Source License
public void contextInitialized(ServletContextEvent servletContextEvent) { Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); logger.info("Hibernate Configuration created successfully"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); logger.info("ServiceRegistry created successfully"); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); logger.info("SessionFactory created successfully"); servletContextEvent.getServletContext().setAttribute("SessionFactory", sessionFactory); logger.info("Hibernate SessionFactory Configured successfully"); }
From source file:org.yawlfoundation.yawl.util.HibernateEngine.java
License:Open Source License
/** initialises hibernate and the required tables */ private void initialise(Set<Class> classes, Properties props) throws HibernateException { try {// w w w .j a va 2s . co m Configuration _cfg = new Configuration(); // if props supplied, use them instead of hibernate.properties if (props != null) { _cfg.setProperties(props); } // add each persisted class to config for (Class persistedClass : classes) { _cfg.addClass(persistedClass); } // get a session context ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(_cfg.getProperties()).build(); _factory = _cfg.buildSessionFactory(serviceRegistry); // check tables exist and are of a matching format to the persisted objects new SchemaUpdate(_cfg).execute(false, true); } catch (MappingException me) { _log.error("Could not initialise database connection.", me); } }
From source file:org.yourorg.yourapp.support.HibernateUtil4.java
/** * This will pass back a Singleton instance of SessionFactory * * @return/* w w w .ja v a2 s . co m*/ */ public static SessionFactory getSessionFactory() { if (sessionFactory == null) { try { // loads configuration and mappings Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); //configuration.setProperty("hibernate.connection.password", "@ChangeMe123"); if (debug) { System.out.println("*** Hibernate Configuration loaded"); } ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); if (debug) { System.out.println("*** Hibernate serviceRegistry created"); } sessionFactory = configuration.buildSessionFactory(serviceRegistry); if (debug) { System.out.println("*** Hibernate sessionFactory created"); } } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.append(ex.getMessage()); System.out.println(sb.toString()); } } if (sessionFactory != null && debug) { System.out.println("\n*** Hibernate: sessionFactory returned.\n"); } return sessionFactory; }
From source file:orm.ORM.java
public static void main(String[] args) throws FileNotFoundException, NoSuchAlgorithmException, IOException { // TODO code application logic here MessageDigest md = MessageDigest.getInstance("MD5"); FileInputStream fis = new FileInputStream("c:\\apache\\cxf.jar"); byte[] dataBytes = new byte[1024]; int nread = 0; while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread);// ww w. j a v a2 s .co m } ; byte[] mdbytes = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < mdbytes.length; i++) { sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } System.out.println("Digest(in hex format):: " + sb.toString()); String checksum; checksum = sb.toString(); /// Hibernate Mapping starts here.... try { factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } //creating configuration object Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file //creating seession factory object ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()) .build(); SessionFactory factory = cfg.buildSessionFactory(serviceRegistry); //creating session object Session session = factory.openSession(); Transaction t = session.beginTransaction(); file e1 = new file(); e1.setID(115); e1.setName("something"); e1.setHashValue(checksum); session.persist(e1);//persisting the object t.commit();//transaction is commited session.close(); boolean a; a = ask_user(); if (a == true) { Scanner o = new Scanner(System.in); String s; System.out.print("Enter the filename"); s = o.nextline(); String hql = "SELECT" + s + "FROM file e"; String new_check; Query query = session.createQuery(hql); List results; results = query.list(); hql2 = "SELECT file hash FROM file WHERE Name like " + o; Query query2 = session.createQuery(hql2); List results2 = query2.list(); String new_check; new_check = checksum_cal(o); if (new_check.equals(old_check)) { System.out.println("No change"); } } else { System.out.println("Change in file"); } }
From source file:osdigital.dao.HibernateUtil.java
private static SessionFactory buildSessionFactory() { try {/*www. j a v a 2 s. c om*/ Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder registradorServico = new StandardServiceRegistryBuilder(); registradorServico.applySettings(cfg.getProperties()); StandardServiceRegistry servico = registradorServico.build(); return cfg.buildSessionFactory(servico); } catch (Throwable e) { // TODO: handle exception System.out.println("Criao inicial do Session Falhou. Erro !!" + e); throw new ExceptionInInitializerError(e); } }
From source file:pkg.CriteriaProductCode.java
public static SessionFactory createSessionFactory() { Configuration configuration = new Configuration(); configuration.configure();/*from ww w . ja v a 2 s . co m*/ serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; }