下面列出了怎么用org.hibernate.engine.jdbc.spi.JdbcServices的API类实例代码及写法,或者点击链接到github查看源代码。
@SuppressWarnings({"unchecked", "UnusedParameters"})
private static void applyRelationalConstraints(ValidatorFactory factory, ActivationContext activationContext) {
final ConfigurationService cfgService = activationContext.getServiceRegistry().getService( ConfigurationService.class );
if ( !cfgService.getSetting( BeanValidationIntegrator.APPLY_CONSTRAINTS, StandardConverters.BOOLEAN, true ) ) {
LOG.debug( "Skipping application of relational constraints from legacy Hibernate Validator" );
return;
}
final Set<ValidationMode> modes = activationContext.getValidationModes();
if ( ! ( modes.contains( ValidationMode.DDL ) || modes.contains( ValidationMode.AUTO ) ) ) {
return;
}
applyRelationalConstraints(
factory,
activationContext.getMetadata().getEntityBindings(),
cfgService.getSettings(),
activationContext.getServiceRegistry().getService( JdbcServices.class ).getDialect(),
new ClassLoaderAccessImpl(
null,
activationContext.getServiceRegistry().getService( ClassLoaderService.class )
)
);
}
/**
* Modify the SQL, adding lock hints and comments, if necessary
*/
protected String preprocessSQL(
String sql,
QueryParameters parameters,
SessionFactoryImplementor sessionFactory,
List<AfterLoadAction> afterLoadActions) throws HibernateException {
Dialect dialect = sessionFactory.getServiceRegistry().getService( JdbcServices.class ).getDialect();
sql = applyLocks( sql, parameters, dialect, afterLoadActions );
sql = dialect.addSqlHintOrComment(
sql,
parameters,
sessionFactory.getSessionFactoryOptions().isCommentsEnabled()
);
return processDistinctKeyword( sql, parameters );
}
private ResultSet wrapResultSetIfEnabled(final ResultSet rs, final SharedSessionContractImplementor session) {
if ( session.getFactory().getSessionFactoryOptions().isWrapResultSetsEnabled() ) {
try {
LOG.debugf( "Wrapping result set [%s]", rs );
return session.getFactory()
.getServiceRegistry()
.getService( JdbcServices.class )
.getResultSetWrapper().wrap( rs, retrieveColumnNameToIndexCache( rs ) );
}
catch (SQLException e) {
LOG.unableToWrapResultSet( e );
return rs;
}
}
else {
return rs;
}
}
private ResultSet wrapResultSetIfEnabled(final ResultSet rs, final SharedSessionContractImplementor session) {
if ( session.getFactory().getSessionFactoryOptions().isWrapResultSetsEnabled() ) {
try {
if ( log.isDebugEnabled() ) {
log.debugf( "Wrapping result set [%s]", rs );
}
ResultSetWrapper wrapper = session.getFactory()
.getServiceRegistry()
.getService( JdbcServices.class )
.getResultSetWrapper();
// synchronized to avoid multi-thread access issues
// Apparently the comment about this needing synchronization was introduced when AbstractLoadPlanBasedLoader first appeared
// in version control. Would need to investigate if it's still needed?
synchronized ( this ) {
return wrapper.wrap( rs, retreiveColumnNameToIndexCache( rs ) );
}
}
catch(SQLException e) {
log.unableToWrapResultSet( e );
return rs;
}
}
else {
return rs;
}
}
/**
* Constructs a JdbcCoordinatorImpl
*
* @param userSuppliedConnection The user supplied connection (may be null)
*/
public JdbcCoordinatorImpl(
Connection userSuppliedConnection,
JdbcSessionOwner owner) {
this.isUserSuppliedConnection = userSuppliedConnection != null;
final ResourceRegistry resourceRegistry = new ResourceRegistryStandardImpl(
owner.getJdbcSessionContext().getObserver()
);
if ( isUserSuppliedConnection ) {
this.logicalConnection = new LogicalConnectionProvidedImpl( userSuppliedConnection, resourceRegistry );
}
else {
this.logicalConnection = new LogicalConnectionManagedImpl(
owner.getJdbcConnectionAccess(),
owner.getJdbcSessionContext(),
resourceRegistry
);
}
this.owner = owner;
this.exceptionHelper = owner.getJdbcSessionContext()
.getServiceRegistry()
.getService( JdbcServices.class )
.getSqlExceptionHelper();
}
protected AbstractBatchImpl(BatchKey key, JdbcCoordinator jdbcCoordinator) {
if ( key == null ) {
throw new IllegalArgumentException( "batch key cannot be null" );
}
if ( jdbcCoordinator == null ) {
throw new IllegalArgumentException( "JDBC coordinator cannot be null" );
}
this.key = key;
this.jdbcCoordinator = jdbcCoordinator;
final JdbcServices jdbcServices = jdbcCoordinator.getJdbcSessionOwner()
.getJdbcSessionContext()
.getServiceRegistry()
.getService( JdbcServices.class );
this.sqlStatementLogger = jdbcServices.getSqlStatementLogger();
this.sqlExceptionHelper = jdbcServices.getSqlExceptionHelper();
}
@Override
public Blob mergeBlob(Blob original, Blob target, SharedSessionContractImplementor session) {
if ( original == null && target == null ) {
return null;
}
try {
final LobCreator lobCreator = session.getFactory().getServiceRegistry().getService( JdbcServices.class ).getLobCreator(
session
);
return original == null
? lobCreator.createBlob( ArrayHelper.EMPTY_BYTE_ARRAY )
: lobCreator.createBlob( original.getBinaryStream(), original.length() );
}
catch (SQLException e) {
throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge BLOB data" );
}
}
@Override
protected IdTableInfoImpl buildIdTableInfo(
PersistentClass entityBinding,
Table idTable,
JdbcServices jdbcServices,
MetadataImplementor metadata,
PreparationContext context) {
return new IdTableInfoImpl(
jdbcServices.getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
idTable.getQualifiedTableName(),
jdbcServices.getJdbcEnvironment().getDialect()
),
buildIdTableCreateStatement( idTable, jdbcServices, metadata ),
buildIdTableDropStatement( idTable, jdbcServices )
);
}
@Override
public void execute(Connection connection) {
try {
Statement statement = connection.createStatement();
try {
statement.executeUpdate( logStatement(factory, idTableInfo.getIdTableCreationStatement()) );
factory.getServiceRegistry()
.getService( JdbcServices.class )
.getSqlExceptionHelper()
.handleAndClearWarnings( statement, WARNING_HANDLER );
}
finally {
try {
statement.close();
}
catch( Throwable ignore ) {
// ignore
}
}
}
catch( Exception e ) {
log.debug( "unable to create temporary id table [" + e.getMessage() + "]" );
}
}
@Override
public void execute(Connection connection) {
try {
Statement statement = connection.createStatement();
try {
statement.executeUpdate( logStatement( factory, idTableInfo.getIdTableDropStatement() ) );
factory.getServiceRegistry()
.getService( JdbcServices.class )
.getSqlExceptionHelper()
.handleAndClearWarnings( statement, WARNING_HANDLER );
}
finally {
try {
statement.close();
}
catch( Throwable ignore ) {
// ignore
}
}
}
catch( Exception e ) {
log.warn( "unable to drop temporary id table after use [" + e.getMessage() + "]" );
}
}
@Override
protected IdTableInfoImpl buildIdTableInfo(
PersistentClass entityBinding,
Table idTable,
JdbcServices jdbcServices,
MetadataImplementor metadata,
PreparationContextImpl context) {
context.creationStatements.add( buildIdTableCreateStatement( idTable, jdbcServices, metadata ) );
if ( dropIdTables ) {
context.dropStatements.add( buildIdTableDropStatement( idTable, jdbcServices ) );
}
final String renderedName = jdbcServices.getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
idTable.getQualifiedTableName(),
jdbcServices.getJdbcEnvironment().getDialect()
);
return new IdTableInfoImpl( renderedName );
}
public InlineIdsSubSelectValuesListUpdateHandlerImpl(
SessionFactoryImplementor factory,
HqlSqlWalker walker) {
super( factory, walker );
Dialect dialect = factory().getServiceRegistry().getService( JdbcServices.class ).getDialect();
if ( !dialect.supportsRowValueConstructorSyntaxInInList() ) {
throw new UnsupportedOperationException(
"The " + getClass().getSimpleName() +
" can only be used with Dialects that support IN clause row-value expressions (for composite identifiers)!"
);
}
if ( !dialect.supportsValuesList() ) {
throw new UnsupportedOperationException(
"The " + getClass().getSimpleName() +
" can only be used with Dialects that support VALUES lists!"
);
}
}
public InlineIdsSubSelectValuesListDeleteHandlerImpl(
SessionFactoryImplementor factory,
HqlSqlWalker walker) {
super( factory, walker );
Dialect dialect = factory().getServiceRegistry().getService( JdbcServices.class ).getDialect();
if ( !dialect.supportsRowValueConstructorSyntaxInInList() ) {
throw new UnsupportedOperationException(
"The " + getClass().getSimpleName() +
" can only be used with Dialects that support IN clause row-value expressions (for composite identifiers)!"
);
}
if ( !dialect.supportsValuesList() ) {
throw new UnsupportedOperationException(
"The " + getClass().getSimpleName() +
" can only be used with Dialects that support VALUES lists!"
);
}
}
@Override
protected IdTableInfoImpl buildIdTableInfo(
PersistentClass entityBinding,
Table idTable,
JdbcServices jdbcServices,
MetadataImplementor metadata,
PreparationContextImpl context) {
final String renderedName = jdbcServices.getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
idTable.getQualifiedTableName(),
jdbcServices.getJdbcEnvironment().getDialect()
);
context.creationStatements.add( buildIdTableCreateStatement( idTable, jdbcServices, metadata ) );
if ( dropIdTables ) {
context.dropStatements.add( buildIdTableDropStatement( idTable, jdbcServices ) );
}
return new IdTableInfoImpl( renderedName );
}
@Override
protected void finishPreparation(
JdbcServices jdbcServices,
JdbcConnectionAccess connectionAccess,
MetadataImplementor metadata,
PreparationContextImpl context) {
IdTableHelper.INSTANCE.executeIdTableCreationStatements(
context.creationStatements,
jdbcServices,
connectionAccess
);
this.dropTableStatements = dropIdTables
? context.dropStatements.toArray( new String[ context.dropStatements.size() ] )
: null;
}
private Dialect getDialect() {
return buildingContext.getBuildingOptions()
.getServiceRegistry()
.getService( JdbcServices.class )
.getJdbcEnvironment()
.getDialect();
}
@Override
public IsolationDelegate createIsolationDelegate() {
final JdbcSessionOwner jdbcSessionOwner = transactionCoordinatorOwner.getJdbcSessionOwner();
return new JdbcIsolationDelegate(
jdbcSessionOwner.getJdbcConnectionAccess(),
jdbcSessionOwner.getJdbcSessionContext().getServiceRegistry().getService( JdbcServices.class ).getSqlExceptionHelper()
);
}
@Override
public IsolationDelegate createIsolationDelegate() {
final JdbcSessionOwner jdbcSessionOwner = transactionCoordinatorOwner.getJdbcSessionOwner();
return new JtaIsolationDelegate(
jdbcSessionOwner.getJdbcConnectionAccess(),
jdbcSessionOwner.getJdbcSessionContext()
.getServiceRegistry()
.getService( JdbcServices.class )
.getSqlExceptionHelper(),
jtaPlatform.retrieveTransactionManager()
);
}
public LogicalConnectionManagedImpl(
JdbcConnectionAccess jdbcConnectionAccess,
JdbcSessionContext jdbcSessionContext,
ResourceRegistry resourceRegistry) {
this.jdbcConnectionAccess = jdbcConnectionAccess;
this.observer = jdbcSessionContext.getObserver();
this.resourceRegistry = resourceRegistry;
this.connectionHandlingMode = determineConnectionHandlingMode(
jdbcSessionContext.getPhysicalConnectionHandlingMode(),
jdbcConnectionAccess
);
this.sqlExceptionHelper = jdbcSessionContext.getServiceRegistry()
.getService( JdbcServices.class )
.getSqlExceptionHelper();
if ( connectionHandlingMode.getAcquisitionMode() == ConnectionAcquisitionMode.IMMEDIATELY ) {
acquireConnectionIfNeeded();
}
this.providerDisablesAutoCommit = jdbcSessionContext.doesConnectionProviderDisableAutoCommit();
if ( providerDisablesAutoCommit ) {
log.debug(
"`hibernate.connection.provider_disables_autocommit` was enabled. This setting should only be " +
"enabled when you are certain that the Connections given to Hibernate by the " +
"ConnectionProvider have auto-commit disabled. Enabling this setting when the " +
"Connections do not have auto-commit disabled will lead to Hibernate executing " +
"SQL operations outside of any JDBC/SQL transaction."
);
}
}
private String getConcreteEntityTypeName(
ResultSet resultSet,
ResultSetProcessingContext context,
EntityKey entityKey) {
final Loadable loadable = (Loadable) entityReference.getEntityPersister();
if ( ! loadable.hasSubclasses() ) {
return entityReference.getEntityPersister().getEntityName();
}
final Object discriminatorValue;
try {
discriminatorValue = loadable.getDiscriminatorType().nullSafeGet(
resultSet,
entityReferenceAliases.getColumnAliases().getSuffixedDiscriminatorAlias(),
context.getSession(),
null
);
}
catch (SQLException e) {
throw context.getSession().getFactory().getServiceRegistry().getService( JdbcServices.class ).getSqlExceptionHelper().convert(
e,
"Could not read discriminator value from ResultSet"
);
}
final String result = loadable.getSubclassForDiscriminatorValue( discriminatorValue );
if ( result == null ) {
// whoops! we got an instance of another class hierarchy branch
throw new WrongClassException(
"Discriminator: " + discriminatorValue,
entityKey.getIdentifier(),
entityReference.getEntityPersister().getEntityName()
);
}
return result;
}
private void checkVersion(
SharedSessionContractImplementor session,
ResultSet resultSet,
EntityPersister persister,
EntityAliases entityAliases,
EntityKey entityKey,
Object entityInstance) {
final Object version = session.getPersistenceContext().getEntry( entityInstance ).getVersion();
if ( version != null ) {
//null version means the object is in the process of being loaded somewhere else in the ResultSet
VersionType versionType = persister.getVersionType();
final Object currentVersion;
try {
currentVersion = versionType.nullSafeGet(
resultSet,
entityAliases.getSuffixedVersionAliases(),
session,
null
);
}
catch (SQLException e) {
throw session.getFactory().getServiceRegistry().getService( JdbcServices.class ).getSqlExceptionHelper().convert(
e,
"Could not read version value from result set"
);
}
if ( !versionType.isEqual( version, currentVersion ) ) {
if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
session.getFactory().getStatistics().optimisticFailure( persister.getEntityName() );
}
throw new StaleObjectStateException( persister.getEntityName(), entityKey.getIdentifier() );
}
}
}
public JdbcContextBuilder(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
final JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
this.sqlStatementLogger = jdbcServices.getSqlStatementLogger();
this.sqlExceptionHelper = jdbcServices.getSqlExceptionHelper();
this.dialect = jdbcServices.getJdbcEnvironment().getDialect();
this.jdbcConnectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess();
}
public JdbcContextDelayedDropImpl(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
this.jdbcServices = serviceRegistry.getService( JdbcServices.class );
this.jdbcConnectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess();
if ( jdbcConnectionAccess == null ) {
// todo : log or error?
throw new SchemaManagementException(
"Could not build JDBC Connection context to drop schema on SessionFactory close"
);
}
}
protected JDBCException convertSqlException(String message, SQLException e) {
// if JdbcServices#getSqlExceptionHelper is available, use it...
final JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
if ( jdbcServices != null && jdbcServices.getSqlExceptionHelper() != null ) {
return jdbcServices.getSqlExceptionHelper().convert( e, message, null );
}
// likely we are still in the process of initializing the ServiceRegistry, so use the simplified
// SQLException conversion
return simpleConverterAccess.getValue().convert( e, message, null );
}
/**
* Constructs a ResultSetReturnImpl
*
* @param jdbcCoordinator The JdbcCoordinator
*/
public ResultSetReturnImpl(JdbcCoordinator jdbcCoordinator) {
this.jdbcCoordinator = jdbcCoordinator;
final JdbcServices jdbcServices = jdbcCoordinator.getJdbcSessionOwner()
.getJdbcSessionContext()
.getServiceRegistry()
.getService( JdbcServices.class );
this.dialect = jdbcServices.getDialect();
this.sqlStatementLogger = jdbcServices.getSqlStatementLogger();
this.sqlExceptionHelper = jdbcServices.getSqlExceptionHelper();
}
private JdbcCoordinatorImpl(
LogicalConnectionImplementor logicalConnection,
boolean isUserSuppliedConnection,
JdbcSessionOwner owner) {
this.logicalConnection = logicalConnection;
this.isUserSuppliedConnection = isUserSuppliedConnection;
this.owner = owner;
this.exceptionHelper = owner.getJdbcSessionContext()
.getServiceRegistry()
.getService( JdbcServices.class )
.getSqlExceptionHelper();
}
private JdbcServices getJdbcService() {
return jdbcCoordinator
.getJdbcSessionOwner()
.getJdbcSessionContext()
.getServiceRegistry()
.getService( JdbcServices.class );
}
@Override
public JdbcServices getJdbcServices() {
if ( jdbcServices == null ) {
jdbcServices = getServiceRegistry().getService( JdbcServices.class );
}
return jdbcServices;
}
@Override
public Clob mergeClob(Clob original, Clob target, SharedSessionContractImplementor session) {
if ( original == null && target == null ) {
return null;
}
try {
final LobCreator lobCreator = session.getFactory().getServiceRegistry().getService( JdbcServices.class ).getLobCreator( session );
return original == null
? lobCreator.createClob( "" )
: lobCreator.createClob( original.getCharacterStream(), original.length() );
}
catch (SQLException e) {
throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge CLOB data" );
}
}
@Override
public NClob mergeNClob(NClob original, NClob target, SharedSessionContractImplementor session) {
if ( original == null && target == null ) {
return null;
}
try {
final LobCreator lobCreator = session.getFactory().getServiceRegistry().getService( JdbcServices.class ).getLobCreator( session );
return original == null
? lobCreator.createNClob( "" )
: lobCreator.createNClob( original.getCharacterStream(), original.length() );
}
catch (SQLException e) {
throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge NCLOB data" );
}
}