类org.hibernate.internal.SessionImpl源码实例Demo

下面列出了怎么用org.hibernate.internal.SessionImpl的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: judgels   文件: AbstractJudgelsDataMigrator.java
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();
}
 
源代码2 项目: judgels   文件: SandalphonDataMigrator.java
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();
            }
        }
    }
}
 
源代码3 项目: judgels   文件: SandalphonDataMigrator.java
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 + ";");
}
 
源代码4 项目: database-rider   文件: DataSetProcessor.java
/**
 * 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;
}
 
源代码5 项目: database-rider   文件: EntityManagerProvider.java
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();
}
 
源代码6 项目: database-rider   文件: EntityManagerProvider.java
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();
}
 
源代码7 项目: jeewx   文件: DbTableUtil.java
/**
 * 数据库类型
 * @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;
}
 
源代码8 项目: cia   文件: AuditableAspectConfiguration.java
/**
 * 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();
}
 
@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);
}
 
源代码10 项目: jeecg   文件: DbTableUtil.java
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;
}
 
源代码11 项目: jeecg   文件: DbTableUtil.java
/**
 * 数据库类型
 * @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;
}
 
源代码12 项目: quarkus   文件: CRUDResource.java
@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();
}
 
源代码13 项目: database-rider   文件: DeltaspikeIt.java
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;

}
 
源代码14 项目: jeewx   文件: DbTableUtil.java
/**
 * 获取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;
}
 
源代码15 项目: jeewx   文件: DbTableUtil.java
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;
}
 
源代码16 项目: axelor-open-suite   文件: FilterSqlService.java
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;
  }
 
源代码17 项目: pnc   文件: AbstractModelTest.java
/**
 * 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);
}
 
源代码18 项目: jadira   文件: TestPersistentDateTime.java
@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();
}
 
源代码19 项目: jeecg   文件: DbTableUtil.java
/**
 * 获取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;
}
 
源代码20 项目: judgels   文件: SandalphonDataMigrator.java
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());
    }
}
 
源代码21 项目: javers   文件: JpaHibernateConnectionProvider.java
@Override
public Connection getConnection() {

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

    return session.connection();
}
 
 类所在包
 同包方法