private SessionFactory createSessionFactory(boolean traceWithActiveSpanOnly) { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(Employee.class); configuration.setProperty("hibernate.connection.driver_class", "io.opentracing.contrib.jdbc.TracingDriver"); configuration.setProperty("hibernate.connection.url", "jdbc:tracing:h2:mem:hibernate?traceWithActiveSpanOnly=" + traceWithActiveSpanOnly); configuration.setProperty("hibernate.connection.username", "sa"); configuration.setProperty("hibernate.connection.password", ""); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop"); configuration.setProperty("hibernate.show_sql", "true"); configuration.setProperty("hibernate.connection.pool_size", "10"); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); return configuration.buildSessionFactory(builder.build()); }
private SessionFactory createSessionFactory(String options) { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(Employee.class); configuration.setProperty("hibernate.connection.url", "jdbc:p6spy:hsqldb:mem:hibernate" + options); configuration.setProperty("hibernate.connection.username", "sa"); configuration.setProperty("hibernate.connection.password", ""); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop"); configuration.setProperty("hibernate.show_sql", "true"); configuration.setProperty("hibernate.connection.pool_size", "10"); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build()); return sessionFactory; }
public static void main(String[] args) { Configuration cfg=null; SessionFactory factory=null; Session ses=null; Transaction tx=null; cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml"); factory=cfg.buildSessionFactory(); ses=factory.openSession(); String hql="select item_name from bigbazarModel where bazarid=:id"; Query q=ses.createQuery(hql); q.setParameter("id", 1001); String s=(String) q.uniqueResult(); System.out.println("\t\t"+s); factory.close(); }
public static void main(String[] args) { Configuration cfg=null; SessionFactory factory=null; Session ses=null; Transaction tx=null; cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml"); factory=cfg.buildSessionFactory(); ses=factory.openSession(); tx=ses.beginTransaction(); String hql="insert into newMall(mallid,item_name,item_price,item_quantity) " + "select bazarid,item_name,item_price,item_quantity from bigbazarModel "; Query q=ses.createQuery(hql); int c=q.executeUpdate(); //int count=Integer.parseUnsignedInt(c); tx.commit(); System.out.println("\t\t"+c+" rows Copied Successfully..."); factory.close(); }
public DBServiceImpl() { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(UserDataSet.class); configuration.addAnnotatedClass(PhoneDataSet.class); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver"); configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/db_example"); configuration.setProperty("hibernate.connection.username", "tully"); configuration.setProperty("hibernate.connection.password", "tully"); configuration.setProperty("hibernate.show_sql", "true"); configuration.setProperty("hibernate.hbm2ddl.auto", "create"); configuration.setProperty("hibernate.connection.useSSL", "false"); configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true"); configuration.setProperty("hibernate.jdbc.time_zone", "UTC"); sessionFactory = createSessionFactory(configuration); }
public DBServiceImpl() { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(UserDataSet.class); configuration.addAnnotatedClass(PhoneDataSet.class); configuration.addAnnotatedClass(AddressDataSet.class); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver"); configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/db_example"); configuration.setProperty("hibernate.connection.username", "tully"); configuration.setProperty("hibernate.connection.password", "tully"); configuration.setProperty("hibernate.show_sql", "true"); configuration.setProperty("hibernate.hbm2ddl.auto", "create"); configuration.setProperty("hibernate.connection.useSSL", "false"); configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true"); sessionFactory = createSessionFactory(configuration); }
@PostConstruct public void init() throws ClassNotFoundException { final Configuration configuration = annotationSessionFactory .getConfiguration(); final ReflectionManager reflectionManager = configuration .getReflectionManager(); final Iterator<PersistentClass> classMappings = configuration .getClassMappings(); while (classMappings.hasNext()) { entityCallbackHandler.add(reflectionManager.classForName( classMappings.next().getClassName(), this.getClass()), reflectionManager); } }
public DBServiceImpl() { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(UserDataSet.class); configuration.addAnnotatedClass(PhoneDataSet.class); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver"); configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/db_example"); configuration.setProperty("hibernate.connection.username", "tully"); configuration.setProperty("hibernate.connection.password", "tully"); configuration.setProperty("hibernate.show_sql", "true"); configuration.setProperty("hibernate.hbm2ddl.auto", "create"); configuration.setProperty("hibernate.connection.useSSL", "false"); configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true"); sessionFactory = createSessionFactory(configuration); }
private static SessionFactory buildSessionFactory() { try { logger.info("Configurando conexao Hibernate->MySQL"); Configuration configuration = new Configuration().configure(); logger.info("Hibernate->MySQL - Properties: " + configuration.getProperties()); // Create the SessionFactory from hibernate.cfg.xml return configuration.buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed logger.error("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
public static synchronized void createConnection() { try { if (sessionFactory == null) { sessionFactory = new Configuration().configure("com/coder/hms/connection/hibernate.cfg.xml") .addAnnotatedClass(Reservation.class).buildSessionFactory(); } } catch (HibernateException e) { Toolkit.getDefaultToolkit().beep(); final InformationFrame dialog = new InformationFrame(); dialog.setMessage("Sorry we can't connect to database right now, without " + "connection the application will not work properly."); dialog.okBtn.addActionListener(ActionListener->{ return; }); dialog.setVisible(true); } }
/** * 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 DbService() { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(UserDataSet.class); configuration.addAnnotatedClass(AddressDataSet.class); configuration.addAnnotatedClass(PhoneDataSet.class); configuration.addAnnotatedClass(Account.class); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); configuration.setProperty("hibernate.connection.url", "jdbc:h2:~/test"); configuration.setProperty("hibernate.connection.username", "sa"); configuration.setProperty("hibernate.connection.password", ""); configuration.setProperty("hibernate.show_sql", "true"); configuration.setProperty("hibernate.hbm2ddl.auto", "create"); configuration.setProperty("hibernate.connection.useSSL", "false"); configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true"); sessionFactory = createSessionFactory(configuration); }
public SchemaExport(ServiceRegistry serviceRegistry, Configuration configuration) { this.connectionHelper = new SuppliedConnectionProviderConnectionHelper( serviceRegistry.getService( ConnectionProvider.class ) ); this.sqlStatementLogger = serviceRegistry.getService( JdbcServices.class ).getSqlStatementLogger(); this.formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter(); this.sqlExceptionHelper = serviceRegistry.getService( JdbcServices.class ).getSqlExceptionHelper(); this.importFiles = ConfigurationHelper.getString( AvailableSettings.HBM2DDL_IMPORT_FILES, configuration.getProperties(), DEFAULT_IMPORT_FILE ); final Dialect dialect = serviceRegistry.getService( JdbcServices.class ).getDialect(); this.dropSQL = configuration.generateDropSchemaScript( dialect ); this.createSQL = configuration.generateSchemaCreationScript( dialect ); }
private SchemaUpdate getSchemaUpdate(Configuration cfg) throws HibernateException, IOException { Properties properties = new Properties(); properties.putAll( cfg.getProperties() ); if (propertiesFile == null) { properties.putAll( getProject().getProperties() ); } else { properties.load( new FileInputStream(propertiesFile) ); } cfg.setProperties(properties); SchemaUpdate su = new SchemaUpdate(cfg); su.setOutputFile( outputFile.getPath() ); su.setDelimiter(delimiter); su.setHaltOnError(haltOnError); return su; }
@SuppressWarnings( {"unchecked"}) public SessionFactoryServiceRegistryImpl( ServiceRegistryImplementor parent, SessionFactoryImplementor sessionFactory, Configuration configuration) { super( parent ); this.sessionFactory = sessionFactory; this.configuration = configuration; this.metadata = null; // for now, just use the standard initiator list for ( SessionFactoryServiceInitiator initiator : StandardSessionFactoryServiceInitiators.LIST ) { // create the bindings up front to help identify to which registry services belong createServiceBinding( initiator ); } }
public static void main(String[] args) { String path = "hibernate.cfg.xml"; Configuration cfg = new Configuration().configure(path); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); User user = new User(); user.setId("443"); user.setName("baa"); session.save(user); // session.close(); session.getTransaction().commit(); sessionFactory.close(); }
public static void main(String[] args) { String path = "hibernate.cfg.xml"; Configuration cfg = new Configuration().configure(path); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); User user = new User(); user.setId("46"); user.setName("aaa"); session.save(user); // session.close(); session.getTransaction().commit(); sessionFactory.close(); }
public DBServiceImpl() { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(UserDataSet.class); configuration.addAnnotatedClass(PhoneDataSet.class); configuration.addAnnotatedClass(EmptyDataSet.class); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver"); configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/db_example"); configuration.setProperty("hibernate.connection.username", "tully"); configuration.setProperty("hibernate.connection.password", "tully"); configuration.setProperty("hibernate.show_sql", "true"); configuration.setProperty("hibernate.hbm2ddl.auto", "create"); configuration.setProperty("hibernate.connection.useSSL", "false"); configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true"); sessionFactory = createSessionFactory(configuration); }
public static SessionFactory getSessionFactory() { if (sessionFactory == null || sessionFactory.isClosed()) { try { Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder(); serviceRegistryBuilder.applySettings(configuration.getProperties()); ServiceRegistry serviceRegistry = serviceRegistryBuilder.build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); // sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (HibernateException ex) { ex.printStackTrace(); System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } return sessionFactory; }
public static void fixSchemaInFormulas(Configuration cfg) { cfg.buildMappings(); String schema = cfg.getProperty("default_schema"); if (schema!=null) { for (Iterator i=cfg.getClassMappings();i.hasNext();) { PersistentClass pc = (PersistentClass)i.next(); for (Iterator j=pc.getPropertyIterator();j.hasNext();) { Property p = (Property)j.next(); for (Iterator k=p.getColumnIterator();k.hasNext();) { Selectable c = (Selectable)k.next(); if (c instanceof Formula) { Formula f = (Formula)c; if (f.getFormula()!=null && f.getFormula().indexOf("%SCHEMA%")>=0) { f.setFormula(f.getFormula().replaceAll("%SCHEMA%", schema)); sLog.debug("Schema updated in "+pc.getClassName()+"."+p.getName()+" to "+f.getFormula()); } } } } } } }
/** * Create the SessionFactory from hibernate.cfg.xml * * @return A new SessionFactory */ private static SessionFactory buildSessionFactory() { try { return new Configuration().configure().buildSessionFactory(); } catch (Throwable exception) { System.err.println("Initial SessionFactory creation failed." + exception); throw new ExceptionInInitializerError(exception); } }
public DBServiceImpl() { Configuration configuration = new Configuration() .configure(new File("config/hibernate.cfg.xml")) .addFile(new File("config/UserDataSet.hbm.xml")); sessionFactory = createSessionFactory(configuration); }
@Override public void executeScriptUrl(String scriptUrl) throws Exception { Configuration cfg = localSessionFactory.getConfiguration(); Connection connection = dataSource.getConnection(); connection.setAutoCommit(true); try { executeScriptUrl(cfg, connection, scriptUrl); } finally { connection.close(); } }
private void executeScriptUrl(Configuration cfg, Connection connection, String scriptUrl) throws Exception { Dialect dialect = Dialect.getDialect(cfg.getProperties()); String dialectStr = dialect.getClass().getSimpleName(); InputStream scriptInputStream = getScriptInputStream(dialect.getClass(), scriptUrl); // check that it exists if (scriptInputStream == null) { throw AlfrescoRuntimeException.create(ERR_SCRIPT_NOT_FOUND, scriptUrl); } // write the script to a temp location for future and failure reference File tempFile = null; try { tempFile = TempFileProvider.createTempFile("AlfrescoSchema-" + dialectStr + "-Update-", ".sql"); ContentWriter writer = new FileContentWriter(tempFile); writer.putContent(scriptInputStream); } finally { try { scriptInputStream.close(); } catch (Throwable e) {} // usually a duplicate close } // now execute it String dialectScriptUrl = scriptUrl.replaceAll(PLACEHOLDER_DIALECT, dialect.getClass().getName()); // Replace the script placeholders executeScriptFile(cfg, connection, tempFile, dialectScriptUrl); }
@SuppressWarnings("deprecation") @Override public Dialect getObject() throws SQLException { Session session = ((SessionFactory) this.localSessionFactory.getObject()).openSession(); Configuration cfg = this.localSessionFactory.getConfiguration(); Connection con = null; try { // make sure that we AUTO-COMMIT con = session.connection(); con.setAutoCommit(true); DatabaseMetaData meta = con.getMetaData(); overrideDialectPropertyForDriver(cfg.getProperties(), meta.getDriverName()); Dialect dialect = DialectFactory.buildDialect(cfg.getProperties(), meta.getDatabaseProductName(), meta.getDatabaseMajorVersion()); dialect = changeDialect(cfg, dialect); return dialect; } finally { try { con.close(); } catch (Exception e) { } } }
/** * Substitute the dialect with an alternative, if possible. * * @param cfg * the configuration * @param dialect * the dialect * @return the dialect */ private Dialect changeDialect(Configuration cfg, Dialect dialect) { String dialectName = cfg.getProperty(Environment.DIALECT); if (dialectName == null || dialectName.length() == 0) { // Fix the dialect property to match the detected dialect cfg.setProperty(Environment.DIALECT, dialect.getClass().getName()); } return dialect; // TODO: https://issues.alfresco.com/jira/browse/ETHREEOH-679 // else if (dialectName.equals(Oracle9Dialect.class.getName())) // { // String subst = AlfrescoOracle9Dialect.class.getName(); // LogUtil.warn(logger, WARN_DIALECT_SUBSTITUTING, dialectName, subst); // cfg.setProperty(Environment.DIALECT, subst); // } // else if (dialectName.equals(MySQLDialect.class.getName())) // { // String subst = MySQLInnoDBDialect.class.getName(); // LogUtil.warn(logger, WARN_DIALECT_SUBSTITUTING, dialectName, subst); // cfg.setProperty(Environment.DIALECT, subst); // } // else if (dialectName.equals(MySQL5Dialect.class.getName())) // { // String subst = MySQLInnoDBDialect.class.getName(); // LogUtil.warn(logger, WARN_DIALECT_SUBSTITUTING, dialectName, subst); // cfg.setProperty(Environment.DIALECT, subst); // } }
@Before public void init() { // 准备环境 { Configuration configuration = new Configuration().configure("hbm.cfg.xml"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); factory = configuration.buildSessionFactory(serviceRegistry); } }
private SessionFactory createSessionFactory() { SessionFactory sessionFactory = null; try { String resource; Configuration configuration = new Configuration(); resource = "oswf-store.cfg.xml"; logger.info("Configuring Hibernate Mapping: " + resource); configuration.configure(resource); // Database configuration; H2 or MySQL resource = "hibernate.xml"; logger.info("Configuring Hibernate Mapping: " + resource); configuration.configure(resource); // Attempt to create the SessionFactory; exceptions may be thrown sessionFactory = configuration.buildSessionFactory(); } catch (Throwable e) { logger.error(fatal, "Failed to create Hibernate SessionFactory: " + e.toString()); sessionFactory = null; } return sessionFactory; }
private SessionFactory() { try { HibernateConfiguration hibernateConfiguration = ConfigurationWrapper.getInstance().getHibernateConfiguration(); Configuration configuration = new Configuration(); initHBMs(configuration); configuration.configure(hibernateConfiguration.getPathToConfigurationFile()); StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); sessionFactory = configuration.buildSessionFactory(standardServiceRegistryBuilder.build()); }catch (Exception excetption){ } }
private void initHBMs(Configuration configuration) throws IOException { //TODO test this. Enumeration<URL> resources = getClass().getClassLoader().getResources(""); while(resources.hasMoreElements()){ URL url = resources.nextElement(); String file = url.getFile(); if(file.endsWith(".hbm.xml")){ configuration.addResource(file); } } }
/** * Return the Hibernate Configuration object used to build the SessionFactory. * Allows for access to configuration metadata stored there (rarely needed). * @throws IllegalStateException if the Configuration object has not been initialized yet */ public final Configuration getConfiguration() { if (this.configuration == null) { throw new IllegalStateException("Configuration not initialized yet"); } return this.configuration; }
/** * Reads metadata from annotated classes and packages into the * AnnotationConfiguration instance. */ @Override protected void postProcessMappings(Configuration config) throws HibernateException { if (this.annotatedClasses != null) { for (Class<?> annotatedClass : this.annotatedClasses) { config.addAnnotatedClass(annotatedClass); } } if (this.annotatedPackages != null) { for (String annotatedPackage : this.annotatedPackages) { config.addPackage(annotatedPackage); } } scanPackages(config); }
/** * Specify the Hibernate Configuration class to use. * <p>Default is {@link org.hibernate.cfg.Configuration}; any subclass * of this default Hibernate Configuration class can be specified. */ @SuppressWarnings("unchecked") public void setConfigurationClass(Class<?> configurationClass) { if (configurationClass == null || !Configuration.class.isAssignableFrom(configurationClass)) { throw new IllegalArgumentException( "'configurationClass' must be assignable to [org.hibernate.cfg.Configuration]"); } this.configurationClass = (Class<? extends Configuration>) configurationClass; }
/** * Return the Configuration object used to build the SessionFactory. * Allows for access to configuration metadata stored there (rarely needed). * @throws IllegalStateException if the Configuration object has not been initialized yet */ public final Configuration getConfiguration() { if (this.configuration == null) { throw new IllegalStateException("Configuration not initialized yet"); } return this.configuration; }