Search in sources :

Example 1 with NaturalIdLoadAccess

use of org.hibernate.NaturalIdLoadAccess in project hibernate-orm by hibernate.

the class ReadWriteTest method testNaturalIdLoaderCached.

@Test
public void testNaturalIdLoaderCached() throws Exception {
    final Statistics stats = sessionFactory().getStatistics();
    stats.setStatisticsEnabled(true);
    stats.clear();
    assertEquals("NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount());
    assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
    assertEquals("NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount());
    assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
    saveSomeCitizens();
    assertEquals("NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount());
    assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
    assertEquals("NaturalId Cache Puts", 2, stats.getNaturalIdCachePutCount());
    assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
    //Try NaturalIdLoadAccess after insert
    final Citizen citizen = withTxSessionApply(s -> {
        State france = ReadWriteTest.this.getState(s, "Ile de France");
        NaturalIdLoadAccess<Citizen> naturalIdLoader = s.byNaturalId(Citizen.class);
        naturalIdLoader.using("ssn", "1234").using("state", france);
        stats.clear();
        Citizen c = naturalIdLoader.load();
        assertNotNull(c);
        assertEquals("NaturalId Cache Hits", 1, stats.getNaturalIdCacheHitCount());
        assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
        assertEquals("NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount());
        assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
        markRollbackOnly(s);
        return c;
    });
    // TODO: Clear caches manually via cache manager (it's faster!!)
    cleanupCache();
    TIME_SERVICE.advance(1);
    stats.setStatisticsEnabled(true);
    stats.clear();
    //Try NaturalIdLoadAccess
    withTxSession(s -> {
        Citizen loadedCitizen = (Citizen) s.get(Citizen.class, citizen.getId());
        assertNotNull(loadedCitizen);
        assertEquals("NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount());
        assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
        assertEquals("NaturalId Cache Puts", 1, stats.getNaturalIdCachePutCount());
        assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
        markRollbackOnly(s);
    });
    // Try NaturalIdLoadAccess after load
    withTxSession(s -> {
        State france = ReadWriteTest.this.getState(s, "Ile de France");
        NaturalIdLoadAccess naturalIdLoader = s.byNaturalId(Citizen.class);
        naturalIdLoader.using("ssn", "1234").using("state", france);
        stats.setStatisticsEnabled(true);
        stats.clear();
        Citizen loadedCitizen = (Citizen) naturalIdLoader.load();
        assertNotNull(loadedCitizen);
        assertEquals("NaturalId Cache Hits", 1, stats.getNaturalIdCacheHitCount());
        assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
        assertEquals("NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount());
        assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
        markRollbackOnly(s);
    });
}
Also used : NaturalIdLoadAccess(org.hibernate.NaturalIdLoadAccess) State(org.hibernate.test.cache.infinispan.functional.entities.State) Citizen(org.hibernate.test.cache.infinispan.functional.entities.Citizen) Statistics(org.hibernate.stat.Statistics) SecondLevelCacheStatistics(org.hibernate.stat.SecondLevelCacheStatistics) Test(org.junit.Test)

Example 2 with NaturalIdLoadAccess

use of org.hibernate.NaturalIdLoadAccess in project hibernate-orm by hibernate.

the class SessionImpl method tryNaturalIdLoadAccess.

/**
	 * Checks to see if the CriteriaImpl is a naturalId lookup that can be done via
	 * NaturalIdLoadAccess
	 *
	 * @param criteria The criteria to check as a complete natural identifier lookup.
	 *
	 * @return A fully configured NaturalIdLoadAccess or null, if null is returned the standard CriteriaImpl execution
	 * should be performed
	 */
private NaturalIdLoadAccess tryNaturalIdLoadAccess(CriteriaImpl criteria) {
    // See if the criteria lookup is by naturalId
    if (!criteria.isLookupByNaturalKey()) {
        return null;
    }
    final String entityName = criteria.getEntityOrClassName();
    final EntityPersister entityPersister = getFactory().getMetamodel().entityPersister(entityName);
    // queries did no natural id validation
    if (!entityPersister.hasNaturalIdentifier()) {
        return null;
    }
    // Since isLookupByNaturalKey is true there can be only one CriterionEntry and getCriterion() will
    // return an instanceof NaturalIdentifier
    final CriterionEntry criterionEntry = criteria.iterateExpressionEntries().next();
    final NaturalIdentifier naturalIdentifier = (NaturalIdentifier) criterionEntry.getCriterion();
    final Map<String, Object> naturalIdValues = naturalIdentifier.getNaturalIdValues();
    final int[] naturalIdentifierProperties = entityPersister.getNaturalIdentifierProperties();
    // Verify the NaturalIdentifier criterion includes all naturalId properties, first check that the property counts match
    if (naturalIdentifierProperties.length != naturalIdValues.size()) {
        return null;
    }
    final String[] propertyNames = entityPersister.getPropertyNames();
    final NaturalIdLoadAccess naturalIdLoader = this.byNaturalId(entityName);
    // Build NaturalIdLoadAccess and in the process verify all naturalId properties were specified
    for (int naturalIdentifierProperty : naturalIdentifierProperties) {
        final String naturalIdProperty = propertyNames[naturalIdentifierProperty];
        final Object naturalIdValue = naturalIdValues.get(naturalIdProperty);
        if (naturalIdValue == null) {
            // A NaturalId property is missing from the critera query, can't use NaturalIdLoadAccess
            return null;
        }
        naturalIdLoader.using(naturalIdProperty, naturalIdValue);
    }
    // Criteria query contains a valid naturalId, use the new API
    log.warn("Session.byNaturalId(" + entityName + ") should be used for naturalId queries instead of Restrictions.naturalId() from a Criteria");
    return naturalIdLoader;
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) NaturalIdLoadAccess(org.hibernate.NaturalIdLoadAccess) SimpleNaturalIdLoadAccess(org.hibernate.SimpleNaturalIdLoadAccess) CriterionEntry(org.hibernate.internal.CriteriaImpl.CriterionEntry) NaturalIdentifier(org.hibernate.criterion.NaturalIdentifier)

Example 3 with NaturalIdLoadAccess

use of org.hibernate.NaturalIdLoadAccess in project hibernate-orm by hibernate.

the class NaturalIdTest method testNaturalIdLoaderCached.

@Test
public void testNaturalIdLoaderCached() {
    Statistics stats = sessionFactory().getStatistics();
    stats.setStatisticsEnabled(true);
    stats.clear();
    assertEquals("NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount());
    assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
    assertEquals("NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount());
    assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
    saveSomeCitizens();
    assertEquals("NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount());
    assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
    assertEquals("NaturalId Cache Puts", 2, stats.getNaturalIdCachePutCount());
    assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
    //Try NaturalIdLoadAccess afterQuery insert
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    State france = this.getState(s, "Ile de France");
    NaturalIdLoadAccess naturalIdLoader = s.byNaturalId(Citizen.class);
    naturalIdLoader.using("ssn", "1234").using("state", france);
    //Not clearing naturalId caches, should be warm from entity loading
    stats.clear();
    // first query
    Citizen citizen = (Citizen) naturalIdLoader.load();
    assertNotNull(citizen);
    assertEquals("NaturalId Cache Hits", 1, stats.getNaturalIdCacheHitCount());
    assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
    assertEquals("NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount());
    assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
    // cleanup
    tx.rollback();
    s.close();
    //Try NaturalIdLoadAccess
    s = openSession();
    tx = s.beginTransaction();
    this.cleanupCache();
    stats.setStatisticsEnabled(true);
    stats.clear();
    // first query
    citizen = (Citizen) s.get(Citizen.class, citizen.getId());
    assertNotNull(citizen);
    assertEquals("NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount());
    assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
    assertEquals("NaturalId Cache Puts", 1, stats.getNaturalIdCachePutCount());
    assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
    // cleanup
    tx.rollback();
    s.close();
    //Try NaturalIdLoadAccess afterQuery load
    s = openSession();
    tx = s.beginTransaction();
    france = this.getState(s, "Ile de France");
    naturalIdLoader = s.byNaturalId(Citizen.class);
    naturalIdLoader.using("ssn", "1234").using("state", france);
    //Not clearing naturalId caches, should be warm from entity loading
    stats.setStatisticsEnabled(true);
    stats.clear();
    // first query
    citizen = (Citizen) naturalIdLoader.load();
    assertNotNull(citizen);
    assertEquals("NaturalId Cache Hits", 1, stats.getNaturalIdCacheHitCount());
    assertEquals("NaturalId Cache Misses", 0, stats.getNaturalIdCacheMissCount());
    assertEquals("NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount());
    assertEquals("NaturalId Cache Queries", 0, stats.getNaturalIdQueryExecutionCount());
    // cleanup
    tx.rollback();
    s.close();
}
Also used : NaturalIdLoadAccess(org.hibernate.NaturalIdLoadAccess) Transaction(org.hibernate.Transaction) Statistics(org.hibernate.stat.Statistics) Session(org.hibernate.Session) Test(org.junit.Test)

Example 4 with NaturalIdLoadAccess

use of org.hibernate.NaturalIdLoadAccess in project hibernate-orm by hibernate.

the class ImmutableEntityNaturalIdTest method testImmutableNaturalIdLifecycle2.

@Test
@TestForIssue(jiraKey = "HHH-7371")
public void testImmutableNaturalIdLifecycle2() {
    Building b1 = new Building();
    b1.setName("Computer Science");
    b1.setAddress("1210 W. Dayton St.");
    b1.setCity("Madison");
    b1.setState("WI");
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(b1);
    tx.commit();
    s.close();
    s = openSession();
    tx = s.beginTransaction();
    NaturalIdLoadAccess naturalIdLoader = s.byNaturalId(Building.class);
    naturalIdLoader.using("address", "1210 W. Dayton St.").using("city", "Madison").using("state", "WI");
    Building building = (Building) naturalIdLoader.getReference();
    assertNotNull(building);
    s.delete(building);
    building = (Building) naturalIdLoader.load();
    //org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [org.hibernate.test.naturalid.immutableentity.Building#1]
    //		at org.hibernate.internal.SessionFactoryImpl$1$1.handleEntityNotFound(SessionFactoryImpl.java:247)
    //		at org.hibernate.event.internal.DefaultLoadEventListener.returnNarrowedProxy(DefaultLoadEventListener.java:282)
    //		at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:248)
    //		at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:148)
    //		at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1079)
    //		at org.hibernate.internal.SessionImpl.access$13(SessionImpl.java:1075)
    //		at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2425)
    //		at org.hibernate.internal.SessionImpl$NaturalIdLoadAccessImpl.load(SessionImpl.java:2586)
    //		at org.hibernate.test.naturalid.immutableentity.ImmutableEntityNaturalIdTest.testImmutableNaturalIdLifecycle2(ImmutableEntityNaturalIdTest.java:188)
    assertNull(building);
    tx.commit();
    s.close();
}
Also used : NaturalIdLoadAccess(org.hibernate.NaturalIdLoadAccess) Transaction(org.hibernate.Transaction) Session(org.hibernate.Session) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 5 with NaturalIdLoadAccess

use of org.hibernate.NaturalIdLoadAccess in project hibernate-orm by hibernate.

the class ImmutableEntityNaturalIdTest method testImmutableNaturalIdLifecycle.

@Test
public void testImmutableNaturalIdLifecycle() {
    Statistics stats = sessionFactory().getStatistics();
    stats.setStatisticsEnabled(true);
    stats.clear();
    assertEquals("Cache hits should be empty", 0, stats.getNaturalIdCacheHitCount());
    assertEquals("Cache misses should be empty", 0, stats.getNaturalIdCacheMissCount());
    assertEquals("Cache put should be empty", 0, stats.getNaturalIdCachePutCount());
    assertEquals("Query count should be empty", 0, stats.getNaturalIdQueryExecutionCount());
    Building b1 = new Building();
    b1.setName("Computer Science");
    b1.setAddress("1210 W. Dayton St.");
    b1.setCity("Madison");
    b1.setState("WI");
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(b1);
    tx.commit();
    s.close();
    assertEquals("Cache hits should be empty", 0, stats.getNaturalIdCacheHitCount());
    assertEquals("Cache misses should be empty", 0, stats.getNaturalIdCacheMissCount());
    assertEquals("Cache put should be one afterQuery insert", 1, stats.getNaturalIdCachePutCount());
    assertEquals("Query count should be empty", 0, stats.getNaturalIdQueryExecutionCount());
    s = openSession();
    tx = s.beginTransaction();
    //Clear caches and reset cache stats
    s.getSessionFactory().getCache().evictNaturalIdRegions();
    stats.clear();
    NaturalIdLoadAccess naturalIdLoader = s.byNaturalId(Building.class);
    naturalIdLoader.using("address", "1210 W. Dayton St.").using("city", "Madison").using("state", "WI");
    // first query
    Building building = (Building) naturalIdLoader.load();
    assertNotNull(building);
    assertEquals("Cache hits should be empty", 0, stats.getNaturalIdCacheHitCount());
    assertEquals("Cache misses should be one afterQuery first query", 1, stats.getNaturalIdCacheMissCount());
    assertEquals("Cache put should be one afterQuery first query", 1, stats.getNaturalIdCachePutCount());
    assertEquals("Query count should be one afterQuery first query", 1, stats.getNaturalIdQueryExecutionCount());
    // cleanup
    tx.rollback();
    s.close();
    //Try two, should be a cache hit
    s = openSession();
    tx = s.beginTransaction();
    naturalIdLoader = s.byNaturalId(Building.class);
    naturalIdLoader.using("address", "1210 W. Dayton St.").using("city", "Madison").using("state", "WI");
    // second query
    building = (Building) naturalIdLoader.load();
    assertNotNull(building);
    assertEquals("Cache hits should be one afterQuery second query", 1, stats.getNaturalIdCacheHitCount());
    assertEquals("Cache misses should be one afterQuery second query", 1, stats.getNaturalIdCacheMissCount());
    assertEquals("Cache put should be one afterQuery second query", 1, stats.getNaturalIdCachePutCount());
    assertEquals("Query count should be one afterQuery second query", 1, stats.getNaturalIdQueryExecutionCount());
    // Try Deleting
    s.delete(building);
    // third query
    building = (Building) naturalIdLoader.load();
    assertNull(building);
    assertEquals("Cache hits should be one afterQuery second query", 1, stats.getNaturalIdCacheHitCount());
    assertEquals("Cache misses should be two afterQuery second query", 2, stats.getNaturalIdCacheMissCount());
    assertEquals("Cache put should be one afterQuery second query", 2, stats.getNaturalIdCachePutCount());
    assertEquals("Query count should be two afterQuery second query", 2, stats.getNaturalIdQueryExecutionCount());
    // cleanup
    tx.commit();
    s.close();
    //Try three, should be db lookup and miss
    s = openSession();
    tx = s.beginTransaction();
    naturalIdLoader = s.byNaturalId(Building.class);
    naturalIdLoader.using("address", "1210 W. Dayton St.").using("city", "Madison").using("state", "WI");
    // second query
    building = (Building) naturalIdLoader.load();
    assertNull(building);
    assertEquals("Cache hits should be one afterQuery third query", 1, stats.getNaturalIdCacheHitCount());
    assertEquals("Cache misses should be one afterQuery third query", 3, stats.getNaturalIdCacheMissCount());
    assertEquals("Cache put should be one afterQuery third query", 2, stats.getNaturalIdCachePutCount());
    assertEquals("Query count should be one afterQuery third query", 3, stats.getNaturalIdQueryExecutionCount());
    // cleanup
    tx.rollback();
    s.close();
}
Also used : NaturalIdLoadAccess(org.hibernate.NaturalIdLoadAccess) Transaction(org.hibernate.Transaction) Statistics(org.hibernate.stat.Statistics) Session(org.hibernate.Session) Test(org.junit.Test)

Aggregations

NaturalIdLoadAccess (org.hibernate.NaturalIdLoadAccess)8 Session (org.hibernate.Session)5 Test (org.junit.Test)5 Transaction (org.hibernate.Transaction)4 Statistics (org.hibernate.stat.Statistics)4 SimpleNaturalIdLoadAccess (org.hibernate.SimpleNaturalIdLoadAccess)2 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Set (java.util.Set)1 EntityManager (javax.persistence.EntityManager)1 NaturalIdentifier (org.hibernate.criterion.NaturalIdentifier)1 CriterionEntry (org.hibernate.internal.CriteriaImpl.CriterionEntry)1 CriteriaLoader (org.hibernate.loader.criteria.CriteriaLoader)1 EntityPersister (org.hibernate.persister.entity.EntityPersister)1 SecondLevelCacheStatistics (org.hibernate.stat.SecondLevelCacheStatistics)1 Citizen (org.hibernate.test.cache.infinispan.functional.entities.Citizen)1 State (org.hibernate.test.cache.infinispan.functional.entities.State)1 TestForIssue (org.hibernate.testing.TestForIssue)1