#671 - ENH: Add support for @View and extra-ddl.xml to nicely support entity beans based on views

This commit is contained in:
Robin Bygrave committed 2016-04-28 20:19:05 +12:00
1 parent 69c2810fbe
commit 81531b6cda
48 files changed
+1187 -255

No files matched your search

@@ -22,9 +22,25 @@ public class CacheChangeSet {
private final Map<ManyKey, ManyChange> manyChangeMap = new HashMap<ManyKey, ManyChange>();
/**
* Apply all the changes to the L2 cache.
* Set of "base tables" modified used to invalidate entities based on views.
*/
public void apply() {
private final Set<String> viewInvalidation = new HashSet<String>();
private final boolean viewEntityInvalidation;
/**
* Construct specifying if we also need to process invalidation for entities based on views.
*/
public CacheChangeSet(boolean viewEntityInvalidation) {
this.viewEntityInvalidation = viewEntityInvalidation;
}
/**
* Apply the changes to the L2 cache except entity/view invalidation.
*
* Return the set of table changes to process invalidation for entities based on views.
*/
public Set<String> apply() {
for (BeanDescriptor entry : queryCaches) {
entry.queryCacheClear();
}
@@ -34,6 +50,7 @@ public class CacheChangeSet {
for (CacheChange entry : manyChangeMap.values()) {
entry.apply();
}
return viewInvalidation;
}
/**
@@ -64,11 +81,23 @@ public class CacheChangeSet {
many(desc, manyProperty).addPut(parentId, entry);
}
/**
* On bean insert register table for view based entity invalidation.
*/
public void addBeanInsert(String baseTable) {
if (viewEntityInvalidation) {
viewInvalidation.add(baseTable);
}
}
/**
* Remove a bean from the cache.
*/
public <T> void addBeanRemove(BeanDescriptor<T> desc, Object id) {
entries.add(new CacheChangeBeanRemove(desc, id));
if (viewEntityInvalidation) {
viewInvalidation.add(desc.getBaseTable());
}
}
/**
@@ -76,6 +105,9 @@ public class CacheChangeSet {
*/
public <T> void addBeanUpdate(BeanDescriptor<T> desc, Object id, Map<String, Object> changes, boolean updateNaturalKey, long version) {
entries.add(new CacheChangeBeanUpdate(desc, id, changes, updateNaturalKey, version));
if (viewEntityInvalidation) {
viewInvalidation.add(desc.getBaseTable());
}
}
/**
@@ -133,7 +133,7 @@ public class BeanDescriptor<T> implements MetaBeanInfo, BeanType<T> {
}
public enum EntityType {
ORM, EMBEDDED, SQL
ORM, EMBEDDED, VIEW, SQL
}
/**
@@ -179,6 +179,8 @@ public class BeanDescriptor<T> implements MetaBeanInfo, BeanType<T> {
private final CompoundUniqueConstraint[] compoundUniqueConstraints;
private final String[] dependentTables;
/**
* The base database table.
*/
@@ -446,6 +448,7 @@ public class BeanDescriptor<T> implements MetaBeanInfo, BeanType<T> {
this.baseTable = InternString.intern(deploy.getBaseTable());
this.baseTableAsOf = deploy.getBaseTableAsOf();
this.baseTableVersionsBetween = deploy.getBaseTableVersionsBetween();
this.dependentTables = deploy.getDependentTables();
this.dbComment = deploy.getDbComment();
this.autoTunable = EntityType.ORM.equals(entityType) && (beanFinder == null);
@@ -1057,6 +1060,13 @@ public class BeanDescriptor<T> implements MetaBeanInfo, BeanType<T> {
return cacheHelp.isBeanCaching();
}
/**
* Return true if there is query caching for this type of bean.
*/
public boolean isQueryCaching() {
return cacheHelp.isQueryCaching();
}
public boolean isManyPropCaching() {
return isBeanCaching();
}
@@ -2325,6 +2335,16 @@ public class BeanDescriptor<T> implements MetaBeanInfo, BeanType<T> {
return dbComment;
}
/**
* Return the dependent tables for a view based entity.
* <p>
* These tables
* </p>
*/
public String[] getDependentTables() {
return dependentTables;
}
/**
* Return the base table. Only properties mapped to the base table are by
* default persisted.
@@ -2333,6 +2353,13 @@ public class BeanDescriptor<T> implements MetaBeanInfo, BeanType<T> {
return baseTable;
}
/**
* Return true if this type is a base table entity type.
*/
public boolean isBaseTable() {
return baseTable != null && entityType == EntityType.ORM;
}
/**
* Return the base table to use given the query temporal mode.
*/
@@ -98,7 +98,7 @@ final class BeanDescriptorCacheHelp<T> {
/**
* Return true if there is currently query caching for this type of bean.
*/
private boolean isQueryCaching() {
boolean isQueryCaching() {
return queryCache != null;
}
@@ -598,6 +598,7 @@ final class BeanDescriptorCacheHelp<T> {
void handleInsert(PersistRequestBean<T> insertRequest, CacheChangeSet changeSet) {
queryCacheClear(changeSet);
cacheDeleteImported(false, insertRequest.getEntityBean(), changeSet);
changeSet.addBeanInsert(desc.getBaseTable());
}
private void cacheDeleteImported(boolean clear, EntityBean entityBean, CacheChangeSet changeSet) {
@@ -124,7 +124,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
private final DocStoreFactory docStoreFactory;
private int enhancedClassCount;
private final boolean updateChangesOnly;
private final BootupClasses bootupClasses;
@@ -143,6 +143,8 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
private final Map<String, List<BeanDescriptor<?>>> tableToDescMap = new HashMap<String, List<BeanDescriptor<?>>>();
private final Map<String, List<BeanDescriptor<?>>> tableToViewDescMap = new HashMap<String, List<BeanDescriptor<?>>>();
private List<BeanDescriptor<?>> immutableDescriptorList;
private final DbIdentity dbIdentity;
@@ -174,12 +176,12 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
/**
* Map of base tables to 'with history views' used to support 'as of' queries.
*/
private final Map<String,String> asOfTableMap = new HashMap<String, String>();
private final Map<String, String> asOfTableMap = new HashMap<String, String>();
/**
* Map of base tables to 'draft' tables.
*/
private final Map<String,String> draftTableMap = new HashMap<String, String>();
private final Map<String, String> draftTableMap = new HashMap<String, String>();
/**
* Create for a given database dbConfig.
@@ -235,7 +237,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
DbHistorySupport historySupport = databasePlatform.getHistorySupport();
// with historySupport returns a simple view suffix or the sql2011 as of timestamp suffix
return (historySupport == null ) ? serverConfig.getAsOfViewSuffix() : historySupport.getAsOfViewSuffix(serverConfig.getAsOfViewSuffix());
return (historySupport == null) ? serverConfig.getAsOfViewSuffix() : historySupport.getAsOfViewSuffix(serverConfig.getAsOfViewSuffix());
}
/**
@@ -245,7 +247,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
DbHistorySupport historySupport = databasePlatform.getHistorySupport();
// with historySupport returns a simple view suffix or the sql2011 versions between timestamp suffix
return (historySupport == null ) ? serverConfig.getAsOfViewSuffix() : historySupport.getVersionsBetweenSuffix(serverConfig.getAsOfViewSuffix());
return (historySupport == null) ? serverConfig.getAsOfViewSuffix() : historySupport.getVersionsBetweenSuffix(serverConfig.getAsOfViewSuffix());
}
@Override
@@ -300,14 +302,14 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
/**
* Return the map of base tables to draft tables.
*/
public Map<String,String> getDraftTableMap() {
public Map<String, String> getDraftTableMap() {
return draftTableMap;
}
/**
* Deploy returning the asOfTableMap (which is required by the SQL builders).
*/
public Map<String,String> deploy() {
public Map<String, String> deploy() {
try {
createListeners();
@@ -356,10 +358,19 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
*/
public void cacheNotify(TransactionEventTable.TableIUD tableIUD) {
List<BeanDescriptor<?>> list = getBeanDescriptors(tableIUD.getTableName());
if (list != null) {
for (int i = 0; i < list.size(); i++) {
list.get(i).cacheHandleBulkUpdate(tableIUD);
String tableName = tableIUD.getTableName().toLowerCase();
List<BeanDescriptor<?>> normalBeanTypes = tableToDescMap.get(tableName);
if (normalBeanTypes != null) {
// 'normal' entity beans based on a "base table"
for (int i = 0; i < normalBeanTypes.size(); i++) {
normalBeanTypes.get(i).cacheHandleBulkUpdate(tableIUD);
}
}
List<BeanDescriptor<?>> viewBeans = tableToViewDescMap.get(tableName);
if (viewBeans != null) {
// entity beans based on a "view"
for (int i = 0; i < viewBeans.size(); i++) {
viewBeans.get(i).cacheHandleBulkUpdate(tableIUD);
}
}
}
@@ -378,6 +389,21 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
return tableToDescMap.get(tableName.toLowerCase());
}
/**
* Invalidate entity beans based on views via their dependent tables.
*/
public void processViewInvalidation(Set<String> viewInvalidation) {
for (String depTable : viewInvalidation) {
List<BeanDescriptor<?>> list = tableToViewDescMap.get(depTable.toLowerCase());
if (list == null) {
for (int i = 0; i < list.size(); i++) {
list.get(i).queryCacheClear();
}
}
}
}
/**
* Build a map of table names to BeanDescriptors.
* <p>
@@ -390,7 +416,6 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
String baseTable = desc.getBaseTable();
if (baseTable != null) {
baseTable = baseTable.toLowerCase();
List<BeanDescriptor<?>> list = tableToDescMap.get(baseTable);
if (list == null) {
list = new ArrayList<BeanDescriptor<?>>(1);
@@ -398,6 +423,22 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
}
list.add(desc);
}
if (desc.getEntityType() == EntityType.VIEW && desc.isQueryCaching()) {
// build map of tables to view entities dependent on those tables
// for the purpose of invalidating appropriate query caches
String[] dependentTables = desc.getDependentTables();
if (dependentTables != null && dependentTables.length > 0) {
for (String depTable : dependentTables) {
depTable = depTable.toLowerCase();
List<BeanDescriptor<?>> list = tableToViewDescMap.get(depTable);
if (list == null) {
list = new ArrayList<BeanDescriptor<?>>(1);
tableToViewDescMap.put(depTable, list);
}
list.add(desc);
}
}
}
}
}
@@ -487,6 +528,14 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
throw new PersistenceException(msg, source);
}
/**
* Return true if there are 'view based entities' using l2 query caching and so need
* to be invalidated based on changes to dependent tables.
*/
public boolean requiresViewEntityCacheInvalidation() {
return !tableToViewDescMap.isEmpty();
}
/**
* Return an immutable list of all the BeanDescriptors.
*/
@@ -539,7 +588,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
* Return the bean deploy info for the given class.
*/
public <T> DeployBeanInfo<T> getDeploy(Class<T> cls) {
return (DeployBeanInfo<T>) deplyInfoMap.get(cls);
return (DeployBeanInfo<T>) deplyInfoMap.get(cls);
}
private void registerBeanDescriptor(BeanDescriptor<?> desc) {
@@ -651,7 +700,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@SuppressWarnings({"unchecked", "rawtypes"})
private void readEntityRelationships() {
// We only perform 'circular' checks etc after we have
@@ -667,9 +716,9 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
// Set inheritance info
for (DeployBeanInfo<?> info : deplyInfoMap.values()) {
setInheritanceInfo(info);
setInheritanceInfo(info);
}
for (DeployBeanInfo<?> info : deplyInfoMap.values()) {
registerBeanDescriptor(new BeanDescriptor(this, info.getDescriptor()));
}
@@ -681,24 +730,24 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
* @param info the new inheritance info
*/
private void setInheritanceInfo(DeployBeanInfo<?> info) {
for (DeployBeanPropertyAssocOne<?> oneProp : info.getDescriptor().propertiesAssocOne()) {
if (!oneProp.isTransient()) {
DeployBeanInfo<?> assoc = deplyInfoMap.get(oneProp.getTargetType());
if (assoc != null){
oneProp.getTableJoin().setInheritInfo(assoc.getDescriptor().getInheritInfo());
}
}
}
for (DeployBeanPropertyAssocMany<?> manyProp : info.getDescriptor().propertiesAssocMany()) {
if (!manyProp.isTransient()) {
DeployBeanInfo<?> assoc = deplyInfoMap.get(manyProp.getTargetType());
if (assoc != null){
manyProp.getTableJoin().setInheritInfo(assoc.getDescriptor().getInheritInfo());
}
}
}
for (DeployBeanPropertyAssocOne<?> oneProp : info.getDescriptor().propertiesAssocOne()) {
if (!oneProp.isTransient()) {
DeployBeanInfo<?> assoc = deplyInfoMap.get(oneProp.getTargetType());
if (assoc != null) {
oneProp.getTableJoin().setInheritInfo(assoc.getDescriptor().getInheritInfo());
}
}
}
for (DeployBeanPropertyAssocMany<?> manyProp : info.getDescriptor().propertiesAssocMany()) {
if (!manyProp.isTransient()) {
DeployBeanInfo<?> assoc = deplyInfoMap.get(manyProp.getTargetType());
if (assoc != null) {
manyProp.getTableJoin().setInheritInfo(assoc.getDescriptor().getInheritInfo());
}
}
}
}
private void secondaryPropsJoins(DeployBeanInfo<?> info) {
@@ -845,7 +894,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
* into the order_id column on the order_lines table).
* </p>
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@SuppressWarnings({"unchecked", "rawtypes"})
private void makeUnidirectional(DeployBeanInfo<?> info, DeployBeanPropertyAssocMany<?> oneToMany) {
DeployBeanDescriptor<?> targetDesc = getTargetDescriptor(oneToMany);
@@ -1081,7 +1130,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
desc.setUpdateChangesOnly(updateChangesOnly);
beanLifecycleAdapterFactory.addLifecycleMethods(desc);
// set bean controller, finder and listener
setBeanControllerFinderListener(desc);
deplyInherit.process(desc);
@@ -1103,8 +1152,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
readXml(desc);
if (!EntityType.ORM.equals(desc.getEntityType())) {
// not using base table
if (EntityType.SQL == desc.getEntityType()) {
desc.setBaseTable(null, null, null);
}
@@ -1373,7 +1421,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
Class<?> beanType = desc.getBeanType();
BeanPropertiesReader reflectProps = new BeanPropertiesReader(beanType);
BeanPropertyInfo beanReflect = reflectFactory.create(beanType);
desc.setProperties(reflectProps.getProperties());
@@ -1384,7 +1432,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
if (isPersistentField(prop)) {
throw new IllegalStateException("Property " + propName + " not found in " + reflectProps + " for type " + beanType);
}
} else {
final int propertyIndex = pos;
prop.setPropertyIndex(propertyIndex);
@@ -1459,7 +1507,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
Class<?> beanClass = desc.getBeanType();
if (!hasEntityBeanInterface(beanClass)) {
throw new IllegalStateException("Bean "+beanClass+" is not enhanced?");
throw new IllegalStateException("Bean " + beanClass + " is not enhanced?");
}
// the bean already implements EntityBean
@@ -1475,7 +1523,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
* enhanced or all dynamically subclassed).
*/
private void checkInheritedClasses(Class<?> beanClass) {
Class<?> superclass = beanClass.getSuperclass();
if (Object.class.equals(superclass)) {
// we got to the top of the inheritance
@@ -1490,9 +1538,9 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
// ok to stop and treat just the same as Object.class
return;
}
throw new IllegalStateException("Super type "+superclass+" is not enhanced?");
throw new IllegalStateException("Super type " + superclass + " is not enhanced?");
}
// recursively continue up the inheritance hierarchy
checkInheritedClasses(superclass);
}
@@ -1502,7 +1550,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
* If so it is ok for it not to be enhanced.
*/
private boolean isMappedSuperWithNoProperties(Class<?> beanClass) {
MappedSuperclass annotation = beanClass.getAnnotation(MappedSuperclass.class);
if (annotation == null) {
return false;
@@ -129,6 +129,8 @@ public class DeployBeanDescriptor<T> {
private String draftTable;
private String[] dependentTables;
private boolean historySupport;
private boolean readAuditing;
@@ -582,6 +584,13 @@ public class DeployBeanDescriptor<T> {
return draftTable;
}
/**
* For view based entity return the dependant tables.
*/
public String[] getDependentTables() {
return dependentTables;
}
/**
* Return the base table. Only properties mapped to the base table are by
* default persisted.
@@ -611,6 +620,15 @@ public class DeployBeanDescriptor<T> {
return baseTableFull;
}
/**
* Set when entity is based on a view.
*/
public void setView(String viewName, String[] dependentTables) {
this.entityType = EntityType.VIEW;
this.dependentTables = this.dependentTables;
setBaseTable(new TableName(viewName), "", "");
}
/**
* Set the base table. Only properties mapped to the base table are by default persisted.
*/
@@ -1,31 +0,0 @@
package com.avaje.ebeaninternal.server.deploy.parse;
import com.avaje.ebean.config.TableName;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanTable;
/**
* Read the annotations for BeanTable.
* <p>
* Refer to BeanTable but basically determining base table, table alias
* and the unique id properties.
* </p>
*/
public class AnnotationBeanTable extends AnnotationBase {
final DeployBeanTable beanTable;
public AnnotationBeanTable(DeployUtil util, DeployBeanTable beanTable){
super(util);
this.beanTable = beanTable;
}
/**
* Parse the annotations.
*/
public void parse() {
TableName tableName = namingConvention.getTableName(beanTable.getBeanType());
beanTable.setBaseTable(tableName.getQualifiedName());
}
}
@@ -22,6 +22,7 @@ import com.avaje.ebean.annotation.NamedUpdate;
import com.avaje.ebean.annotation.NamedUpdates;
import com.avaje.ebean.annotation.ReadAudit;
import com.avaje.ebean.annotation.UpdateMode;
import com.avaje.ebean.annotation.View;
import com.avaje.ebean.config.TableName;
import com.avaje.ebeaninternal.server.core.CacheOptions;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor.EntityType;
@@ -136,13 +137,15 @@ public class AnnotationClass extends AnnotationParser {
descriptor.addCompoundUniqueConstraint(new CompoundUniqueConstraint(uc.columnNames()));
}
View view = cls.getAnnotation(View.class);
if (view != null) {
descriptor.setView(view.name(), view.dependentTables());
}
Table table = cls.getAnnotation(Table.class);
if (table != null) {
UniqueConstraint[] uniqueConstraints = table.uniqueConstraints();
if (uniqueConstraints != null) {
for (UniqueConstraint c : uniqueConstraints) {
descriptor.addCompoundUniqueConstraint(new CompoundUniqueConstraint(c.columnNames()));
}
for (UniqueConstraint c : uniqueConstraints) {
descriptor.addCompoundUniqueConstraint(new CompoundUniqueConstraint(c.columnNames()));
}
}
@@ -84,9 +84,9 @@ public final class PostCommitProcessing {
/**
* Notify the local part of L2 cache.
*/
void notifyLocalCache() {
void notifyLocalCache(boolean viewInvalidation) {
processTableEvents(event.getEventTables());
cacheChanges = event.buildCacheChanges();
cacheChanges = event.buildCacheChanges(viewInvalidation);
}
/**
@@ -149,7 +149,7 @@ public final class PostCommitProcessing {
return new Runnable() {
public void run() {
if (cacheChanges != null) {
cacheChanges.apply();
manager.processViewInvalidation(cacheChanges.apply());
}
localPersistListenersNotify();
notifyCluster();
@@ -27,6 +27,7 @@ import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
/**
@@ -104,6 +105,8 @@ public class TransactionManager {
*/
private final ChangeLogListener changeLogListener;
private final boolean viewInvalidation;
/**
* Create the TransactionManager
*/
@@ -113,6 +116,7 @@ public class TransactionManager {
this.persistBatch = config.getPersistBatch();
this.persistBatchOnCascade = config.appliedPersistBatchOnCascade();
this.beanDescriptorManager = descMgr;
this.viewInvalidation = descMgr.requiresViewEntityCacheInvalidation();
this.changeLogPrepare = descMgr.getChangeLogPrepare();
this.changeLogListener = descMgr.getChangeLogListener();
this.clusterManager = clusterManager;
@@ -398,7 +402,7 @@ public class TransactionManager {
}
PostCommitProcessing postCommit = new PostCommitProcessing(clusterManager, this, transaction);
postCommit.notifyLocalCache();
postCommit.notifyLocalCache(viewInvalidation);
backgroundExecutor.execute(postCommit.backgroundNotify());
for (TransactionEventListener listener : transactionEventListeners) {
@@ -423,7 +427,7 @@ public class TransactionManager {
event.add(tableEvents);
PostCommitProcessing postCommit = new PostCommitProcessing(clusterManager, this, event);
postCommit.notifyLocalCache();
postCommit.notifyLocalCache(viewInvalidation);
backgroundExecutor.execute(postCommit.backgroundNotify());
}
@@ -478,4 +482,13 @@ public class TransactionManager {
});
}
}
/**
* Invalidate the query caches for entities based on views.
*/
public void processViewInvalidation(Set<String> viewInvalidation) {
if (!viewInvalidation.isEmpty()) {
beanDescriptorManager.processViewInvalidation(viewInvalidation);
}
}
}