下面列出了怎么用org.hibernate.internal.SessionImpl的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
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();
}
}
}
}
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 + ";");
}
/**
* 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;
}
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();
}
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();
}
/**
* 数据库类型
* @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;
}
/**
* 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);
}
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;
}
/**
* 数据库类型
* @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;
}
@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();
}
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;
}
/**
* 获取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;
}
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;
}
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;
}
/**
* 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);
}
@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();
}
/**
* 获取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;
}
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());
}
}
@Override
public Connection getConnection() {
SessionImpl session = (SessionImpl)entityManager.unwrap(Session.class);
return session.connection();
}