org.hibernate.internal.SessionImpl Java Examples

The following examples show how to use org.hibernate.internal.SessionImpl. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DbTableUtil.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * 数据库类型
 * @param session
 * @return
 */

public static String getDataType(Session session){
	String dataType="MYSQL";
	String dialect = ((SessionImpl)session).getFactory().getDialect()
	.getClass().getName();
	if (dialect.equals("org.hibernate.dialect.MySQLDialect")) {
		dataType="MYSQL";
	}else if (dialect.contains("Oracle")) {
		dataType="ORACLE";
	}else if (dialect.equals("org.hibernate.dialect.PostgreSQLDialect")) {
		dataType = "POSTGRESQL";
	}else if (dialect.equals("org.hibernate.dialect.SQLServerDialect")) {
		dataType="SQLSERVER";
	}
	else if (dialect.equals("org.jeecgframework.core.common.hibernate.dialect.MySQLServer2008Dialect")) {
		dataType="SQLSERVER";
	}
	return dataType;
}
 
Example #2
Source File: SandalphonDataMigrator.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
private void migrateV2toV3() throws SQLException {
    SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);
    Connection connection = session.getJdbcConnectionAccess().obtainConnection();

    String jidCacheTable = "sandalphon_jid_cache";
    Statement statement = connection.createStatement();
    String jidCacheQuery = "SELECT * FROM " + jidCacheTable + ";";
    ResultSet resultSet = statement.executeQuery(jidCacheQuery);

    while (resultSet.next()) {
        long id = resultSet.getLong("id");
        String jid = resultSet.getString("jid");
        String displayName = resultSet.getString("displayName");

        if (jid.startsWith("JIDUSER")) {
            if (displayName.contains("(")) {
                displayName = displayName.substring(0, displayName.indexOf("(") - 1);

                PreparedStatement preparedStatement = connection.prepareStatement("UPDATE " + jidCacheTable + " SET displayName= ? WHERE id=" + id + ";");
                preparedStatement.setString(1, displayName);
                preparedStatement.executeUpdate();
            }
        }
    }
}
 
Example #3
Source File: SandalphonDataMigrator.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
private void migrateV1toV2() throws SQLException {
    SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);
    Connection connection = session.getJdbcConnectionAccess().obtainConnection();

    String programmingSubmissionTable = "sandalphon_submission_programming";
    String newProgrammingSubmissionTable = "sandalphon_programming_submission";
    String bundleSubmissionTable = "sandalphon_submission_bundle";
    String newBundleSubmissionTable = "sandalphon_bundle_submission";
    Statement statement = connection.createStatement();

    statement.execute("ALTER TABLE " + programmingSubmissionTable + " CHANGE contestJid containerJid VARCHAR(255);");
    statement.execute("ALTER TABLE " + bundleSubmissionTable + " CHANGE contestJid containerJid VARCHAR(255);");

    statement.execute("DROP TABLE " + newProgrammingSubmissionTable + ";");
    statement.execute("DROP TABLE " + newBundleSubmissionTable + ";");

    statement.execute("RENAME TABLE " + programmingSubmissionTable + " TO " + newProgrammingSubmissionTable + ";");
    statement.execute("RENAME TABLE " + bundleSubmissionTable + " TO " + newBundleSubmissionTable + ";");
}
 
Example #4
Source File: DbTableUtil.java    From jeecg with Apache License 2.0 6 votes vote down vote up
public static DbTableHandleI getTableHandle(Session  session) {
	DbTableHandleI dbTableHandle = null;
	String dialect = ((SessionImpl)session).getFactory().getDialect().getClass().getName();
	if (dialect.equals("org.hibernate.dialect.MySQLDialect")) {
		dbTableHandle = new DbTableMysqlHandleImpl();
	}else if (dialect.contains("Oracle")) {
		dbTableHandle = new DbTableOracleHandleImpl();
	}else if (dialect.equals("org.hibernate.dialect.PostgreSQLDialect")) {
		dbTableHandle = new DbTablePostgresHandleImpl();
	}else if (dialect.equals("org.hibernate.dialect.SQLServerDialect")) {
		dbTableHandle = new TableSQLServerHandleImpl();
	}
	else if (dialect.equals("org.jeecgframework.core.common.hibernate.dialect.MySQLServer2008Dialect")) {
		dbTableHandle = new TableSQLServerHandleImpl();
	}
	return dbTableHandle;
}
 
Example #5
Source File: DataSetProcessor.java    From database-rider with Apache License 2.0 6 votes vote down vote up
/**
 * unfortunately there is no standard way to get jdbc connection from JPA entity manager
 *
 * @return JDBC connection
 */
