Search in sources :

Example 76 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class LoadPlanStructureAssertionTest method testEncapsulatedCompositeIdWithFetches2.

@Test
public void testEncapsulatedCompositeIdWithFetches2() {
    Configuration cfg = new Configuration();
    cfg.addAnnotatedClass(Card.class);
    cfg.addAnnotatedClass(CardField.class);
    cfg.addAnnotatedClass(Key.class);
    cfg.addAnnotatedClass(PrimaryKey.class);
    final SessionFactoryImplementor sf = (SessionFactoryImplementor) cfg.buildSessionFactory();
    try {
        final OuterJoinLoadable cardPersister = (OuterJoinLoadable) sf.getClassMetadata(Card.class);
        doCompare(sf, cardPersister);
        final LoadPlan cardLoadPlan = LoadPlanStructureAssertionHelper.INSTANCE.buildLoadPlan(sf, cardPersister);
        assertEquals(LoadPlan.Disposition.ENTITY_LOADER, cardLoadPlan.getDisposition());
        assertEquals(1, cardLoadPlan.getReturns().size());
        // Check the root EntityReturn(Card)
        final EntityReturn cardReturn = assertTyping(EntityReturn.class, cardLoadPlan.getReturns().get(0));
        assertFalse(cardReturn.getIdentifierDescription().hasFetches());
        // Card should have one fetch, the fields collection
        assertEquals(1, cardReturn.getFetches().length);
        final CollectionAttributeFetch fieldsFetch = assertTyping(CollectionAttributeFetch.class, cardReturn.getFetches()[0]);
        assertNotNull(fieldsFetch.getElementGraph());
        // the Card.fields collection has entity elements of type CardField...
        final CollectionFetchableElementEntityGraph cardFieldElementGraph = assertTyping(CollectionFetchableElementEntityGraph.class, fieldsFetch.getElementGraph());
        // CardField should have no fetches
        assertEquals(0, cardFieldElementGraph.getFetches().length);
        // But it should have 1 key-many-to-one fetch for Key (Card is already handled)
        assertTrue(cardFieldElementGraph.getIdentifierDescription().hasFetches());
        final FetchSource cardFieldElementGraphIdAsFetchSource = assertTyping(FetchSource.class, cardFieldElementGraph.getIdentifierDescription());
        assertEquals(1, cardFieldElementGraphIdAsFetchSource.getFetches().length);
        assertEquals(1, cardFieldElementGraphIdAsFetchSource.getBidirectionalEntityReferences().length);
        BidirectionalEntityReference circularCardFetch = assertTyping(BidirectionalEntityReference.class, cardFieldElementGraphIdAsFetchSource.getBidirectionalEntityReferences()[0]);
        assertSame(circularCardFetch.getTargetEntityReference(), cardReturn);
        // the fetch above is to the other key-many-to-one for CardField.primaryKey composite: key
        EntityFetch keyFetch = assertTyping(EntityFetch.class, cardFieldElementGraphIdAsFetchSource.getFetches()[0]);
        assertEquals(Key.class.getName(), keyFetch.getEntityPersister().getEntityName());
    } finally {
        sf.close();
    }
}
Also used : EntityFetch(org.hibernate.loader.plan.spi.EntityFetch) OuterJoinLoadable(org.hibernate.persister.entity.OuterJoinLoadable) CollectionAttributeFetch(org.hibernate.loader.plan.spi.CollectionAttributeFetch) CollectionFetchableElementEntityGraph(org.hibernate.loader.plan.build.internal.returns.CollectionFetchableElementEntityGraph) FetchSource(org.hibernate.loader.plan.spi.FetchSource) Configuration(org.hibernate.cfg.Configuration) LoadPlan(org.hibernate.loader.plan.spi.LoadPlan) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) BidirectionalEntityReference(org.hibernate.loader.plan.spi.BidirectionalEntityReference) Key(org.hibernate.test.annotations.cid.keymanytoone.Key) PrimaryKey(org.hibernate.test.annotations.cid.keymanytoone.PrimaryKey) Card(org.hibernate.test.annotations.cid.keymanytoone.Card) EntityReturn(org.hibernate.loader.plan.spi.EntityReturn) Test(org.junit.Test) EncapsulatedCompositeIdResultSetProcessorTest(org.hibernate.test.loadplans.process.EncapsulatedCompositeIdResultSetProcessorTest)

