@Bean public EntityManagerFactory entityManagerFactory() { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setDatabase(Database.H2); vendorAdapter.setGenerateDdl(jpaGenerateDdl); vendorAdapter.setShowSql(jpaShowSql); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("org.bricket.b4.*.entity"); factory.setDataSource(dataSource()); factory.setJpaDialect(jpaDialect()); Map<String, String> jpaProperties = new HashMap<String, String>(); jpaProperties.put("hibernate.dialect", H2Dialect.class.getName()); jpaProperties.put("hibernate.cache.region.factory_class", EhCacheRegionFactory.class.getName()); jpaProperties.put("hibernate.cache.use_second_level_cache", "true"); jpaProperties.put("hibernate.cache.use_query_cache", "true"); jpaProperties.put("hibernate.cache.use_minimal_puts", "true"); factory.setJpaPropertyMap(jpaProperties); factory.afterPropertiesSet(); return factory.getObject(); }
/** * 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型. * 仅支持Oracle 10, H2, MySql, PostgreSql, SQLServer,如需更多数据库类型,请仿照此类自行编写。 */ public static String getDialect(DataSource dataSource) { switch (getDBType(dataSource)) { case H2: return H2Dialect.class.getName(); case MYSQL: return MySQLDialectWithoutFK.class.getName(); case ORACLE: return Oracle10gDialectWithoutFK.class.getName() ; case POSTGRESQL: return PostgreSQL9DialectWithoutFK.class.getName() ; case SQL_SERVER: return SQLServer2008Dialect.class.getName(); } throw new IllegalArgumentException("未知的数据库类型"); }
/** * Determine the Hibernate database dialect class for the given target database. * @param database the target database * @return the Hibernate database dialect class, or {@code null} if none found */ @SuppressWarnings("deprecation") protected Class<?> determineDatabaseDialectClass(Database database) { switch (database) { case DB2: return DB2Dialect.class; case DERBY: return DerbyDialect.class; // DerbyDialect deprecated in 4.x case H2: return H2Dialect.class; case HSQL: return HSQLDialect.class; case INFORMIX: return InformixDialect.class; case MYSQL: return MySQLDialect.class; case ORACLE: return Oracle9iDialect.class; case POSTGRESQL: return PostgreSQLDialect.class; // PostgreSQLDialect deprecated in 4.x case SQL_SERVER: return SQLServerDialect.class; case SYBASE: return org.hibernate.dialect.SybaseDialect.class; // SybaseDialect deprecated in 3.6 but not 4.x default: return null; } }
private static Class<?> hibernateDatabaseDialectClass(DatabasePlatform database) { switch (database) { case DB2: return DB2Dialect.class; case DB2_AS400: return DB2400Dialect.class; case DERBY: return DerbyTenSevenDialect.class; case H2: return H2Dialect.class; case HSQL: return HSQLDialect.class; case INFORMIX: return InformixDialect.class; case MYSQL: return MySQL5Dialect.class; case ORACLE: return Oracle10gDialect.class; case POSTGRESQL: return PostgreSQL82Dialect.class; case SQL_SERVER: return SQLServerDialect.class; case MARIADB: return MySQL5Dialect.class; case HANA: return HANARowStoreDialect.class; case SQLITE: case NONE: default: break; } return null; }
/** * 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型. * 仅支持Oracle, H2, MySql, PostgreSql, SQLServer,如需更多数据库类型,请仿照此类自行编写。 */ public static String getDialect(DataSource dataSource) { String jdbcUrl = getJdbcUrlFromDataSource(dataSource); // 根据jdbc url判断dialect if (StringUtils.contains(jdbcUrl, ":h2:")) { return H2Dialect.class.getName(); } else if (StringUtils.contains(jdbcUrl, ":mysql:")) { return MySQL5InnoDBDialect.class.getName(); } else if (StringUtils.contains(jdbcUrl, ":oracle:")) { return Oracle10gDialect.class.getName(); } else if (StringUtils.contains(jdbcUrl, ":postgresql:")) { return PostgreSQL82Dialect.class.getName(); } else if (StringUtils.contains(jdbcUrl, ":sqlserver:")) { return SQLServer2008Dialect.class.getName(); } else { throw new IllegalArgumentException("Unknown Database of " + jdbcUrl); } }
private Class<? extends Dialect> getHibernateDialect(final PersistenceUnitContext context) { final ConnectionDialect dialect = context.getConnectionDialect(); switch (dialect) { case MSSQLSERVER: return SQLServerDialect.class; case MYSQL: return MySQL5InnoDBDialect.class; case POSTGRESQL: return PostgreSQL9Dialect.class; case ORACLE: return Oracle10gDialect.class; case H2: return H2Dialect.class; default: throw UnknownArgumentException.newInstance(ConnectionDialect.class, dialect); } }
@Test public void test() { List<LogbackRecorder> recorders = new LinkedList<>(); recorders.add(LogbackRecorder.forName("org.jboss.logging").reset().capture("ALL")); recorders.add(LogbackRecorder.forClass(Dialect.class).reset().capture("ALL")); recorders.add(LogbackRecorder.forClass(H2Dialect.class).reset().capture("ALL")); Map<Integer, String> registered = new LinkedHashMap<>(); new FixedH2Dialect() { @Override protected void registerColumnType(int code, String name) { registered.put(code, name); super.registerColumnType(code, name); } }; assertThat(registered.get(Types.FLOAT)).isEqualTo("real"); recorders.forEach(LogbackRecorder::release); }
@Test public void testGetDialect() throws SQLException { DataSource mockDataSource = mock(DataSource.class); Connection mockConnection = mock(Connection.class); DatabaseMetaData mockMetaData = mock(DatabaseMetaData.class); when(mockDataSource.getConnection()).thenReturn(mockConnection); when(mockConnection.getMetaData()).thenReturn(mockMetaData); when(mockMetaData.getURL()).thenReturn("jdbc:h2:file:~/test;AUTO_SERVER=TRUE"); String dialect = Hibernates.getDialect(mockDataSource); assertThat(dialect).isEqualTo(H2Dialect.class.getName()); when(mockMetaData.getURL()).thenReturn("jdbc:mysql://localhost:3306/test"); dialect = Hibernates.getDialect(mockDataSource); assertThat(dialect).isEqualTo(MySQL5InnoDBDialect.class.getName()); when(mockMetaData.getURL()).thenReturn("jdbc:oracle:thin:@127.0.0.1:1521:XE"); dialect = Hibernates.getDialect(mockDataSource); assertThat(dialect).isEqualTo(Oracle10gDialect.class.getName()); }
@Override public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) { String[] columns = criteriaQuery.findColumns(getPropiedad(), criteria); if (columns.length != 1) { throw new HibernateException( "NumberLike may only be used with single-column properties"); } SessionFactoryImplementor factory = criteriaQuery.getFactory(); if (factory.getDialect() instanceof H2Dialect) { return "cast(cast(" + columns[0] + " as int) as VARCHAR) " + "like ?"; } else { // XXX ver consistencia entre bases de datos return columns[0] + "::text like ?"; } }
@Override public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) { String[] columns = criteriaQuery.findColumns(getPath(), criteria); if (columns.length != 1) { throw new HibernateException( "Regex may only be used with single-column properties"); } SessionFactoryImplementor factory = criteriaQuery.getFactory(); if (factory.getDialect() instanceof H2Dialect) { return columns[0] + " regexp ?"; } else { // XXX ver consistencia entre bases de datos return columns[0] + " ~ ?"; } }
/** * Determine the Hibernate database dialect class for the given target database. * @param database the target database * @return the Hibernate database dialect class, or {@code null} if none found */ protected Class determineDatabaseDialectClass(Database database) { switch (database) { case DB2: return DB2Dialect.class; case DERBY: return DerbyDialect.class; case H2: return H2Dialect.class; case HSQL: return HSQLDialect.class; case INFORMIX: return InformixDialect.class; case MYSQL: return MySQLDialect.class; case ORACLE: return Oracle9iDialect.class; case POSTGRESQL: return PostgreSQLDialect.class; case SQL_SERVER: return SQLServerDialect.class; case SYBASE: return SybaseDialect.class; default: return null; } }
/** * Test provide and dispose. */ @Test public void testProvideDispose() { HibernateServiceRegistryFactory factory = new HibernateServiceRegistryFactory(); ServiceRegistry serviceRegistry = factory.provide(); Dialect d = new MetadataSources(serviceRegistry) .buildMetadata().getDatabase().getDialect(); Assert.assertTrue(d instanceof H2Dialect); // This shouldn't actually do anything, but is included here for // coverage. factory.dispose(serviceRegistry); }
/** * Test the application binder. */ @Test public void testBinder() { ResourceConfig config = new ResourceConfig(); config.register(TestFeature.class); // Make sure it's registered Assert.assertTrue(config.isRegistered(TestFeature.class)); // Create a fake application. ApplicationHandler handler = new ApplicationHandler(config); ServiceRegistry serviceRegistry = handler .getServiceLocator().getService(ServiceRegistry.class); Assert.assertNotNull(serviceRegistry); // Make sure it's reading from the same place. Dialect d = new MetadataSources(serviceRegistry) .buildMetadata().getDatabase().getDialect(); Assert.assertTrue(d instanceof H2Dialect); // Make sure it's a singleton... ServiceRegistry serviceRegistry2 = handler .getServiceLocator().getService(ServiceRegistry.class); Assert.assertSame(serviceRegistry, serviceRegistry2); }
@Test public void testGetDialect() throws SQLException { DataSource mockDataSource = Mockito.mock(DataSource.class); Connection mockConnection = Mockito.mock(Connection.class); DatabaseMetaData mockMetaData = Mockito.mock(DatabaseMetaData.class); Mockito.when(mockDataSource.getConnection()).thenReturn(mockConnection); Mockito.when(mockConnection.getMetaData()).thenReturn(mockMetaData); Mockito.when(mockMetaData.getURL()).thenReturn("jdbc:h2:file:~/test;AUTO_SERVER=TRUE"); String dialect = Hibernates.getDialect(mockDataSource); assertEquals(H2Dialect.class.getName(), dialect); Mockito.when(mockMetaData.getURL()).thenReturn("jdbc:mysql://localhost:3306/test"); dialect = Hibernates.getDialect(mockDataSource); assertEquals(MySQL5InnoDBDialect.class.getName(), dialect); Mockito.when(mockMetaData.getURL()).thenReturn("jdbc:oracle:thin:@127.0.0.1:1521:XE"); dialect = Hibernates.getDialect(mockDataSource); assertEquals(Oracle10gDialect.class.getName(), dialect); }
private Properties hibernateProperties() { Properties props = new Properties(); props.setProperty("hibernate.hbm2ddl.auto", "create"); props.setProperty("hibernate.dialect", H2Dialect.class.getName()); props.setProperty("hibernate.globally_quoted_identifiers", "true"); return props; }
private Properties hibernateProperties() { Properties props = new Properties(); props.setProperty("hibernate.dialect", H2Dialect.class.getName()); props.setProperty("hibernate.hbm2ddl.auto", "create"); props.setProperty("hibernate.globally_quoted_identifiers", "true"); return props; }
H2EntryDatabase(File dataDir) { if (factory == null) { factory = new HibernateBuilder().confDriver(Driver.class).confDialect(H2Dialect.class) .confConnection("jdbc:h2:file:" + dataDir.getAbsolutePath() + "/journalEntries") .buildServiceRegistry().build(); } s = factory.openSession(); createTable(); }
@Test public void initApplicationContext() throws Exception { assertNotNull(repositoryService); assertNotNull(sessionFactory); createSQLSchema("./target/h2-schema.sql", H2Dialect.class.getName()); createSQLSchema("./target/sqlserver-schema.sql", UnicodeSQLServer2008Dialect.class.getName()); createSQLSchema("./target/mysql-schema.sql", MidPointMySQLDialect.class.getName()); createSQLSchema("./target/oracle-schema.sql", Oracle10gDialect.class.getName()); createSQLSchema("./target/postgresql-schema.sql", MidPointPostgreSQLDialect.class.getName()); }
/** * This method checks actual configuration and updates if it's in embedded mode. (build correct * jdbc url, sets default username and password, driver class and hibernate properties) * * @param config * @throws RepositoryServiceFactoryException * this exception is thrown if baseDir defined in configuration xml doesn't exist or it's not a directory */ private void normalizeConfiguration(SqlRepositoryConfiguration config) throws RepositoryServiceFactoryException { if (!config.isEmbedded()) { return; } StringBuilder jdbcUrl = new StringBuilder(prepareJdbcUrlPrefix(config)); jdbcUrl.append(";MVCC=FALSE"); // turn off MVCC, revert to table locking //jdbcUrl.append(";MV_STORE=FALSE"); // use old page store //disable database closing on exit. By default, a database is closed when the last connection is closed. jdbcUrl.append(";DB_CLOSE_ON_EXIT=FALSE"); //Both read locks and write locks are kept until the transaction commits. jdbcUrl.append(";LOCK_MODE=1"); //fix for "Timeout trying to lock table [50200-XXX]" in H2 database. Default value is 1000ms. jdbcUrl.append(";LOCK_TIMEOUT=100"); // experimental setting - let's resolve locking conflicts by midPoint itself //we want to store blob datas (full xml object right in table (it's always only a few kb) jdbcUrl.append(";MAX_LENGTH_INPLACE_LOB=10240"); config.setJdbcUrl(jdbcUrl.toString()); LOGGER.trace("JDBC url created: {}", new Object[]{config.getJdbcUrl()}); config.setJdbcUsername("sa"); config.setJdbcPassword(""); config.setDriverClassName(Driver.class.getName()); config.setHibernateDialect(H2Dialect.class.getName()); config.setHibernateHbm2ddl("update"); }
public void testLoadSaveRepository() throws Exception { Class.forName("org.h2.Driver").newInstance(); Connection theConnection = null; try { theConnection = DriverManager.getConnection("jdbc:h2:mem:dname", "sa", ""); Class theHibernateDialect = H2Dialect.class; String theModelResource = "/de/erdesignerng/test/io/repository/examplemodel.mxm"; String theNewFile = RepositioryHelper.performRepositorySaveAndLoad(theModelResource, theHibernateDialect, theConnection); String theOriginalFile = IOUtils.toString(getClass().getResourceAsStream(theModelResource)); assertTrue(compareStrings(theOriginalFile, theNewFile)); } finally { if (theConnection != null) { theConnection.createStatement().execute("SHUTDOWN"); theConnection.close(); } } }
private String extractData(Clob clob) throws Throwable { if ( getDialect() instanceof H2Dialect ) { return clob.getSubString( 1, ( int ) clob.length() ); } else { char[] data = new char[ (int) clob.length() ]; clob.getCharacterStream().read( data ); return new String( data ); } }
@Test public void generateSchemas() { createSQLSchema("./target/h2-schema.sql", H2Dialect.class.getName()); createSQLSchema("./target/sqlserver-schema.sql", UnicodeSQLServer2008Dialect.class.getName()); createSQLSchema("./target/mysql-schema.sql", MidPointMySQLDialect.class.getName()); createSQLSchema("./target/oracle-schema.sql", MidPointOracleDialect.class.getName()); createSQLSchema("./target/postgresql-schema.sql", MidPointPostgreSQLDialect.class.getName()); }
@Bean public Map<String, Object> jpaProperties() { Map<String, Object> props = new HashMap<String, Object>(); props.put("hibernate.dialect", H2Dialect.class.getName()); // props.put("hibernate.cache.provider_class", HashtableCacheProvider.class.getName()); return props; }
/** * Tests whether physical table names are transformed to lowercase. * * @throws SQLException */ @Test public void testPhysicalTableNamesAreLowercase() throws SQLException { String className = "SomeCamelCaseClass"; String expectedPhysicalName = "somecamelcaseclass"; Dialect dialect = new H2Dialect(); assertExpectedPhysicalTableName(dialect, className, expectedPhysicalName); }
/** * Tests whether physical column are transformed to lowercase. * * @throws SQLException */ @Test public void testPhysicalColumnNamesAreLowercase() throws SQLException { String columnName = "SomeCamelCaseColumn"; String expectedPhysicalName = "somecamelcasecolumn"; Dialect dialect = new H2Dialect(); assertExpectedPhysicalColumnName(dialect, columnName, expectedPhysicalName); }
/** * Tests whether the table prefix is being respected. * * @throws SQLException */ @Test public void testIfTablePrefixIsBeingUsed() throws SQLException { String tablePrefix = "TBL_"; namingStrategy.setTablePrefix(tablePrefix); String className = "SomeCamelCaseClass"; String expectedPhysicalName = "tbl_somecamelcaseclass"; Dialect dialect = new H2Dialect(); assertExpectedPhysicalTableName(dialect, className, expectedPhysicalName); }
/** * Tests whether everything is fine, if table prefix is null. * * @throws SQLException */ @Test public void testIfTablePrefixIsNull() throws SQLException { String tablePrefix = null; namingStrategy.setTablePrefix(tablePrefix); String className = "SomeCamelCaseClass"; String expectedPhysicalName = "somecamelcaseclass"; Dialect dialect = new H2Dialect(); assertExpectedPhysicalTableName(dialect, className, expectedPhysicalName); }
/** * Tests whether everything is fine, if table prefix is empty. * * @throws SQLException */ @Test public void testIfTablePrefixIsEmpty() throws SQLException { String tablePrefix = ""; namingStrategy.setTablePrefix(tablePrefix); String className = "SomeCamelCaseClass"; String expectedPhysicalName = "somecamelcaseclass"; Dialect dialect = new H2Dialect(); assertExpectedPhysicalTableName(dialect, className, expectedPhysicalName); }
/** * 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型. * 仅支持Oracle, H2, MySql,如需更多数据库类型,请仿照此类自行编写。 */ public static String getDialect(DataSource dataSource) { String jdbcUrl = getJdbcUrlFromDataSource(dataSource); // 根据jdbc url判断dialect if (StringUtils.contains(jdbcUrl, ":h2:")) { return H2Dialect.class.getName(); } else if (StringUtils.contains(jdbcUrl, ":mysql:")) { return MySQL5InnoDBDialect.class.getName(); } else if (StringUtils.contains(jdbcUrl, ":oracle:")) { return Oracle10gDialect.class.getName(); } else { throw new IllegalArgumentException("Unknown Database of " + jdbcUrl); } }
public static void configure(org.hibernate.cfg.Configuration configuration) { configuration.setProperty(Environment.CONNECTION_PROVIDER, AppConnectionProvider.class.getName()); configuration.setProperty(CURRENT_SESSION_CONTEXT_CLASS, "thread"); configuration.setProperty(DIALECT, H2Dialect.class.getName()); configuration.setProperty(HBM2DDL_AUTO, "create-drop"); configuration.setProperty(USE_SECOND_LEVEL_CACHE, Boolean.FALSE.toString()); configuration.setProperty(USE_QUERY_CACHE, Boolean.FALSE.toString()); configuration.setProperty(SHOW_SQL, Boolean.TRUE.toString()); configuration.setProperty(FORMAT_SQL, Boolean.TRUE.toString()); addAnnotatedClasses(configuration); }