private Connection createConnection(String entityManagerBeanName) {
    try {
        if (isJta()) {
            return jtaConnectionHolder.get().getConnection(entityManagerBeanName);
        } else {
            if (isHibernatePresentOnClasspath() && entityManager.getDelegate() instanceof Session) {
                connection = ((SessionImpl) entityManager.unwrap(Session.class)).connection();
            } else {
                /**
                 * see here:http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager
                 */
                EntityTransaction tx = this.entityManager.getTransaction();
                tx.begin();
                connection = entityManager.unwrap(Connection.class);
                tx.commit();
            }

        }
    } catch (Exception e) {
        throw new RuntimeException("Could not create database connection", e);
    }

    return connection;
}
 
Example #6
Source File: EntityManagerProvider.java    From database-rider with Apache License 2.0 6 votes vote down vote up
private void init(String unitName) {
    if (emf == null) {
        log.debug("creating emf for unit {}", unitName);
        Map<String,String> dbConfig = getDbPropertyConfig();
        log.debug("using dbConfig '{}' to create emf", dbConfig);
        emf = dbConfig == null ? Persistence.createEntityManagerFactory(unitName) : Persistence.createEntityManagerFactory(unitName, dbConfig);
        em =  emf.createEntityManager();
        tx = em.getTransaction();
        if (isHibernateOnClasspath() && em.getDelegate() instanceof Session) {
            conn = ((SessionImpl) em.unwrap(Session.class)).connection();
        } else{
            /**
             * see here:http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager
             */
            tx.begin();
            conn = em.unwrap(Connection.class);
            tx.commit();
        }

    }
    emf.getCache().evictAll();
}
 
Example #7
Source File: EntityManagerProvider.java    From database-rider with Apache License 2.0 6 votes vote down vote up
private void init(String unitName) {
    if (emf == null) {
        log.debug("creating emf for unit {}", unitName);
        Map<String,String> dbConfig = getDbPropertyConfig();
        log.debug("using dbConfig '{}' to create emf", dbConfig);
        emf = dbConfig == null ? Persistence.createEntityManagerFactory(unitName) : Persistence.createEntityManagerFactory(unitName, dbConfig);
        em =  emf.createEntityManager();
        tx = em.getTransaction();
        if (isHibernateOnClasspath() && em.getDelegate() instanceof Session) {
            conn = ((SessionImpl) em.unwrap(Session.class)).connection();
        } else{
            /**
             * see here:http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager
             */
            tx.begin();
            conn = em.unwrap(Connection.class);
            tx.commit();
        }

    }
    emf.getCache().evictAll();
}
 
Example #8
Source File: QuarkusJpaConnectionProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public JpaConnectionProvider create(KeycloakSession session) {
    logger.trace("Create QuarkusJpaConnectionProvider");
    EntityManager em;
    if (!jtaEnabled) {
        logger.trace("enlisting EntityManager in JpaKeycloakTransaction");
        em = emf.createEntityManager();
        try {
            SessionImpl.class.cast(em).connection().setAutoCommit(false);
        } catch (SQLException cause) {
            throw new RuntimeException(cause);
        }
    } else {

        em = emf.createEntityManager(SynchronizationType.SYNCHRONIZED);
    }
    em = PersistenceExceptionConverter.create(em);
    if (!jtaEnabled) session.getTransactionManager().enlist(new JpaKeycloakTransaction(em));
    return new DefaultJpaConnectionProvider(em);
}
 
Example #9
Source File: AbstractJudgelsDataMigrator.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
private void checkTable() throws SQLException {
    String tableName = "judgels_data_version";

    SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);
    Connection connection = session.getJdbcConnectionAccess().obtainConnection();
    Statement statement = connection.createStatement();

    ResultSet resultSet = statement.executeQuery("SHOW TABLES LIKE '" + tableName + "';");

    if (!resultSet.next()) {
        statement.execute("CREATE TABLE " + tableName + "("
                + "id bigint(20) NOT NULL AUTO_INCREMENT,"
                + "version bigint(20) NOT NULL,"
                + "PRIMARY KEY (id)"
                + ");");
        statement.executeUpdate("INSERT INTO `judgels_data_version` (`version`) VALUES (" + getLatestDataVersion() + ");");
    }

    resultSet.close();
    statement.close();
}
 
Example #10
Source File: DbTableUtil.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 数据库类型
 * @param session
 * @return
 */