Example 77 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class LoadPlanStructureAssertionTest method testManyToMany.

@Test
public void testManyToMany() {
    Configuration cfg = new Configuration();
    cfg.addResource("org/hibernate/test/immutable/entitywithmutablecollection/inverse/ContractVariation.hbm.xml");
    SessionFactoryImplementor sf = (SessionFactoryImplementor) cfg.buildSessionFactory();
    try {
        doCompare(sf, (OuterJoinLoadable) sf.getClassMetadata(org.hibernate.test.immutable.entitywithmutablecollection.Contract.class));
    } finally {
        sf.close();
    }
}
Also used : Configuration(org.hibernate.cfg.Configuration) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) Test(org.junit.Test) EncapsulatedCompositeIdResultSetProcessorTest(org.hibernate.test.loadplans.process.EncapsulatedCompositeIdResultSetProcessorTest)

Example 78 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class LoadPlanStructureAssertionTest method testEncapsulatedCompositeIdNoFetches1.

@Test
public void testEncapsulatedCompositeIdNoFetches1() {
    // CardField is an entity with a composite identifier mapped via a @EmbeddedId class (CardFieldPK) defining
    // a @ManyToOne
    Configuration cfg = new Configuration();
    cfg.addAnnotatedClass(EncapsulatedCompositeIdResultSetProcessorTest.CardField.class);
    cfg.addAnnotatedClass(EncapsulatedCompositeIdResultSetProcessorTest.Card.class);
    SessionFactoryImplementor sf = (SessionFactoryImplementor) cfg.buildSessionFactory();
    try {
        doCompare(sf, (OuterJoinLoadable) sf.getClassMetadata(EncapsulatedCompositeIdResultSetProcessorTest.CardField.class));
        doCompare(sf, (OuterJoinLoadable) sf.getClassMetadata(EncapsulatedCompositeIdResultSetProcessorTest.Card.class));
    } finally {
        sf.close();
    }
}
Also used : Configuration(org.hibernate.cfg.Configuration) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EncapsulatedCompositeIdResultSetProcessorTest(org.hibernate.test.loadplans.process.EncapsulatedCompositeIdResultSetProcessorTest) Test(org.junit.Test) EncapsulatedCompositeIdResultSetProcessorTest(org.hibernate.test.loadplans.process.EncapsulatedCompositeIdResultSetProcessorTest)

Example 79 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class CollectionCacheInvalidator method evictCache.

