diff --git a/src/main/java/com/avaje/ebean/Transaction.java b/src/main/java/com/avaje/ebean/Transaction.java index 8be8ee2bf..cd2db3004 100644 --- a/src/main/java/com/avaje/ebean/Transaction.java +++ b/src/main/java/com/avaje/ebean/Transaction.java @@ -3,6 +3,7 @@ package com.avaje.ebean; import com.avaje.ebean.annotation.DocStoreMode; import com.avaje.ebean.config.DocStoreConfig; import com.avaje.ebean.config.PersistBatch; +import com.avaje.ebean.config.ServerConfig; import javax.persistence.PersistenceException; import javax.persistence.RollbackException; @@ -125,13 +126,78 @@ public interface Transaction extends Closeable { * Set to true when you want all loaded properties to be included in the update * (rather than just the changed properties). *

- * You might set this when using JDBC batch in order to get multiple updates - * with slightly different sets of changed properties into the same statement - * and hence better JDBC batch performance. + * You might set this when using JDBC batch in order to get multiple updates + * with slightly different sets of changed properties into the same statement + * and hence better JDBC batch performance. *

*/ void setUpdateAllLoadedProperties(boolean updateAllLoadedProperties); + /** + * Set if the L2 cache should be skipped for "find by id" and "find by natural key" queries. + *

+ * By default {@link ServerConfig#isSkipCacheAfterWrite()} is true and that means that for + * "find by id" and "find by natural key" queries which normally hit L2 bean cache automatically + * - will not do so after a persist/write on the transaction. + *

+ *

+ * This method provides explicit control over whether "find by id" and "find by natural key" + * will skip the L2 bean cache or not (regardless of whether the transaction is considered "read only"). + *

+ *

+ * Refer to {@link ServerConfig#setSkipCacheAfterWrite(boolean)} for configuring the default behavior + * for using the L2 bean cache in transactions spanning multiple query/persist requests. + *

+ * + *
{@code
+   *
+   *   // assume Customer has L2 bean caching enabled ...
+   *
+   *   Transaction transaction = Ebean.beginTransaction();
+   *   try {
+   *
+   *     // this uses L2 bean cache as the transaction
+   *     // ... is considered "query only" at this point
+   *     Customer.find.byId(42);
+   *
+   *     // transaction no longer "query only" once
+   *     // ... a bean has been saved etc
+   *     Ebean.save(someBean);
+   *
+   *     // will NOT use L2 bean cache as the transaction
+   *     // ... is no longer considered "query only"
+   *     Customer.find.byId(55);
+   *
+   *
+   *
+   *     // explicit control - please use L2 bean cache
+   *
+   *     transaction.setSkipCache(false);
+   *     Customer.find.byId(77); // hit the l2 bean cache
+   *
+   *
+   *     // explicit control - please don't use L2 bean cache
+   *
+   *     transaction.setSkipCache(true);
+   *     Customer.find.byId(99); // skips l2 bean cache
+   *
+   *
+   *   } finally {
+   *     transaction.end();
+   *   }
+   *
+   * }
+ * + * @see ServerConfig#isSkipCacheAfterWrite() + */ + void setSkipCache(boolean skipCache); + + /** + * Return true if the L2 cache should be skipped. More accurately if true then find by id + * and find by natural key queries should NOT automatically use the L2 bean cache. + */ + boolean isSkipCache(); + /** * Turn on or off statement batching. Statement batching can be transparent * for drivers and databases that support getGeneratedKeys. Otherwise you may diff --git a/src/main/java/com/avaje/ebean/config/ServerConfig.java b/src/main/java/com/avaje/ebean/config/ServerConfig.java index cf4598009..32cea0f65 100644 --- a/src/main/java/com/avaje/ebean/config/ServerConfig.java +++ b/src/main/java/com/avaje/ebean/config/ServerConfig.java @@ -220,6 +220,11 @@ public class ServerConfig { private String ddlSeedSql; + /** + * When true L2 bean cache use is skipped after a write has occurred on a transaction. + */ + private boolean skipCacheAfterWrite = true; + private boolean useJtaTransactionManager; /** @@ -1795,6 +1800,66 @@ public class ServerConfig { return classes; } + /** + * Return true if L2 bean cache should be skipped once writes have occurred on a transaction. + *

+ * This defaults to true and means that for "find by id" and "find by natural key" + * queries that normally hit L2 bean cache automatically will not do so after a write/persist + * on the transaction. + *

+ * + *
{@code
+   *
+   *   // assume Customer has L2 bean caching enabled ...
+   *
+   *   Transaction transaction = Ebean.beginTransaction();
+   *   try {
+   *
+   *     // this uses L2 bean cache as the transaction
+   *     // ... is considered "query only" at this point
+   *     Customer.find.byId(42);
+   *
+   *     // transaction no longer "query only" once
+   *     // ... a bean has been saved etc
+   *     Ebean.save(someBean);
+   *
+   *     // will NOT use L2 bean cache as the transaction
+   *     // ... is no longer considered "query only"
+   *     Customer.find.byId(55);
+   *
+   *
+   *
+   *     // explicit control - please use L2 bean cache
+   *
+   *     transaction.setSkipCache(false);
+   *     Customer.find.byId(77); // hit the l2 bean cache
+   *
+   *
+   *     // explicit control - please don't use L2 bean cache
+   *
+   *     transaction.setSkipCache(true);
+   *     Customer.find.byId(99); // skips l2 bean cache
+   *
+   *
+   *   } finally {
+   *     transaction.end();
+   *   }
+   *
+   * }
+ * + * @see com.avaje.ebean.Transaction#setSkipCache(boolean) + */ + public boolean isSkipCacheAfterWrite() { + return skipCacheAfterWrite; + } + + /** + * Set to false when we still want to hit the cache after a write has occurred on a transaction. + */ + public void setSkipCacheAfterWrite(boolean skipCacheAfterWrite) { + this.skipCacheAfterWrite = skipCacheAfterWrite; + } + /** * Return true to only update changed properties. */ @@ -2312,6 +2377,7 @@ public class ServerConfig { collectQueryStatsByNode = p.getBoolean("collectQueryStatsByNode", collectQueryStatsByNode); collectQueryOrigins = p.getBoolean("collectQueryOrigins", collectQueryOrigins); + skipCacheAfterWrite = p.getBoolean("skipCacheAfterWrite", skipCacheAfterWrite); updateAllPropertiesInBatch = p.getBoolean("updateAllPropertiesInBatch", updateAllPropertiesInBatch); updateChangesOnly = p.getBoolean("updateChangesOnly", updateChangesOnly); diff --git a/src/main/java/com/avaje/ebeaninternal/api/ScopedTransaction.java b/src/main/java/com/avaje/ebeaninternal/api/ScopedTransaction.java index 17116e2c0..a8a98d5c2 100644 --- a/src/main/java/com/avaje/ebeaninternal/api/ScopedTransaction.java +++ b/src/main/java/com/avaje/ebeaninternal/api/ScopedTransaction.java @@ -105,6 +105,16 @@ public class ScopedTransaction implements SpiTransaction { transaction.logSummary(msg); } + @Override + public void setSkipCache(boolean skipCache) { + transaction.setSkipCache(skipCache); + } + + @Override + public boolean isSkipCache() { + return transaction.isSkipCache(); + } + @Override public void addBeanChange(BeanChange beanChange) { transaction.addBeanChange(beanChange); diff --git a/src/main/java/com/avaje/ebeaninternal/server/core/DefaultServer.java b/src/main/java/com/avaje/ebeaninternal/server/core/DefaultServer.java index 1546a2428..9d1f494ec 100644 --- a/src/main/java/com/avaje/ebeaninternal/server/core/DefaultServer.java +++ b/src/main/java/com/avaje/ebeaninternal/server/core/DefaultServer.java @@ -991,7 +991,7 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer { } } - if (!query.isUseBeanCache()) { + if (!query.isUseBeanCache() || (t != null && t.isSkipCache())) { return null; } @@ -1041,26 +1041,32 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer { } } - public T findUnique(Query query, Transaction t) { + public T findUnique(Query query, Transaction transaction) { Object id = query.getId(); if (id != null) { // actually a find by Id query - return findId(query, t); + return findId(query, transaction); } SpiQuery spiQuery = (SpiQuery) query; BeanDescriptor desc = spiQuery.getBeanDescriptor(); - id = desc.cacheNaturalKeyIdLookup(spiQuery); - if (id != null) { - T bean = findIdCheckPersistenceContextAndCache(t, spiQuery, id); - if (bean != null) { - return bean; + SpiTransaction t = (SpiTransaction) transaction; + if (t == null) { + t = getCurrentServerTransaction(); + } + if (t == null || !t.isSkipCache()) { + id = desc.cacheNaturalKeyIdLookup(spiQuery); + if (id != null) { + T bean = findIdCheckPersistenceContextAndCache(t, spiQuery, id); + if (bean != null) { + return bean; + } } } - // a query that is expected to return either 0 or 1 rows + // a query that is expected to return either 0 or 1 beans List list = findList(query, t); return extractUnique(list); } diff --git a/src/main/java/com/avaje/ebeaninternal/server/deploy/BeanDescriptorCacheHelp.java b/src/main/java/com/avaje/ebeaninternal/server/deploy/BeanDescriptorCacheHelp.java index 5ab077b3b..12a06bc67 100644 --- a/src/main/java/com/avaje/ebeaninternal/server/deploy/BeanDescriptorCacheHelp.java +++ b/src/main/java/com/avaje/ebeaninternal/server/deploy/BeanDescriptorCacheHelp.java @@ -326,7 +326,7 @@ final class BeanDescriptorCacheHelp { // try to lookup the id using the natural key Object id = naturalKeyCache.get(keyBindParam.getValue()); - if (natLog.isTraceEnabled() && id != null) { + if (natLog.isTraceEnabled()) { natLog.trace(" LOOKUP {}({}) - id:{}", cacheName, keyBindParam.getValue(), id); } return id; diff --git a/src/main/java/com/avaje/ebeaninternal/server/transaction/JdbcTransaction.java b/src/main/java/com/avaje/ebeaninternal/server/transaction/JdbcTransaction.java index d49c86bbe..9edd8b395 100644 --- a/src/main/java/com/avaje/ebeaninternal/server/transaction/JdbcTransaction.java +++ b/src/main/java/com/avaje/ebeaninternal/server/transaction/JdbcTransaction.java @@ -4,6 +4,7 @@ import com.avaje.ebean.TransactionCallback; import com.avaje.ebean.annotation.DocStoreMode; import com.avaje.ebean.bean.PersistenceContext; import com.avaje.ebean.config.PersistBatch; +import com.avaje.ebean.config.ServerConfig; import com.avaje.ebean.config.dbplatform.DatabasePlatform.OnQueryOnly; import com.avaje.ebean.event.changelog.BeanChange; import com.avaje.ebean.event.changelog.ChangeSet; @@ -151,6 +152,16 @@ public class JdbcTransaction implements SpiTransaction { protected int docStoreBatchSize; + /** + * Explicit control over skipCache. + */ + protected Boolean skipCache; + + /** + * Default skip cache behavior from {@link ServerConfig#isSkipCacheAfterWrite()}. + */ + protected final boolean skipCacheAfterWrite; + /** * Create a new JdbcTransaction. */ @@ -162,11 +173,20 @@ public class JdbcTransaction implements SpiTransaction { this.explicit = explicit; this.manager = manager; this.connection = connection; - this.batchMode = manager == null ? PersistBatch.NONE : manager.getPersistBatch(); - this.batchOnCascadeMode = manager == null ? PersistBatch.NONE : manager.getPersistBatchOnCascade(); - this.onQueryOnly = manager == null ? OnQueryOnly.ROLLBACK : manager.getOnQueryOnly(); this.persistenceContext = new DefaultPersistenceContext(); + if (manager == null) { + this.skipCacheAfterWrite = true; + this.batchMode = PersistBatch.NONE; + this.batchOnCascadeMode = PersistBatch.NONE; + this.onQueryOnly = OnQueryOnly.ROLLBACK; + } else { + this.skipCacheAfterWrite = manager.isSkipCacheAfterWrite(); + this.batchMode = manager.getPersistBatch(); + this.batchOnCascadeMode = manager.getPersistBatchOnCascade(); + this.onQueryOnly = manager.getOnQueryOnly(); + } + checkAutoCommit(connection); } catch (Exception e) { @@ -197,6 +217,17 @@ public class JdbcTransaction implements SpiTransaction { return sb.toString(); } + @Override + public boolean isSkipCache() { + if (skipCache != null) return skipCache; + return skipCacheAfterWrite && !queryOnly; + } + + @Override + public void setSkipCache(boolean skipCache) { + this.skipCache = skipCache; + } + @Override public String getLogPrefix() { return logPrefix; diff --git a/src/main/java/com/avaje/ebeaninternal/server/transaction/TransactionManager.java b/src/main/java/com/avaje/ebeaninternal/server/transaction/TransactionManager.java index aa9db8dad..0086f4e4e 100644 --- a/src/main/java/com/avaje/ebeaninternal/server/transaction/TransactionManager.java +++ b/src/main/java/com/avaje/ebeaninternal/server/transaction/TransactionManager.java @@ -109,12 +109,15 @@ public class TransactionManager { protected final boolean viewInvalidation; + private final boolean skipCacheAfterWrite; + /** * Create the TransactionManager */ public TransactionManager(boolean localL2Caching, ServerConfig config, ClusterManager clusterManager, BackgroundExecutor backgroundExecutor, DocStoreUpdateProcessor docStoreUpdateProcessor, BeanDescriptorManager descMgr, BootupClasses bootupClasses) { + this.skipCacheAfterWrite = config.isSkipCacheAfterWrite(); this.localL2Caching = localL2Caching; this.persistBatch = config.getPersistBatch(); this.persistBatchOnCascade = config.appliedPersistBatchOnCascade(); @@ -149,6 +152,10 @@ public class TransactionManager { return docStoreActive; } + public boolean isSkipCacheAfterWrite() { + return skipCacheAfterWrite; + } + public BeanDescriptorManager getBeanDescriptorManager() { return beanDescriptorManager; } diff --git a/src/test/java/com/avaje/ebeaninternal/server/transaction/JdbcTransactionTest.java b/src/test/java/com/avaje/ebeaninternal/server/transaction/JdbcTransactionTest.java new file mode 100644 index 000000000..7d9b5ecc6 --- /dev/null +++ b/src/test/java/com/avaje/ebeaninternal/server/transaction/JdbcTransactionTest.java @@ -0,0 +1,77 @@ +package com.avaje.ebeaninternal.server.transaction; + +import com.avaje.ebean.Ebean; +import com.avaje.ebean.Transaction; +import com.avaje.ebean.cache.ServerCache; +import com.avaje.ebean.cache.ServerCacheManager; +import com.avaje.tests.model.basic.Contact; +import com.avaje.tests.model.basic.Customer; +import com.avaje.tests.model.basic.EBasic; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JdbcTransactionTest { + + @Test + public void isSkipCache() throws Exception { + + Transaction transaction = Ebean.beginTransaction(); + try { + // implicitly skip false due to query only at this point + assertThat(transaction.isSkipCache()).isFalse(); + + EBasic basic = new EBasic("b1"); + Ebean.save(basic); + + // implicitly skip true due to save + assertThat(transaction.isSkipCache()).isTrue(); + + Customer.find.byId(1); + + // explicit control + transaction.setSkipCache(false); + assertThat(transaction.isSkipCache()).isFalse(); + + transaction.setSkipCache(true); + assertThat(transaction.isSkipCache()).isTrue(); + + } finally { + transaction.end(); + } + } + + @Test + public void skipCacheAfterSave() throws Exception { + + ServerCacheManager cacheManager = Ebean.getDefaultServer().getServerCacheManager(); + ServerCache customerBeanCache = cacheManager.getBeanCache(Customer.class); + ServerCache contactNatKeyCache = cacheManager.getNaturalKeyCache(Contact.class); + + Transaction transaction = Ebean.beginTransaction(); + try { + customerBeanCache.getStatistics(true); + contactNatKeyCache.getStatistics(true); + + Customer.find.byId(19898989); + Ebean.find(Contact.class).where().eq("email","junk@foo.com").findUnique(); + + assertThat(customerBeanCache.getStatistics(true).getMissCount()).isEqualTo(1); + assertThat(contactNatKeyCache.getStatistics(true).getMissCount()).isEqualTo(1); + + EBasic basic = new EBasic("b1"); + Ebean.save(basic); + + // these don't hit L2 cache due to the save of b1 + Customer.find.byId(29898989); + Ebean.find(Contact.class).where().eq("email","junk2@foo.com").findUnique(); + + assertThat(customerBeanCache.getStatistics(true).getMissCount()).isEqualTo(0); + assertThat(contactNatKeyCache.getStatistics(true).getMissCount()).isEqualTo(0); + + } finally { + transaction.end(); + } + } + +} \ No newline at end of file diff --git a/src/test/java/com/avaje/tests/model/basic/EBasic.java b/src/test/java/com/avaje/tests/model/basic/EBasic.java index a7a12b599..d64e8d036 100644 --- a/src/test/java/com/avaje/tests/model/basic/EBasic.java +++ b/src/test/java/com/avaje/tests/model/basic/EBasic.java @@ -35,6 +35,14 @@ public class EBasic { Timestamp someDate; + public EBasic() { + + } + + public EBasic(String name) { + this.name = name; + } + public Integer getId() { return id; } diff --git a/src/test/resources/test-ebean.properties b/src/test/resources/test-ebean.properties index 3ee993b51..b64de6610 100644 --- a/src/test/resources/test-ebean.properties +++ b/src/test/resources/test-ebean.properties @@ -2,4 +2,6 @@ datasource.h2.username=sa ebean.jodaLocalTimeMode=normal -#ebean.jodaLocalTimeMode=utc \ No newline at end of file +#ebean.jodaLocalTimeMode=utc + +#ebean.skipCacheAfterWrite=false \ No newline at end of file