下面列出了怎么用org.hibernate.AssertionFailure的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Convert from the Hibernate specific LockMode to the JPA defined LockModeType.
*
* @param lockMode The Hibernate LockMode.
*
* @return The JPA LockModeType
*/
public static LockModeType convertToLockModeType(LockMode lockMode) {
if ( lockMode == LockMode.NONE ) {
return LockModeType.NONE;
}
else if ( lockMode == LockMode.OPTIMISTIC || lockMode == LockMode.READ ) {
return LockModeType.OPTIMISTIC;
}
else if ( lockMode == LockMode.OPTIMISTIC_FORCE_INCREMENT || lockMode == LockMode.WRITE ) {
return LockModeType.OPTIMISTIC_FORCE_INCREMENT;
}
else if ( lockMode == LockMode.PESSIMISTIC_READ ) {
return LockModeType.PESSIMISTIC_READ;
}
else if ( lockMode == LockMode.PESSIMISTIC_WRITE
|| lockMode == LockMode.UPGRADE
|| lockMode == LockMode.UPGRADE_NOWAIT
|| lockMode == LockMode.UPGRADE_SKIPLOCKED) {
return LockModeType.PESSIMISTIC_WRITE;
}
else if ( lockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT
|| lockMode == LockMode.FORCE ) {
return LockModeType.PESSIMISTIC_FORCE_INCREMENT;
}
throw new AssertionFailure( "unhandled lock mode " + lockMode );
}
@Override
public Object[] extractNaturalIdValues(Object entity, EntityPersister persister) {
if ( entity == null ) {
throw new AssertionFailure( "Entity from which to extract natural id value(s) cannot be null" );
}
if ( persister == null ) {
throw new AssertionFailure( "Persister to use in extracting natural id value(s) cannot be null" );
}
final int[] naturalIdentifierProperties = persister.getNaturalIdentifierProperties();
final Object[] naturalIdValues = new Object[naturalIdentifierProperties.length];
for ( int i = 0; i < naturalIdentifierProperties.length; i++ ) {
naturalIdValues[i] = persister.getPropertyValue( entity, naturalIdentifierProperties[i] );
}
return naturalIdValues;
}
public static MappedSuperclass getMappedSuperclassOrNull(
XClass declaringClass,
Map<XClass, InheritanceState> inheritanceStatePerClass,
MetadataBuildingContext context) {
boolean retrieve = false;
if ( declaringClass != null ) {
final InheritanceState inheritanceState = inheritanceStatePerClass.get( declaringClass );
if ( inheritanceState == null ) {
throw new org.hibernate.annotations.common.AssertionFailure(
"Declaring class is not found in the inheritance state hierarchy: " + declaringClass
);
}
if ( inheritanceState.isEmbeddableSuperclass() ) {
retrieve = true;
}
}
if ( retrieve ) {
return context.getMetadataCollector().getMappedSuperclass(
context.getBootstrapContext().getReflectionManager().toClass( declaringClass )
);
}
else {
return null;
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public BasicProxyFactoryImpl(Class superClass, Class[] interfaces, ByteBuddyState byteBuddyState) {
if ( superClass == null && ( interfaces == null || interfaces.length < 1 ) ) {
throw new AssertionFailure( "attempting to build proxy without any superclass or interfaces" );
}
final Class<?> superClassOrMainInterface = superClass != null ? superClass : interfaces[0];
final TypeCache.SimpleKey cacheKey = getCacheKey( superClass, interfaces );
this.proxyClass = byteBuddyState.loadBasicProxy( superClassOrMainInterface, cacheKey, byteBuddy -> byteBuddy
.with( new NamingStrategy.SuffixingRandom( PROXY_NAMING_SUFFIX, new NamingStrategy.SuffixingRandom.BaseNameResolver.ForFixedValue( superClassOrMainInterface.getName() ) ) )
.subclass( superClass == null ? Object.class : superClass, ConstructorStrategy.Default.DEFAULT_CONSTRUCTOR )
.implement( interfaces == null ? NO_INTERFACES : interfaces )
.defineField( ProxyConfiguration.INTERCEPTOR_FIELD_NAME, ProxyConfiguration.Interceptor.class, Visibility.PRIVATE )
.method( byteBuddyState.getProxyDefinitionHelpers().getVirtualNotFinalizerFilter() )
.intercept( byteBuddyState.getProxyDefinitionHelpers().getDelegateToInterceptorDispatcherMethodDelegation() )
.implement( ProxyConfiguration.class )
.intercept( byteBuddyState.getProxyDefinitionHelpers().getInterceptorFieldAccessor() )
);
this.interceptor = new PassThroughInterceptor( proxyClass.getName() );
}
@Override
public Serializable disassemble(
Object value,
SharedSessionContractImplementor session,
Object owner) throws HibernateException {
if ( value == null ) {
return null;
}
else {
// cache the actual id of the object, not the value of the
// property-ref, which might not be initialized
Object id = ForeignKeys.getEntityIdentifierIfNotUnsaved(
getAssociatedEntityName(),
value,
session
);
if ( id == null ) {
throw new AssertionFailure(
"cannot cache a reference to an object with a null id: " +
getAssociatedEntityName()
);
}
return getIdentifierType( session ).disassemble( id, session, owner );
}
}
/**
* make sure user didn't mangle the id
*/
public void checkId(Object object, EntityPersister persister, Serializable id, SessionImplementor session)
throws HibernateException {
if ( id != null && id instanceof DelayedPostInsertIdentifier ) {
// this is a situation where the entity id is assigned by a post-insert generator
// and was saved outside the transaction forcing it to be delayed
return;
}
if ( persister.canExtractIdOutOfEntity() ) {
Serializable oid = persister.getIdentifier( object, session );
if ( id == null ) {
throw new AssertionFailure( "null id in " + persister.getEntityName() + " entry (don't flush the Session after an exception occurs)" );
}
if ( !persister.getIdentifierType().isEqual( id, oid, session.getFactory() ) ) {
throw new HibernateException(
"identifier of an instance of " + persister.getEntityName() + " was altered from "
+ id + " to " + oid
);
}
}
}
public void bindTableForDiscriminatedSubclass(InFlightMetadataCollector.EntityTableXref superTableXref) {
if ( !SingleTableSubclass.class.isInstance( persistentClass ) ) {
throw new AssertionFailure(
"Was expecting a discriminated subclass [" + SingleTableSubclass.class.getName() +
"] but found [" + persistentClass.getClass().getName() + "] for entity [" +
persistentClass.getEntityName() + "]"
);
}
context.getMetadataCollector().addEntityTableXref(
persistentClass.getEntityName(),
context.getMetadataCollector().getDatabase().toIdentifier(
context.getMetadataCollector().getLogicalTableName(
superTableXref.getPrimaryTable()
)
),
superTableXref.getPrimaryTable(),
superTableXref
);
}
/**
* The given save-update event named a detached entity.
* <p/>
* Here, we will perform the update processing.
*
* @param event The update event to be handled.
*/
protected void entityIsDetached(SaveOrUpdateEvent event) {
LOG.trace( "Updating detached instance" );
if ( event.getSession().getPersistenceContext().isEntryFor( event.getEntity() ) ) {
//TODO: assertion only, could be optimized away
throw new AssertionFailure( "entity was persistent" );
}
Object entity = event.getEntity();
EntityPersister persister = event.getSession().getEntityPersister( event.getEntityName(), entity );
event.setRequestedId(
getUpdateId(
entity, persister, event.getRequestedId(), event.getSession()
)
);
performUpdate( event, entity, persister );
}
public void processInsertGeneratedProperties(
Serializable id,
Object entity,
Object[] state,
SharedSessionContractImplementor session) {
if ( !hasInsertGeneratedProperties() ) {
throw new AssertionFailure( "no insert-generated properties" );
}
processGeneratedProperties(
id,
entity,
state,
session,
sqlInsertGeneratedValuesSelectString,
GenerationTiming.INSERT
);
}
public void addAttributeConverterInfo(AttributeConverterInfo info) {
if ( this.attributeConverterInfoMap == null ) {
this.attributeConverterInfoMap = new HashMap<>();
}
final Object old = this.attributeConverterInfoMap.put( info.getConverterClass(), info );
if ( old != null ) {
throw new AssertionFailure(
String.format(
"AttributeConverter class [%s] registered multiple times",
info.getConverterClass()
)
);
}
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session, Object owner)
throws HibernateException {
if (value==null) {
return null;
}
else {
// cache the actual id of the object, not the value of the
// property-ref, which might not be initialized
Object id = ForeignKeys.getEntityIdentifierIfNotUnsaved( getAssociatedEntityName(), value, session );
if (id==null) {
throw new AssertionFailure(
"cannot cache a reference to an object with a null id: " +
getAssociatedEntityName()
);
}
return getIdentifierType(session).disassemble(id, session, owner);
}
}
public static FlushModeType getFlushModeType(FlushMode flushMode) {
if ( flushMode == FlushMode.ALWAYS ) {
log.debug( "Interpreting Hibernate FlushMode#ALWAYS to JPA FlushModeType#AUTO; may cause problems if relying on FlushMode#ALWAYS-specific behavior" );
return FlushModeType.AUTO;
}
else if ( flushMode == FlushMode.MANUAL ) {
log.debug( "Interpreting Hibernate FlushMode#MANUAL to JPA FlushModeType#COMMIT; may cause problems if relying on FlushMode#MANUAL-specific behavior" );
return FlushModeType.COMMIT;
}
else if ( flushMode == FlushMode.COMMIT ) {
return FlushModeType.COMMIT;
}
else if ( flushMode == FlushMode.AUTO ) {
return FlushModeType.AUTO;
}
throw new AssertionFailure( "unhandled FlushMode " + flushMode );
}
public void afterTransactionCompletion(boolean success) {
while ( !processes.isEmpty() ) {
try {
processes.poll().doAfterTransactionCompletion( success, session );
}
catch (CacheException ce) {
LOG.unableToReleaseCacheLock( ce );
// continue loop
}
catch (Exception e) {
throw new AssertionFailure( "Exception releasing cache locks", e );
}
}
if ( session.getFactory().getSessionFactoryOptions().isQueryCacheEnabled() ) {
session.getFactory().getCache().getTimestampsCache().invalidate(
querySpacesToInvalidate.toArray( new String[querySpacesToInvalidate.size()] ),
session
);
}
querySpacesToInvalidate.clear();
}
public void addConverter(ConverterDescriptor descriptor) {
if ( attributeConverterDescriptorsByClass == null ) {
attributeConverterDescriptorsByClass = new ConcurrentHashMap<>();
}
final Object old = attributeConverterDescriptorsByClass.put(
descriptor.getAttributeConverterClass(),
descriptor
);
if ( old != null ) {
throw new AssertionFailure(
String.format(
Locale.ENGLISH,
"AttributeConverter class [%s] registered multiple times",
descriptor.getAttributeConverterClass()
)
);
}
}
private EnumState(int offset, Class<E> enumType) {
final E[] enumConstants = enumType.getEnumConstants();
// In case any of the enums cannot be stored in 4 bits anymore, we'd have to re-structure the compressed
// state int
if ( enumConstants.length > 15 ) {
throw new AssertionFailure( "Cannot store enum type " + enumType.getName() + " in compressed state as"
+ " it has too many values." );
}
this.offset = offset;
this.enumConstants = enumConstants;
// a mask for reading the four bits, starting at the right offset
this.mask = 0xF << offset;
// a mask for setting the four bits at the right offset to 0
this.unsetMask = 0xFFFF & ~mask;
}
/**
* Translates an AST join type (i.e., the token type) into a JoinFragment.XXX join type.
*
* @param astJoinType The AST join type (from HqlSqlTokenTypes or SqlTokenTypes)
* @return a JoinFragment.XXX join type.
* @see JoinFragment
* @see SqlTokenTypes
*/
public static int toHibernateJoinType(int astJoinType) {
switch ( astJoinType ) {
case LEFT_OUTER:
return JoinFragment.LEFT_OUTER_JOIN;
case INNER:
return JoinFragment.INNER_JOIN;
case RIGHT_OUTER:
return JoinFragment.RIGHT_OUTER_JOIN;
default:
throw new AssertionFailure( "undefined join type " + astJoinType );
}
}
/**
* Handle the given load event.
*
* @param event The load event to be handled.
*/
@Override
public CompletionStage<Void> reactiveOnLoad(
final LoadEvent event,
final LoadEventListener.LoadType loadType) throws HibernateException {
final EntityPersister persister = getPersister( event );
if ( persister == null ) {
throw new HibernateException( "Unable to locate persister: " + event.getEntityClassName() );
}
return checkId( event, loadType, persister ).thenCompose(
vd -> doOnLoad( persister, event, loadType )
.thenAccept( event::setResult )
.handle( (v, x) -> {
if ( x instanceof HibernateException ) {
LOG.unableToLoadCommand( (HibernateException) x );
}
CompletionStages.returnNullorRethrow( x );
if ( event.getResult() instanceof CompletionStage ) {
throw new AssertionFailure( "Unexpected CompletionStage" );
}
return v;
} ));
}
public static Object[] bind(Binder binder) {
PreparedStatementAdaptor statement = new PreparedStatementAdaptor();
try {
binder.bind(statement);
}
catch (SQLException e) {
throw new AssertionFailure("SQLException should never occur", e);
}
return statement.getParametersAsArray();
}
/**
* Translates an AST join type (i.e., the token type) into a JoinFragment.XXX join type.
*
* @param astJoinType The AST join type (from HqlSqlTokenTypes or SqlTokenTypes)
* @return a JoinFragment.XXX join type.
* @see JoinFragment
* @see SqlTokenTypes
*/
public static int toHibernateJoinType(int astJoinType) {
switch ( astJoinType ) {
case LEFT_OUTER:
return JoinFragment.LEFT_OUTER_JOIN;
case INNER:
return JoinFragment.INNER_JOIN;
case RIGHT_OUTER:
return JoinFragment.RIGHT_OUTER_JOIN;
default:
throw new AssertionFailure( "undefined join type " + astJoinType );
}
}
private static Class<?> getTargetEntityClass(XProperty property) {
final ManyToOne mTo = property.getAnnotation( ManyToOne.class );
if (mTo != null) {
return mTo.targetEntity();
}
final OneToOne oTo = property.getAnnotation( OneToOne.class );
if (oTo != null) {
return oTo.targetEntity();
}
throw new AssertionFailure("Unexpected discovery of a targetEntity: " + property.getName() );
}
static PropertyData getPropertyOverriddenByMapperOrMapsId(
boolean isId,
PropertyHolder propertyHolder,
String propertyName,
MetadataBuildingContext buildingContext) {
final XClass persistentXClass;
try {
persistentXClass = buildingContext.getBootstrapContext().getReflectionManager()
.classForName( propertyHolder.getPersistentClass().getClassName() );
}
catch ( ClassLoadingException e ) {
throw new AssertionFailure( "PersistentClass name cannot be converted into a Class", e);
}
if ( propertyHolder.isInIdClass() ) {
PropertyData pd = buildingContext.getMetadataCollector().getPropertyAnnotatedWithIdAndToOne(
persistentXClass,
propertyName
);
if ( pd == null && buildingContext.getBuildingOptions().isSpecjProprietarySyntaxEnabled() ) {
pd = buildingContext.getMetadataCollector().getPropertyAnnotatedWithMapsId(
persistentXClass,
propertyName
);
}
return pd;
}
String propertyPath = isId ? "" : propertyName;
return buildingContext.getMetadataCollector().getPropertyAnnotatedWithMapsId( persistentXClass, propertyPath );
}
public String foreignKeyColumnName(
String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName
) {
String header = propertyName != null ? StringHelper.unqualify( propertyName ) : propertyTableName;
if ( header == null ) throw new AssertionFailure( "NamingStrategy not properly filled" );
return columnName( header + "_" + referencedColumnName );
}
private void setProxyReadOnly(HibernateProxy proxy, boolean readOnly) {
if ( proxy.getHibernateLazyInitializer().getSession() != getSession() ) {
throw new AssertionFailure(
"Attempt to set a proxy to read-only that is associated with a different session" );
}
proxy.getHibernateLazyInitializer().setReadOnly( readOnly );
}
/**
* Return the property name or propertyTableName
*/
public String foreignKeyColumnName(
String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName
) {
String header = propertyName != null ? StringHelper.unqualify( propertyName ) : propertyTableName;
if (header == null) throw new AssertionFailure("NammingStrategy not properly filled");
return columnName( header ); //+ "_" + referencedColumnName not used for backward compatibility
}
private void bindEjb3Annotation(Entity ejb3Ann) {
if ( ejb3Ann == null ) throw new AssertionFailure( "@Entity should always be not null" );
if ( BinderHelper.isEmptyAnnotationValue( ejb3Ann.name() ) ) {
name = StringHelper.unqualify( annotatedClass.getName() );
}
else {
name = ejb3Ann.name();
}
}
OptimisticLockStyle getVersioning(OptimisticLockType type) {
switch ( type ) {
case VERSION:
return OptimisticLockStyle.VERSION;
case NONE:
return OptimisticLockStyle.NONE;
case DIRTY:
return OptimisticLockStyle.DIRTY;
case ALL:
return OptimisticLockStyle.ALL;
default:
throw new AssertionFailure( "optimistic locking not supported: " + type );
}
}
@Override
public void registerNaturalIdUniqueKeyBinder(String entityName, NaturalIdUniqueKeyBinder ukBinder) {
if ( naturalIdUniqueKeyBinderMap == null ) {
naturalIdUniqueKeyBinderMap = new HashMap<>();
}
final NaturalIdUniqueKeyBinder previous = naturalIdUniqueKeyBinderMap.put( entityName, ukBinder );
if ( previous != null ) {
throw new AssertionFailure( "Previous NaturalIdUniqueKeyBinder already registered for entity name : " + entityName );
}
}
private void makeOneToManyMapKeyColumnNullableIfNotInProperty(
final XProperty property) {
final org.hibernate.mapping.Map map = (org.hibernate.mapping.Map) this.collection;
if ( map.isOneToMany() &&
property.isAnnotationPresent( MapKeyColumn.class ) ) {
final Value indexValue = map.getIndex();
if ( indexValue.getColumnSpan() != 1 ) {
throw new AssertionFailure( "Map key mapped by @MapKeyColumn does not have 1 column" );
}
final Selectable selectable = indexValue.getColumnIterator().next();
if ( selectable.isFormula() ) {
throw new AssertionFailure( "Map key mapped by @MapKeyColumn is a Formula" );
}
Column column = (Column) map.getIndex().getColumnIterator().next();
if ( !column.isNullable() ) {
final PersistentClass persistentClass = ( ( OneToMany ) map.getElement() ).getAssociatedClass();
// check if the index column has been mapped by the associated entity to a property;
// @MapKeyColumn only maps a column to the primary table for the one-to-many, so we only
// need to check "un-joined" properties.
if ( !propertyIteratorContainsColumn( persistentClass.getUnjoinedPropertyIterator(), column ) ) {
// The index column is not mapped to an associated entity property so we can
// safely make the index column nullable.
column.setNullable( true );
}
}
}
}
public boolean isSecondary() {
if ( propertyHolder == null ) {
throw new AssertionFailure( "Should not call getTable() on column w/o persistent class defined" );
}
return StringHelper.isNotEmpty( explicitTableName )
&& !propertyHolder.getTable().getName().equals( explicitTableName );
}
public BasicProxyFactoryImpl(Class superClass, Class[] interfaces) {
if ( superClass == null && ( interfaces == null || interfaces.length < 1 ) ) {
throw new AssertionFailure( "attempting to build proxy without any superclass or interfaces" );
}
final javassist.util.proxy.ProxyFactory factory = new javassist.util.proxy.ProxyFactory();
factory.setFilter( FINALIZE_FILTER );
if ( superClass != null ) {
factory.setSuperclass( superClass );
}
if ( interfaces != null && interfaces.length > 0 ) {
factory.setInterfaces( interfaces );
}
proxyClass = factory.createClass();
}