public static String getDataType(Session session){
	String dataType="MYSQL";
	String dialect = ((SessionImpl)session).getFactory().getDialect()
	.getClass().getName();
	if (dialect.equals("org.hibernate.dialect.MySQLDialect")) {
		dataType="MYSQL";
	}else if (dialect.contains("Oracle")) {
		dataType="ORACLE";
	}else if (dialect.equals("org.hibernate.dialect.PostgreSQLDialect")) {
		dataType = "POSTGRESQL";
	}else if (dialect.equals("org.hibernate.dialect.SQLServerDialect")) {
		dataType="SQLSERVER";
	}
	return dataType;
}
 
Example #11
Source File: AuditableAspectConfiguration.java    From cia with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the javers.
 *
 * @param txManager the tx manager
 * @return the javers
 */
@Bean
public Javers getJavers(final PlatformTransactionManager txManager) {
	final JaversSqlRepository sqlRepository = SqlRepositoryBuilder.sqlRepository()
			.withConnectionProvider(new ConnectionProvider() {

				@Override
				public Connection getConnection() {
					final SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);

					return session.connection();
				}
			}).withDialect(DialectName.POSTGRES).build();

	return TransactionalJaversBuilder.javers().withTxManager(txManager)
			.withObjectAccessHook(new HibernateUnproxyObjectAccessHook()).registerJaversRepository(sqlRepository)
			.withMappingStyle(MappingStyle.BEAN).build();
}
 
Example #12
Source File: DbTableUtil.java    From jeewx with Apache License 2.0 5 votes vote down vote up
public static DbTableHandleI getTableHandle(Session  session) {
	DbTableHandleI dbTableHandle = null;
	String dialect = ((SessionImpl)session).getFactory().getDialect()
			.getClass().getName();
	if (dialect.equals("org.hibernate.dialect.MySQLDialect")) {
		dbTableHandle = new DbTableMysqlHandleImpl();
	}else if (dialect.contains("Oracle")) {
		dbTableHandle = new DbTableOracleHandleImpl();
	}else if (dialect.equals("org.hibernate.dialect.PostgreSQLDialect")) {
		dbTableHandle = new DbTablePostgresHandleImpl();
	}else if (dialect.equals("org.hibernate.dialect.SQLServerDialect")) {
		dbTableHandle = new TableSQLServerHandleImpl();
	}
	return dbTableHandle;
}
 
Example #13
Source File: DbTableUtil.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
 * 获取DB 维护表的工具类
 * @return
 */
public static DbTableServiceI getTableUtil(Session  session) {
	DbTableServiceI tableUtil = null;
	String dialect = ((SessionImpl)session).getFactory().getDialect()
			.getClass().getName();
	if (dialect.equals("org.hibernate.dialect.MySQLDialect")) {
		tableUtil = new DbTableServiceMysqlImpl();
	}
	return tableUtil;
}
 
Example #14
Source File: TestPersistentDateTime.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testRead() throws SQLException {

	SessionImpl session = (SessionImpl)(factory.createEntityManager().getDelegate());

	Connection conn = session.getJdbcConnectionAccess().obtainConnection();

	String insertTableSQL = "INSERT INTO dateTime"
			+ "(ID, NAME, DATETIME) VALUES"
			+ "(?,?,?)";
	    	
    for (int i = 0; i < dateTimes.length; i++) {

    	PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
    	preparedStatement.setInt(1, i);
    	preparedStatement.setString(2, "test_" + i);
    	preparedStatement.setTimestamp(3, dateTimes[i] == null ? null : new java.sql.Timestamp(dateTimes[i].getMillis()));
    	preparedStatement.executeUpdate();
    }
    conn.commit();

    for (int i = 0; i < dateTimes.length; i++) {

        JodaDateTimeHolder item = find(JodaDateTimeHolder.class, i);

        assertNotNull(item);
        assertEquals(i, item.getId());
        assertEquals("test_" + i, item.getName());
        if (dateTimes[i] == null) {
            assertNull(item.getDateTime());
        } else {
            assertEquals(dateTimes[i].withZone(DateTimeZone.UTC).toString(), item.getDateTime().toString());
        }
    }

    verifyDatabaseTable();
}
 
Example #15
Source File: AbstractModelTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
/**
 * Inserts data into database from the dbunit XML file
 * 
 * @param em Entity manager
 * @param datasetPath Path to DBunit dataset file
 * @throws Exception Thrown in case of any error during the operation
 */
