List of usage examples for org.hibernate.cfg Configuration getProperties
public Properties getProperties()
From source file:com.aegeus.db.DbSessionFactory.java
License:Apache License
protected void build(DbIdentity identity, List<Class> pojoGroup) { Configuration cfg = new Configuration(); cfg.setProperty("hibernate.connection.driver", identity.getDriver()) .setProperty("hibernate.dialect", identity.getDialect()) .setProperty("hibernate.connection.url", identity.getUrl()) .setProperty("hibernate.connection.username", identity.getUsername()) .setProperty("hibernate.connection.password", identity.getPassword()) .setProperty("hibernate.connection.CharSet", "utf-8") .setProperty("hibernate.connection.characterEncoding", "utf-8") .setProperty("hibernate.connection.useUnicode", "true") .setProperty("current_session_context_class", "thread").setProperty("connection.pool_size", "4") .setProperty("hibernate.show_sql", "true"); for (Class pojo : pojoGroup) { cfg.addAnnotatedClass(pojo);/*from w w w. j a va 2 s .c o m*/ } StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(); builder.applySettings(cfg.getProperties()); factory = cfg.buildSessionFactory(builder.build()); }
From source file:com.alfredmuponda.lostandfound.persistence.HibernateUtil.java
private static SessionFactory buildSessionFactory() { try {/* w w w .j a va 2s .c o m*/ // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); System.out.println("Hibernate Configuration loaded"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); System.out.println("Hibernate serviceRegistry created"); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
From source file:com.alfredmuponda.lostandfound.persistence.HibernateUtil.java
private static SessionFactory buildSessionAnnotationFactory() { try {//from w w w . ja v a 2 s . co m // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); configuration.configure("hibernate-annotation.cfg.xml"); System.out.println("Hibernate Annotation Configuration loaded"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); System.out.println("Hibernate Annotation serviceRegistry created"); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
From source file:com.alfredmuponda.lostandfound.persistence.HibernateUtil.java
private static SessionFactory buildSessionJavaConfigFactory() { try {/* w w w . j ava 2 s . c om*/ Configuration configuration = new Configuration(); //Create Properties, can be read from property files too Properties props = new Properties(); props.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver"); props.put("hibernate.connection.url", "jdbc:mysql://localhost/LostAndFound"); props.put("hibernate.connection.username", "hitrac"); props.put("hibernate.connection.password", "hitrac"); props.put("hibernate.current_session_context_class", "thread"); configuration.setProperties(props); //we can set mapping file or class with annotation //addClass(Employee1.class) will look for resource // com/journaldev/hibernate/model/Employee1.hbm.xml (not good) //configuration.addAnnotatedClass(Employee1.class); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); System.out.println("Hibernate Java Config serviceRegistry created"); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
From source file:com.almuradev.backpack.backend.DatabaseManager.java
License:MIT License
public static void init(Path databaseRootPath, String name) { final Configuration configuration = new Configuration(); configuration.setProperty("hibernate.connection.provider_class", CONNECTION_PROVIDER); configuration.setProperty("hibernate.dialect", DIALECT); configuration.setProperty("hibernate.hikari.dataSourceClassName", DRIVER_CLASSPATH); configuration.setProperty("hibernate.hikari.dataSource.url", DATA_SOURCE_PREFIX + databaseRootPath.toString() + File.separator + name + DATA_SOURCE_SUFFIX); configuration.setProperty("hibernate.hbm2ddl.auto", AUTO_SCHEMA_MODE); registerTables(configuration);// www . j a v a2 s . com sessionFactory = configuration.buildSessionFactory( new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build()); }
From source file:com.anyuan.thomweboss.persistence.dao.HibernateDaoTemplate.java
License:Apache License
/** * ?hibernatejdbctransaction// w w w .j ava 2 s .c o m * @author Thomsen * @since Dec 15, 2012 11:20:02 PM * @return */ public static Transaction getTranscation() { Transaction transaction = null; try { Configuration configuration = new Configuration().configure(); // classpathhibernate.cfg.xml ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(registry); // hibernate4.0 ?buildSessionFactory() // Session session = sessionFactory.getCurrentSession(); session = sessionFactory.openSession(); transaction = session.beginTransaction(); } catch (HibernateException e) { e.printStackTrace(); } if (transaction == null) { throw new HibernateException("transaction is null"); } return transaction; }
From source file:com.anyuan.thomweboss.persistence.hibimpl.user.UserDaoHibImpl.java
License:Apache License
@Override public List<User> listAll() { Configuration config = new Configuration().configure(); ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(config.getProperties()) .buildServiceRegistry();/*from w ww . j av a2 s. co m*/ SessionFactory sessionFactory = config.buildSessionFactory(registry); Session session = sessionFactory.openSession(); String hql = "from User"; Query query = session.createQuery(hql); List<User> listUser = query.list(); session.close(); return listUser; }
From source file:com.arnau.persistencia.hibernate.HibernateUtil.java
public static synchronized void buildSessionFactory() { if (sessionFactory == null) { Configuration configuration = new Configuration(); configuration.configure();//w w w . j a v a 2 s .com configuration.setProperty("hibernate.current_session_context_class", "thread"); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } }
From source file:com.atolcd.alfresco.repo.patch.SchemaUpgradeScriptPatch.java
License:Open Source License
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); }//from ww w .jav a2s.co m // 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_SCRIPT_DIALECT, dialect.getClass().getName()); // Replace the script placeholders executeScriptFile(cfg, connection, tempFile, dialectScriptUrl); }
From source file:com.atolcd.alfresco.repo.patch.SchemaUpgradeScriptPatch.java
License:Open Source License
/** * @param cfg/*from w w w . j av a2 s .c om*/ * the Hibernate configuration * @param connection * the DB connection to use * @param scriptFile * the file containing the statements * @param scriptUrl * the URL of the script to report. If this is null, the script * is assumed to have been auto-generated. */ @SuppressWarnings("resource") private void executeScriptFile(Configuration cfg, Connection connection, File scriptFile, String scriptUrl) throws Exception { final Dialect dialect = Dialect.getDialect(cfg.getProperties()); StringBuilder executedStatements = executedStatementsThreadLocal.get(); if (executedStatements == null) { // Dump the normalized, pre-upgrade Alfresco schema. We keep the // file for later reporting. /* * xmlPreSchemaOutputFile = dumpSchema(this.dialect, * TempFileProvider .createTempFile( "AlfrescoSchema-" + * this.dialect.getClass().getSimpleName() + "-", * "-Startup.xml").getPath(), * "Failed to dump normalized, pre-upgrade schema to file."); */ // There is no lock at this stage. This process can fall out if the // lock can't be applied. // setBootstrapStarted(connection); executedStatements = new StringBuilder(8094); executedStatementsThreadLocal.set(executedStatements); } if (scriptUrl == null) { LogUtil.info(logger, MSG_EXECUTING_GENERATED_SCRIPT, scriptFile); } else { LogUtil.info(logger, MSG_EXECUTING_COPIED_SCRIPT, scriptFile, scriptUrl); } InputStream scriptInputStream = new FileInputStream(scriptFile); BufferedReader reader = new BufferedReader(new InputStreamReader(scriptInputStream, "UTF-8")); try { int line = 0; // loop through all statements StringBuilder sb = new StringBuilder(1024); String fetchVarName = null; String fetchColumnName = null; boolean doBatch = false; int batchUpperLimit = 0; int batchSize = 1; Map<String, Object> varAssignments = new HashMap<String, Object>(13); // Special variable assignments: if (dialect instanceof PostgreSQLDialect) { // Needs 1/0 for true/false varAssignments.put("true", "true"); varAssignments.put("false", "false"); varAssignments.put("TRUE", "TRUE"); varAssignments.put("FALSE", "FALSE"); } else { // Needs true/false as strings varAssignments.put("true", "1"); varAssignments.put("false", "0"); varAssignments.put("TRUE", "1"); varAssignments.put("FALSE", "0"); } while (true) { String sqlOriginal = reader.readLine(); line++; if (sqlOriginal == null) { // nothing left in the file break; } // trim it String sql = sqlOriginal.trim(); // Check for variable assignment if (sql.startsWith("--ASSIGN:")) { if (sb.length() > 0) { // This can only be set before a new SQL statement throw AlfrescoRuntimeException.create(ERR_STATEMENT_VAR_ASSIGNMENT_BEFORE_SQL, (line - 1), scriptUrl); } String assignStr = sql.substring(9, sql.length()); String[] assigns = assignStr.split("="); if (assigns.length != 2 || assigns[0].length() == 0 || assigns[1].length() == 0) { throw AlfrescoRuntimeException.create(ERR_STATEMENT_VAR_ASSIGNMENT_FORMAT, (line - 1), scriptUrl); } fetchVarName = assigns[0]; fetchColumnName = assigns[1]; continue; } // Handle looping control else if (sql.startsWith("--FOREACH")) { // --FOREACH table.column batch.size.property String[] args = sql.split("[ \\t]+"); int sepIndex; if (args.length == 3 && (sepIndex = args[1].indexOf('.')) != -1) { doBatch = true; // Select the upper bound of the table column String stmt = "SELECT MAX(" + args[1].substring(sepIndex + 1) + ") AS upper_limit FROM " + args[1].substring(0, sepIndex); Object fetchedVal = executeStatement(connection, stmt, "upper_limit", false, line, scriptFile); if (fetchedVal instanceof Number) { batchUpperLimit = ((Number) fetchedVal).intValue(); // Read the batch size from the named property String batchSizeString = globalProperties.getProperty(args[2]); // Fall back to the default property if (batchSizeString == null) { batchSizeString = globalProperties.getProperty(PROPERTY_DEFAULT_BATCH_SIZE); } batchSize = batchSizeString == null ? 10000 : Integer.parseInt(batchSizeString); } } continue; } // Allow transaction delineation else if (sql.startsWith("--BEGIN TXN")) { connection.setAutoCommit(false); continue; } else if (sql.startsWith("--END TXN")) { connection.commit(); connection.setAutoCommit(true); continue; } // Check for comments if (sql.length() == 0 || sql.startsWith("--") || sql.startsWith("//") || sql.startsWith("/*")) { if (sb.length() > 0) { // we have an unterminated statement throw AlfrescoRuntimeException.create(ERR_STATEMENT_TERMINATOR, (line - 1), scriptUrl); } // there has not been anything to execute - it's just a // comment line continue; } // have we reached the end of a statement? boolean execute = false; boolean optional = false; if (sql.endsWith(";")) { sql = sql.substring(0, sql.length() - 1); execute = true; optional = false; } else if (sql.endsWith("(optional)") || sql.endsWith("(OPTIONAL)")) { // Get the end of statement int endIndex = sql.lastIndexOf(';'); if (endIndex > -1) { sql = sql.substring(0, endIndex); execute = true; optional = true; } else { // Ends with "(optional)" but there is no semi-colon. // Just take it at face value and probably fail. } } // Add newline if (sb.length() > 0) { sb.append("\n"); } // Add leading whitespace for formatting int whitespaceCount = sqlOriginal.indexOf(sql); for (int i = 0; i < whitespaceCount; i++) { sb.append(" "); } // append to the statement being built up sb.append(sql); // execute, if required if (execute) { // Now substitute and execute the statement the appropriate // number of times String unsubstituted = sb.toString(); for (int lowerBound = 0; lowerBound <= batchUpperLimit; lowerBound += batchSize) { sql = unsubstituted; // Substitute in the next pair of range parameters if (doBatch) { varAssignments.put("LOWERBOUND", String.valueOf(lowerBound)); varAssignments.put("UPPERBOUND", String.valueOf(lowerBound + batchSize - 1)); } // Perform variable replacement using the ${var} format for (Map.Entry<String, Object> entry : varAssignments.entrySet()) { String var = entry.getKey(); Object val = entry.getValue(); sql = sql.replaceAll("\\$\\{" + var + "\\}", val.toString()); } // Handle the 0/1 values that PostgreSQL doesn't // translate to TRUE if (this.dialect != null && this.dialect instanceof PostgreSQLDialect) { sql = sql.replaceAll("\\$\\{TRUE\\}", "TRUE"); } else { sql = sql.replaceAll("\\$\\{TRUE\\}", "1"); } if (this.dialect != null && this.dialect instanceof MySQLInnoDBDialect) { // note: enable bootstrap on MySQL 5.5 (eg. for // auto-generated SQL, such as JBPM) sql = sql.replaceAll("(?i)TYPE=InnoDB", "ENGINE=InnoDB"); } Object fetchedVal = executeStatement(connection, sql, fetchColumnName, optional, line, scriptFile); if (fetchVarName != null && fetchColumnName != null) { varAssignments.put(fetchVarName, fetchedVal); } } sb.setLength(0); fetchVarName = null; fetchColumnName = null; doBatch = false; batchUpperLimit = 0; batchSize = 1; } } } finally { try { reader.close(); } catch (Throwable e) { } try { scriptInputStream.close(); } catch (Throwable e) { } } }