private void evictCache(Object entity, EntityPersister persister, EventSource session, Object[] oldState) {
    try {
        SessionFactoryImplementor factory = persister.getFactory();
        Set<String> collectionRoles = factory.getMetamodel().getCollectionRolesByEntityParticipant(persister.getEntityName());
        if (collectionRoles == null || collectionRoles.isEmpty()) {
            return;
        }
        for (String role : collectionRoles) {
            final CollectionPersister collectionPersister = factory.getMetamodel().collectionPersister(role);
            if (!collectionPersister.hasCache()) {
                // ignore collection if no caching is used
                continue;
            }
            // this is the property this OneToMany relation is mapped by
            String mappedBy = collectionPersister.getMappedByProperty();
            if (!collectionPersister.isManyToMany() && mappedBy != null && !mappedBy.isEmpty()) {
                int i = persister.getEntityMetamodel().getPropertyIndex(mappedBy);
                Serializable oldId = null;
                if (oldState != null) {
                    // in case of updating an entity we perhaps have to decache 2 entity collections, this is the
                    // old one
                    oldId = getIdentifier(session, oldState[i]);
                }
                Object ref = persister.getPropertyValue(entity, i);
                Serializable id = getIdentifier(session, ref);
                // only evict if the related entity has changed
                if ((id != null && !id.equals(oldId)) || (oldId != null && !oldId.equals(id))) {
                    if (id != null) {
                        evict(id, collectionPersister, session);
                    }
                    if (oldId != null) {
                        evict(oldId, collectionPersister, session);
                    }
                }
            } else {
                LOG.debug("Evict CollectionRegion " + role);
                final SoftLock softLock = collectionPersister.getCacheAccessStrategy().lockRegion();
                session.getActionQueue().registerProcess((success, session1) -> {
                    collectionPersister.getCacheAccessStrategy().unlockRegion(softLock);
                });
            }
        }
    } catch (Exception e) {
        if (PROPAGATE_EXCEPTION) {
            throw new IllegalStateException(e);
        }
        // don't let decaching influence other logic
        LOG.error("", e);
    }
}
Also used : Serializable(java.io.Serializable) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) HibernateException(org.hibernate.HibernateException) SoftLock(org.hibernate.cache.spi.access.SoftLock)

Example 80 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class StatefulPersistenceContext method deserialize.

/**
	 * Used by the owning session to explicitly control deserialization of the persistence context.
	 *
	 * @param ois The stream from which the persistence context should be read
	 * @param session The owning session
	 *
	 * @return The deserialized StatefulPersistenceContext
	 *
	 * @throws IOException deserialization errors.
	 * @throws ClassNotFoundException deserialization errors.
	 */
