/** * Create a new SpringSessionContext for the given Hibernate SessionFactory. * @param sessionFactory the SessionFactory to provide current Sessions for */ public SpringSessionContext(SessionFactoryImplementor sessionFactory) { this.sessionFactory = sessionFactory; try { JtaPlatform jtaPlatform = sessionFactory.getServiceRegistry().getService(JtaPlatform.class); this.transactionManager = jtaPlatform.retrieveTransactionManager(); if (this.transactionManager != null) { this.jtaSessionContext = new SpringJtaSessionContext(sessionFactory); } } catch (Exception ex) { LogFactory.getLog(SpringSessionContext.class).warn( "Could not introspect Hibernate JtaPlatform for SpringJtaSessionContext", ex); } }
@Override protected String renderOrderByElement(String expression, String collation, String order, String nulls) { final NullPrecedence nullPrecedence = NullPrecedence.parse( nulls, sessionFactory.getSessionFactoryOptions().getDefaultNullPrecedence() ); return sessionFactory.getDialect().renderOrderByElement( expression, collation, order, nullPrecedence ); } }
@Override public void nullSafeSet( PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { String entityName = session.getFactory().getClassMetadata((Class) value).getEntityName(); Loadable entityPersister = (Loadable) session.getFactory().getEntityPersister(entityName); underlyingType.nullSafeSet(st, entityPersister.getDiscriminatorValue(), index, session); }
protected void prepareForPossibleLoadingOutsideTransaction() { if ( session != null ) { allowLoadOutsideTransaction = session.getFactory().getSessionFactoryOptions().isInitializeLazyStateOutsideTransactionsEnabled(); if ( allowLoadOutsideTransaction && sessionFactoryUuid == null ) { sessionFactoryUuid = session.getFactory().getUuid(); } } }
@Override protected String renderOrderByElement(String expression, String order, String nulls) { final NullPrecedence nullPrecedence = NullPrecedence.parse( nulls, sessionFactory.getSettings() .getDefaultNullPrecedence() ); return sessionFactory.getDialect().renderOrderByElement( expression, null, order, nullPrecedence ); } }
/** * Obtain a lob creator for the given session. * * @param session The session for which to obtain a lob creator * * @return The log creator reference */ public static LobCreator getLobCreator(SessionImplementor session) { return session.getFactory() .getServiceRegistry() .getService( JdbcServices.class ) .getLobCreator( session ); }
private void assertEnumProperty(Class<?> entityClass, Class<?> typeClass, String propertyName, EnumType expectedType) { doInJPA( this::entityManagerFactory, entityManager -> { final SessionFactoryImplementor sessionFactory = entityManager.unwrap( SessionImplementor.class ).getSessionFactory(); final EntityPersister entityPersister = sessionFactory.getMetamodel().entityPersister( entityClass ); final EnversService enversService = sessionFactory.getServiceRegistry().getService( EnversService.class ); final String entityName = entityPersister.getEntityName(); final String auditEntityName = enversService.getAuditEntitiesConfiguration().getAuditEntityName( entityName ); final EntityPersister auditedEntityPersister = sessionFactory.getMetamodel().entityPersister( auditEntityName ); final org.hibernate.type.Type propertyType = auditedEntityPersister.getPropertyType( propertyName ); assertTyping( CustomType.class, propertyType ); final UserType userType = ( (CustomType) propertyType ).getUserType(); assertTyping( typeClass, userType ); assertTyping( org.hibernate.type.EnumType.class, userType ); switch ( expectedType ) { case STRING: assertTrue( !( (org.hibernate.type.EnumType) userType ).isOrdinal() ); break; default: assertTrue( ( (org.hibernate.type.EnumType) userType ).isOrdinal() ); break; } } ); } }
EntityKey entityKey, Object entityInstance) { final Object version = session.getPersistenceContext().getEntry( entityInstance ).getVersion(); VersionType versionType = persister.getVersionType(); final Object currentVersion; try { throw session.getFactory().getServiceRegistry().getService( JdbcServices.class ).getSqlExceptionHelper().convert( e, "Could not read version value from result set" if ( session.getFactory().getStatistics().isStatisticsEnabled() ) { session.getFactory().getStatistics().optimisticFailure( persister.getEntityName() ); throw new StaleObjectStateException( persister.getEntityName(), entityKey.getIdentifier() );
protected boolean checkModified(SessionImplementor session, Object newObj, Object oldObj) { if ( nonInsertableFake ) { return false; } if ( newObj == null || oldObj == null || newObj.getClass().equals( oldObj.getClass() ) ) { return !EntityTools.entitiesEqual( session, referencedEntityName, newObj, oldObj ); } // There is a chance that oldObj may reference the identifier of the old entity rather // than the entity instance itself. This happens under Session#update with a detached // entity because the database snapshot that is used to derive the prior state doesn't // return the entity instances of the to-one associations but only the identifier. // // So here we assume the method was supplied the id and we ask the persister to verify // if the value is the identifier type. If not, we assume its the entity type and // therefore resolve the identifier from the entity directly prior to simply then // doing the identifier comparison. final EntityPersister persister = session.getFactory().getMetamodel().entityPersister( referencedEntityName ); Object resolvedNewObjectId = newObj; if ( !persister.getIdentifierType().getReturnedClass().isInstance( newObj ) ) { resolvedNewObjectId = EntityTools.getIdentifier( session, referencedEntityName, newObj ); } Object resolvedOldObjectId = oldObj; if ( !persister.getIdentifierType().getReturnedClass().isInstance( oldObj ) ) { resolvedOldObjectId = EntityTools.getIdentifier( session, referencedEntityName, oldObj ); } return !Objects.deepEquals( resolvedNewObjectId, resolvedOldObjectId ); }
private static void processDereferencedCollection(PersistentCollection coll, SessionImplementor session) { final PersistenceContext persistenceContext = session.getPersistenceContext(); final CollectionEntry entry = persistenceContext.getCollectionEntry( coll ); final CollectionPersister loadedPersister = entry.getLoadedPersister(); Serializable ownerId = loadedPersister.getOwnerEntityPersister().getIdentifier( coll.getOwner(), session ); if ( ownerId == null ) { if ( session.getFactory().getSessionFactoryOptions().isIdentifierRollbackEnabled() ) { final EntityEntry ownerEntry = persistenceContext.getEntry( coll.getOwner() ); if ( ownerEntry != null ) { ownerId = ownerEntry.getId(); final EntityKey key = session.generateEntityKey( ownerId, loadedPersister.getOwnerEntityPersister() ); final Object owner = persistenceContext.getEntity( key ); if ( owner == null ) { throw new AssertionFailure(
entityName = source.bestGuessEntityName( entity ); event.setEntityName( entityName ); final EntityEntry entityEntry = source.getPersistenceContext().getEntry( entity ); EntityState entityState = getEntityState( entity, entityName, entityEntry, source ); if ( entityState == EntityState.DETACHED ) { EntityPersister persister = source.getFactory().getEntityPersister( entityName ); if ( ForeignGenerator.class.isInstance( persister.getIdentifierGenerator() ) ) { if ( LOG.isDebugEnabled() && persister.getIdentifier( entity, source ) != null ) { LOG.debug( "Resetting entity id attribute to null for foreign generator" ); persister.setIdentifier( entity, null, source ); entityState = getEntityState( entity, entityName, entityEntry, source );
@Before public void init() { sessionFactoryImplementorMock = Mockito.mock(SessionFactoryImplementor.class); sessionFactoryOptionsMock = Mockito.mock(SessionFactoryOptions.class); when(sessionFactoryImplementorMock.getSessionFactoryOptions()).thenReturn( sessionFactoryOptionsMock ); serviceRegistryMock = Mockito.mock(ServiceRegistryImplementor.class); when( sessionFactoryImplementorMock.getServiceRegistry() ).thenReturn( serviceRegistryMock ); classLoaderServiceMock = Mockito.mock(ClassLoaderService.class); when( serviceRegistryMock.getService( eq( ClassLoaderService.class ) ) ).thenReturn( classLoaderServiceMock ); }
private String generateVersionIncrementUpdateString() { Update update = new Update( getFactory().getDialect() ); update.setTableName( getTableName( 0 ) ); if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) { update.setComment( "forced version increment" ); } update.addColumn( getVersionColumnName() ); update.addPrimaryKeyColumns( rootTableKeyColumnNames ); update.setVersionColumnName( getVersionColumnName() ); return update.toStatementString(); }
protected CollectionPersister resolveCollectionPersister( SessionImplementor session, PersistentCollection collection) { // First attempt to resolve the persister from the collection entry if ( collection != null ) { CollectionEntry collectionEntry = session.getPersistenceContext().getCollectionEntry( collection ); if ( collectionEntry != null ) { CollectionPersister collectionPersister = collectionEntry.getCurrentPersister(); if ( collectionPersister != null ) { return collectionPersister; } } } // Fallback to resolving the persister from the collection role final CollectionPersister collectionPersister = session.getFactory() .getMetamodel() .collectionPersister( commonCollectionMapperData.getRole() ); if ( collectionPersister == null ) { throw new AuditException( String.format( Locale.ROOT, "Failed to locate CollectionPersister for collection [%s]", commonCollectionMapperData.getRole() ) ); } return collectionPersister; }
@Test public void testExtensionPoints() throws Exception { final ServiceReference sr = bundleContext.getServiceReference( SessionFactory.class.getName() ); final SessionFactoryImplementor sfi = (SessionFactoryImplementor) bundleContext.getService( sr ); assertTrue( TestIntegrator.passed() ); Class impl = sfi.getServiceRegistry().getService( StrategySelector.class ).selectStrategyImplementor( Calendar.class, TestStrategyRegistrationProvider.GREGORIAN ); assertNotNull( impl ); BasicType basicType = sfi.getTypeResolver().basic( TestTypeContributor.NAME ); assertNotNull( basicType ); }
assertTrue( ( (SessionImplementor) session ).getPersistenceContext().containsEntity( new EntityKey( ( (SessionImplementor) session ).getContextEntityIdentifier( a2.getB() ), ( (SessionImplementor) session ).getFactory().getEntityPersister( B.class.getName() )
@Test @SuppressWarnings("unchecked") public void testPropertyAccessIgnoresStaticFields() { // verify that the entity persister is configured with property intValue as an Integer rather than // using the static field reference and determining the type to be String. assertTrue( sessionFactory() .getMetamodel() .entityPersister( FooEntity.class ) .getPropertyType( "intValue" ) .getReturnedClass() .isAssignableFrom( Integer.class ) ); } }
public AddWorkUnit( SessionImplementor sessionImplementor, String entityName, EnversService enversService, Serializable id, Map<String, Object> data) { super( sessionImplementor, entityName, enversService, id, RevisionType.ADD ); this.data = data; final String[] propertyNames = sessionImplementor.getFactory().getMetamodel() .entityPersister( getEntityName() ) .getPropertyNames(); this.state = ArraysTools.mapToArray( data, propertyNames ); }
/** * Create Hibernate proxy or retrieve the complete object of referenced, not audited entity. According to * {@link org.hibernate.envers.Audited#targetAuditMode()}} documentation, reference shall point to current * (non-historical) version of an entity. */ private Object createNotAuditedEntityReference( AuditReaderImplementor versionsReader, Class<?> entityClass, String entityName, Serializable primaryKey) { final EntityPersister entityPersister = versionsReader.getSessionImplementor().getFactory().getMetamodel() .entityPersister( entityName ); if ( entityPersister.hasProxy() ) { // If possible create a proxy. Returning complete object may affect performance. return versionsReader.getSession().load( entityClass, primaryKey ); } else { // If proxy is not allowed (e.g. @Proxy(lazy=false)) construct the original object. return versionsReader.getSession().get( entityClass, primaryKey ); } } }
private static void checkInBatchFetchQueue(long id, Session session, boolean expected) { final SessionImplementor sessionImplementor = (SessionImplementor) session; final EntityPersister persister = sessionImplementor.getFactory().getMetamodel().entityPersister( Task.class ); final BatchFetchQueue batchFetchQueue = sessionImplementor.getPersistenceContext().getBatchFetchQueue(); assertEquals( expected, batchFetchQueue.containsEntityKey( new EntityKey( id, persister ) ) ); }