protected void initDatabaseUsingDataset(EntityManager em, String datasetPath) throws Exception {
    IDatabaseConnection connection = new DatabaseConnection(em.unwrap(SessionImpl.class).connection());
    connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());
    FlatXmlDataSetBuilder flatXmlDataSetBuilder = new FlatXmlDataSetBuilder();
    flatXmlDataSetBuilder.setColumnSensing(true);
    InputStream dataSetStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(datasetPath);
    IDataSet dataSet = flatXmlDataSetBuilder.build(dataSetStream);
    DatabaseOperation.INSERT.execute(connection, dataSet);
}
 
Example #16
Source File: FilterSqlService.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getColumn(String model, String field) {

    SessionImpl sessionImpl = (SessionImpl) JPA.em().getDelegate();
    @SuppressWarnings("deprecation")
    AbstractEntityPersister aep =
        ((AbstractEntityPersister)
            sessionImpl.getSession().getSessionFactory().getClassMetadata(model));
    String[] columns = aep.getPropertyColumnNames(field);
    if (columns != null && columns.length > 0) {
      return columns[0];
    }

    return null;
  }
 
Example #17
Source File: DbTableUtil.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
 * 获取DB 维护表的工具类
 * @return
 */
public static DbTableServiceI getTableUtil(Session  session) {
	DbTableServiceI tableUtil = null;
	String dialect = ((SessionImpl)session).getFactory().getDialect()
			.getClass().getName();
	if (dialect.equals("org.hibernate.dialect.MySQLDialect")) {
		tableUtil = new DbTableServiceMysqlImpl();
	}
	return tableUtil;
}
 
Example #18
Source File: DeltaspikeIt.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private Connection createConnection() {
    /* eclipselink
   entityManager.getTransaction().begin();
    Connection connection = entityManager.unwrap(java.sql.Connection.class);
    entityManager.getTransaction().commit();*/
    Connection connection = ((SessionImpl) entityManager.unwrap(Session.class)).connection();
    assertNotNull(connection);
    return connection;

}
 
Example #19
Source File: CRUDResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/timestamps")
public String checkCachingState() {
    SessionImpl sessionImpl = em.unwrap(SessionImpl.class);
    TimestampsCache timestampsCache = sessionImpl.getSessionFactory().getCache().getTimestampsCache();
    return timestampsCache.getClass().getName();
}
 
Example #20
Source File: SandalphonDataMigrator.java    From judgels with GNU General Public License v2.0 4 votes vote down vote up
private void migrateV4toV5() throws SQLException {
    SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);
    Connection connection = session.getJdbcConnectionAccess().obtainConnection();

    String[] tables = {
            "activity_log",
            "bundle_grading",
            "bundle_submission",
            "client",
            "grader",
            "lesson",
            "lesson_partner",
            "problem",
            "problem_partner",
            "programming_grading",
            "programming_submission",
            "jid_cache",
            "user",
    };

    Statement statement = connection.createStatement();

    for (String table : tables) {
        StringBuilder sb = new StringBuilder();
        sb.append("ALTER TABLE sandalphon_").append(table)
                .append(" ADD COLUMN createdAt DATETIME(3) NOT NULL DEFAULT NOW(3), ")
                .append(" ADD COLUMN updatedAt DATETIME(3) NOT NULL DEFAULT NOW(3), ")
                .append(" CHANGE COLUMN ipCreate createdIp VARCHAR(255), ")
                .append(" CHANGE COLUMN ipUpdate updatedIp VARCHAR(255), ")
                .append(" CHANGE COLUMN userCreate createdBy VARCHAR(255), ")
                .append(" CHANGE COLUMN userUpdate updatedBy VARCHAR(255);");
        statement.execute(sb.toString());

        sb = new StringBuilder();
        sb.append("UPDATE sandalphon_").append(table).append(" SET ")
                .append("createdAt=FROM_UNIXTIME(timeCreate * 0.001), ")
                .append("updatedAt=FROM_UNIXTIME(timeUpdate * 0.001);");
        statement.execute(sb.toString());

        sb = new StringBuilder();
        sb.append("ALTER TABLE sandalphon_").append(table)
                .append(" DROP COLUMN timeCreate, ")
                .append(" DROP COLUMN timeUpdate;");
        statement.execute(sb.toString());

        sb = new StringBuilder();
        sb.append("ALTER TABLE sandalphon_").append(table)
                .append(" MODIFY COLUMN createdAt DATETIME(3) NOT NULL, ")
                .append(" MODIFY COLUMN updatedAt DATETIME(3) NOT NULL; ");
        statement.execute(sb.toString());
    }
}
 
Example #21
Source File: JpaHibernateConnectionProvider.java    From javers with Apache License 2.0 3 votes vote down vote up
@Override
public Connection getConnection() {

    SessionImpl session =  (SessionImpl)entityManager.unwrap(Session.class);

    return session.connection();
}