public static StatefulPersistenceContext deserialize(ObjectInputStream ois, SessionImplementor session) throws IOException, ClassNotFoundException {
    final boolean tracing = LOG.isTraceEnabled();
    if (tracing) {
        LOG.trace("Serializing persistent-context");
    }
    final StatefulPersistenceContext rtn = new StatefulPersistenceContext(session);
    SessionFactoryImplementor sfi = session.getFactory();
    try {
        rtn.defaultReadOnly = ois.readBoolean();
        // todo : we can actually just determine this from the incoming EntityEntry-s
        rtn.hasNonReadOnlyEntities = ois.readBoolean();
        int count = ois.readInt();
        if (tracing) {
            LOG.trace("Starting deserialization of [" + count + "] entitiesByKey entries");
        }
        rtn.entitiesByKey = new HashMap<>(count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count);
        for (int i = 0; i < count; i++) {
            rtn.entitiesByKey.put(EntityKey.deserialize(ois, sfi), ois.readObject());
        }
        count = ois.readInt();
        if (tracing) {
            LOG.trace("Starting deserialization of [" + count + "] entitiesByUniqueKey entries");
        }
        rtn.entitiesByUniqueKey = new HashMap<>(count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count);
        for (int i = 0; i < count; i++) {
            rtn.entitiesByUniqueKey.put(EntityUniqueKey.deserialize(ois, session), ois.readObject());
        }
        count = ois.readInt();
        if (tracing) {
            LOG.trace("Starting deserialization of [" + count + "] proxiesByKey entries");
        }
        //noinspection unchecked
        rtn.proxiesByKey = new ConcurrentReferenceHashMap<>(count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count, .75f, 1, ConcurrentReferenceHashMap.ReferenceType.STRONG, ConcurrentReferenceHashMap.ReferenceType.WEAK, null);
        for (int i = 0; i < count; i++) {
            final EntityKey ek = EntityKey.deserialize(ois, sfi);
            final Object proxy = ois.readObject();
            if (proxy instanceof HibernateProxy) {
                ((HibernateProxy) proxy).getHibernateLazyInitializer().setSession(session);
                rtn.proxiesByKey.put(ek, proxy);
            } else {
                // otherwise, the proxy was pruned during the serialization process
                if (tracing) {
                    LOG.trace("Encountered pruned proxy");
                }
            }
        }
        count = ois.readInt();
        if (tracing) {
            LOG.trace("Starting deserialization of [" + count + "] entitySnapshotsByKey entries");
        }
        rtn.entitySnapshotsByKey = new HashMap<>(count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count);
        for (int i = 0; i < count; i++) {
            rtn.entitySnapshotsByKey.put(EntityKey.deserialize(ois, sfi), ois.readObject());
        }
        rtn.entityEntryContext = EntityEntryContext.deserialize(ois, rtn);
        count = ois.readInt();
        if (tracing) {
            LOG.trace("Starting deserialization of [" + count + "] collectionsByKey entries");
        }
        rtn.collectionsByKey = new HashMap<>(count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count);
        for (int i = 0; i < count; i++) {
            rtn.collectionsByKey.put(CollectionKey.deserialize(ois, session), (PersistentCollection) ois.readObject());
        }
        count = ois.readInt();
        if (tracing) {
            LOG.trace("Starting deserialization of [" + count + "] collectionEntries entries");
        }
        rtn.collectionEntries = IdentityMap.instantiateSequenced(count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count);
        for (int i = 0; i < count; i++) {
            final PersistentCollection pc = (PersistentCollection) ois.readObject();
            final CollectionEntry ce = CollectionEntry.deserialize(ois, session);
            pc.setCurrentSession(session);
            rtn.collectionEntries.put(pc, ce);
        }
        count = ois.readInt();
        if (tracing) {
            LOG.trace("Starting deserialization of [" + count + "] arrayHolders entries");
        }
        rtn.arrayHolders = new IdentityHashMap<>(count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count);
        for (int i = 0; i < count; i++) {
            rtn.arrayHolders.put(ois.readObject(), (PersistentCollection) ois.readObject());
        }
        count = ois.readInt();
        if (tracing) {
            LOG.trace("Starting deserialization of [" + count + "] nullifiableEntityKey entries");
        }
        rtn.nullifiableEntityKeys = new HashSet<>();
        for (int i = 0; i < count; i++) {
            rtn.nullifiableEntityKeys.add(EntityKey.deserialize(ois, sfi));
        }
    } catch (HibernateException he) {
        throw new InvalidObjectException(he.getMessage());
    }
    return rtn;
}
Also used : CollectionEntry(org.hibernate.engine.spi.CollectionEntry) HibernateException(org.hibernate.HibernateException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) HibernateProxy(org.hibernate.proxy.HibernateProxy) EntityKey(org.hibernate.engine.spi.EntityKey) PersistentCollection(org.hibernate.collection.spi.PersistentCollection) InvalidObjectException(java.io.InvalidObjectException)

Aggregations

SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)129 Test (org.junit.Test)46 Configuration (org.hibernate.cfg.Configuration)27 SQLException (java.sql.SQLException)18 Type (org.hibernate.type.Type)16 EntityPersister (org.hibernate.persister.entity.EntityPersister)13 Connection (java.sql.Connection)12 HibernateException (org.hibernate.HibernateException)12 PreparedStatement (java.sql.PreparedStatement)11 Metadata (org.hibernate.boot.Metadata)11 Statement (java.sql.Statement)10 ArrayList (java.util.ArrayList)10 JdbcConnectionAccess (org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess)10 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)10 Serializable (java.io.Serializable)9 EncapsulatedCompositeIdResultSetProcessorTest (org.hibernate.test.loadplans.process.EncapsulatedCompositeIdResultSetProcessorTest)8 HashMap (java.util.HashMap)7 Integrator (org.hibernate.integrator.spi.Integrator)7 SessionFactoryServiceRegistry (org.hibernate.service.spi.SessionFactoryServiceRegistry)7 Map (java.util.Map)6