Fixes for #94 - Additional API - added update(Collection beans); and insert(Collection beans); and #93 - ebean.properties defaultDeleteMissingChildren moved to updatesDeleteMissingChildren

This commit is contained in:
Rob Bygrave committed 2014-04-26 23:43:08 +12:00
1 parent e1ec0bcdfe
commit 1a13fc9742
19 files changed
+627 -344

No files matched your search

@@ -21,18 +21,18 @@ public abstract class BeanRequest {
/**
* The server processing the request.
*/
final SpiEbeanServer ebeanServer;
protected final SpiEbeanServer ebeanServer;
final String serverName;
protected final String serverName;
/**
* The transaction this is part of.
*/
SpiTransaction transaction;
protected SpiTransaction transaction;
boolean createdTransaction;
protected boolean createdTransaction;
boolean readOnly;
protected boolean readOnly;
public BeanRequest(SpiEbeanServer ebeanServer, SpiTransaction t) {
this.ebeanServer = ebeanServer;
@@ -90,7 +90,6 @@ import com.avaje.ebeaninternal.server.deploy.InheritInfo;
import com.avaje.ebeaninternal.server.el.ElFilter;
import com.avaje.ebeaninternal.server.jmx.MAdminAutofetch;
import com.avaje.ebeaninternal.server.lib.ShutdownManager;
import com.avaje.ebeaninternal.server.loadcontext.DLoadContext;
import com.avaje.ebeaninternal.server.query.CQuery;
import com.avaje.ebeaninternal.server.query.CQueryEngine;
import com.avaje.ebeaninternal.server.query.CallableQueryIds;
@@ -105,7 +104,6 @@ import com.avaje.ebeaninternal.server.query.SqlQueryFutureList;
import com.avaje.ebeaninternal.server.querydefn.DefaultOrmQuery;
import com.avaje.ebeaninternal.server.querydefn.DefaultOrmUpdate;
import com.avaje.ebeaninternal.server.querydefn.DefaultRelationalQuery;
import com.avaje.ebeaninternal.server.querydefn.NaturalKeyBindParam;
import com.avaje.ebeaninternal.server.text.csv.TCsvReader;
import com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext;
import com.avaje.ebeaninternal.server.transaction.RemoteTransactionEvent;
@@ -125,6 +123,8 @@ public final class DefaultServer implements SpiEbeanServer {
private static final String AVAJE_EBEAN = Ebean.class.getName().substring(0, 15);
private final ServerConfig serverConfig;
private final String serverName;
private final DatabasePlatform databasePlatform;
@@ -143,8 +143,6 @@ public final class DefaultServer implements SpiEbeanServer {
*/
private final boolean rollbackOnChecked;
private final boolean defaultDeleteMissingChildren;
/**
* Handles the save, delete, updateSql CallableSql.
*/
@@ -228,8 +226,7 @@ public final class DefaultServer implements SpiEbeanServer {
*/
public DefaultServer(InternalConfiguration config, ServerCacheManager cache) {
ServerConfig serverConfig = config.getServerConfig();
this.serverConfig = config.getServerConfig();
this.objectGraphStats = new ConcurrentHashMap<ObjectGraphNode, CObjectGraphNodeStatistics>();
this.metaInfoManager = new DefaultMetaInfoManager(this);
this.serverCacheManager = cache;
@@ -251,9 +248,6 @@ public final class DefaultServer implements SpiEbeanServer {
this.collectQueryStatsByNode = serverConfig.isCollectQueryStatsByNode();
this.maxCallStack = GlobalProperties.getInt("ebean.maxCallStack", 5);
this.defaultDeleteMissingChildren = "true".equalsIgnoreCase(config.getServerConfig()
.getProperty("defaultDeleteMissingChildren", "true"));
this.rollbackOnChecked = GlobalProperties.getBoolean("ebean.transaction.rollbackOnChecked", true);
this.transactionManager = config.getTransactionManager();
this.transactionScopeManager = config.getTransactionScopeManager();
@@ -309,10 +303,6 @@ public final class DefaultServer implements SpiEbeanServer {
return collectQueryOrigins;
}
public boolean isDefaultDeleteMissingChildren() {
return defaultDeleteMissingChildren;
}
public int getLazyLoadBatchSize() {
return lazyLoadBatchSize;
}
@@ -321,6 +311,10 @@ public final class DefaultServer implements SpiEbeanServer {
return pstmtBatch;
}
public ServerConfig getServerConfig() {
return serverConfig;
}
public DatabasePlatform getDatabasePlatform() {
return databasePlatform;
}
@@ -1571,63 +1565,109 @@ public final class DefaultServer implements SpiEbeanServer {
* Save the bean with an explicit transaction.
*/
public void save(Object bean, Transaction t) {
persister.save(checkEntityBean(bean), t);
}
/**
* Force an update using the bean updating non-null properties.
* Update the bean using the default 'updatesDeleteMissingChildren' setting.
*/
public void update(Object bean) {
update(bean, null);
}
/**
* Force an update using the bean explicitly stating which properties to
* include in the update.
* Update the bean using the default 'updatesDeleteMissingChildren' setting.
*/
public void update(Object bean, Transaction t) {
update(bean, t, defaultDeleteMissingChildren);
persister.update(checkEntityBean(bean), t);
}
/**
* Force an update using the bean explicitly stating which properties to
* include in the update.
* Update the bean specifying the deleteMissingChildren option.
*/
public void update(Object bean, Transaction t, boolean deleteMissingChildren) {
persister.forceUpdate(checkEntityBean(bean), t, deleteMissingChildren);
persister.update(checkEntityBean(bean), t, deleteMissingChildren);
}
/**
* Force the bean to be saved with an explicit insert.
* <p>
* Typically you would use save() and let Ebean determine if the bean should
* be inserted or updated. This can be useful when you are transferring data
* between databases and want to explicitly insert a bean into a different
* database that it came from.
* </p>
* Update all beans in the collection.
*/
public void update(Collection<?> beans) {
update(beans, null);
}
/**
* Update all beans in the collection with an explicit transaction.
*/
public void update(Collection<?> beans, Transaction t) {
if (beans == null || beans.isEmpty()) {
// Nothing to update?
return;
}
TransWrapper wrap = initTransIfRequired(t);
try {
SpiTransaction trans = wrap.transaction;
for (Object bean : beans) {
update(checkEntityBean(bean), trans);
}
wrap.commitIfCreated();
} catch (RuntimeException e) {
wrap.rollbackIfCreated();
throw e;
}
}
/**
* Insert the bean.
*/
public void insert(Object bean) {
insert(bean, null);
}
/**
* Force the bean to be saved with an explicit insert.
* <p>
* Typically you would use save() and let Ebean determine if the bean should
* be inserted or updated. This can be useful when you are transferring data
* between databases and want to explicitly insert a bean into a different
* database that it came from.
* </p>
* Insert the bean with a transaction.
*/
public void insert(Object bean, Transaction t) {
persister.forceInsert(checkEntityBean(bean), t);
persister.insert(checkEntityBean(bean), t);
}
/**
* Insert all beans in the collection.
*/
public void insert(Collection<?> beans) {
insert(beans, null);
}
/**
* Insert all beans in the collection with a transaction.
*/
public void insert(Collection<?> beans, Transaction t) {
if (beans == null || beans.isEmpty()) {
// Nothing to insert?
return;
}
TransWrapper wrap = initTransIfRequired(t);
try {
SpiTransaction trans = wrap.transaction;
for (Object bean : beans) {
persister.insert(checkEntityBean(bean), trans);
}
wrap.commitIfCreated();
} catch (RuntimeException e) {
wrap.rollbackIfCreated();
throw e;
}
}
private EntityBean checkEntityBean(Object bean) {
if (bean == null) {
throw new NullPointerException(Message.msg("bean.isnull"));
throw new IllegalArgumentException(Message.msg("bean.isnull"));
}
if (bean instanceof EntityBean == false) {
throw new IllegalArgumentException("Was expecting an EntityBean but got a "+bean.getClass());
@@ -1735,6 +1775,14 @@ public final class DefaultServer implements SpiEbeanServer {
return save(c.iterator(), null);
}
/**
* Perform an update or insert on each bean in the collection. Returns the
* number of beans that where saved.
*/
public int save(Collection<?> c, Transaction t) {
return save(c.iterator(), t);
}
/**
* Save all beans in the iterator with an explicit transaction.
*/
@@ -15,14 +15,14 @@ public abstract class PersistRequest extends BeanRequest implements BatchPostExe
DETERMINE, INSERT, UPDATE, DELETE, ORMUPDATE, UPDATESQL, CALLABLESQL
};
boolean persistCascade;
protected boolean persistCascade;
/**
* One of INSERT, UPDATE, DELETE, UPDATESQL or CALLABLESQL.
*/
Type type;
protected Type type;
final PersistExecute persistExecute;
protected final PersistExecute persistExecute;
/**
* Used by CallableSqlRequest and UpdateSqlRequest.
@@ -32,66 +32,64 @@ import com.avaje.ebeaninternal.server.transaction.BeanPersistIdMap;
/**
* PersistRequest for insert update or delete of a bean.
*/
public class PersistRequestBean<T> extends PersistRequest implements BeanPersistRequest<T> {
public final class PersistRequestBean<T> extends PersistRequest implements BeanPersistRequest<T> {
protected final BeanManager<T> beanManager;
private final BeanManager<T> beanManager;
protected final BeanDescriptor<T> beanDescriptor;
private final BeanDescriptor<T> beanDescriptor;
protected final BeanPersistListener<T> beanPersistListener;
private final BeanPersistListener<T> beanPersistListener;
/**
* For per post insert update delete control.
*/
protected final BeanPersistController controller;
private final BeanPersistController controller;
/**
* The bean being persisted.
*/
protected final T bean;
private final T bean;
protected final EntityBean entityBean;
private final EntityBean entityBean;
/**
* The associated intercept.
*/
protected final EntityBeanIntercept intercept;
private final EntityBeanIntercept intercept;
/**
* The parent bean for unidirectional save.
*/
protected final Object parentBean;
private final Object parentBean;
protected final boolean dirty;
private final boolean dirty;
protected ConcurrencyMode concurrencyMode;
private ConcurrencyMode concurrencyMode;
/**
* The unique id used for logging summary.
*/
protected Object idValue;
private Object idValue;
/**
* Hash value used to handle cascade delete both ways in a relationship.
*/
protected Integer beanHash;
protected Integer beanIdentityHash;
private Integer beanHash;
protected boolean notifyCache;
private boolean notifyCache;
private boolean statelessUpdate;
private boolean deleteMissingChildren;
private final Set<String> dirtyPropertyNames;
/**
* Flag used to detect when only many properties where updated via a cascade. Used to ensure
* appropriate cache updates occur in that case.
* appropriate caches are updated in that case.
*/
private boolean updatedManysOnly;
/**
* Many properties that were cascade saved (and hence might need cache update later).
* Many properties that were cascade saved (and hence might need caches updated later).
*/
private List<BeanPropertyAssocMany<?>> updatedManys;
@@ -108,21 +106,23 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
if (PersistRequest.Type.DETERMINE != type) {
this.type = type;
} else {
// determine mode during cascade save (supporting stateless update)
this.type = beanDescriptor.isInsertMode(intercept) ? Type.INSERT : Type.UPDATE;
this.persistCascade = t.isPersistCascade();
}
if (this.type == Type.UPDATE && intercept.isNew() ) {
// 'stateless update' - set bean up for doing update
intercept.setNewBeanForUpdate();
}
// derive the set of property names now as we will pass them to a beanPersistListener later
this.dirtyPropertyNames = (beanPersistListener == null) ? null : intercept.getDirtyPropertyNames();
this.bean = bean;
this.parentBean = parentBean;
this.controller = beanDescriptor.getPersistController();
this.concurrencyMode = beanDescriptor.getConcurrencyMode(intercept);
// this is ok to not use isNewOrDirty() as used for updates only
this.dirty = intercept.isDirty();
}
@@ -268,13 +268,6 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
return beanDescriptor;
}
/**
* Return true if this is a stateless update.
*/
public boolean isStatelessUpdate() {
return statelessUpdate;
}
/**
* Return true if a stateless update should also delete any missing details
* beans.
@@ -284,15 +277,9 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
}
/**
* Set to true if this is a stateless update.
* <p>
* By Stateless it means that the bean was not previously fetched (and so
* does not have it's previous state) so we are doing an update on a bean
* that was probably created from JSON or XML.
* </p>
* Set if deleteMissingChildren occurs on cascade save to OneToMany or ManyToMany.
*/
public void setStatelessUpdate(boolean statelessUpdate, boolean deleteMissingChildren) {
this.statelessUpdate = statelessUpdate;
public void setDeleteMissingChildren(boolean deleteMissingChildren) {
this.deleteMissingChildren = deleteMissingChildren;
}
@@ -609,8 +596,8 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
}
/**
* A reference bean was saved. Check if any of its many properties where
* cascade saved and hence we need to update related many property caches.
* Check if any of its many properties where cascade saved and hence we need to update related
* many property caches.
*/
public void checkUpdatedManysOnly() {
if (!dirty && updatedManys != null) {
@@ -14,15 +14,20 @@ import com.avaje.ebean.bean.EntityBean;
*/
public interface Persister {
/**
* Update the bean.
*/
public void update(EntityBean entityBean, Transaction t);
/**
* Force an Update using the given bean.
* Update the bean specifying deleteMissingChildren.
*/
public void forceUpdate(EntityBean entityBean, Transaction t, boolean deleteMissingChildren);
public void update(EntityBean entityBean, Transaction t, boolean deleteMissingChildren);
/**
* Force an Insert using the given bean.
*/
public void forceInsert(EntityBean entityBean, Transaction t);
public void insert(EntityBean entityBean, Transaction t);
/**
* Insert or update the bean depending on its state.
@@ -207,8 +207,9 @@ public class BeanDescriptor<T> implements MetaBeanInfo {
* Derived list of properties that are used for version concurrency checking.
*/
private final BeanProperty versionProperty;
private final int versionPropertyIndex;
/**
* Properties local to this type (not from a super type).
*/
@@ -436,7 +437,7 @@ public class BeanDescriptor<T> implements MetaBeanInfo {
this.versionPropertyIndex = (versionProperty == null) ? -1 : ebi.findProperty(versionProperty.getName());
}
}
/**
* Create an entity bean that is used as a prototype/factory to create new instances.
*/
@@ -1818,6 +1819,12 @@ public class BeanDescriptor<T> implements MetaBeanInfo {
}
public boolean isInsertMode(EntityBeanIntercept ebi) {
if (ebi.isLoaded()) {
return false;
}
// determine based on Id property
if (idProperty.isEmbedded()) {
return !ebi.isLoaded();
}
@@ -107,6 +107,13 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
}
}
}
/**
* Return the property value as an entity bean.
*/
public EntityBean getValueAsEntityBean(EntityBean owner) {
return (EntityBean)getValue(owner);
}
public void setRelationshipProperty(BeanPropertyAssocMany<?> relationshipProperty){
this.relationshipProperty = relationshipProperty;
@@ -71,10 +71,12 @@ public final class DefaultPersister implements Persister {
private final BeanDescriptorManager beanDescriptorManager;
private final boolean updatesDeleteMissingChildren;
public DefaultPersister(SpiEbeanServer server, Binder binder, BeanDescriptorManager descMgr, PstmtBatch pstmtBatch) {
this.server = server;
this.updatesDeleteMissingChildren = server.getServerConfig().isUpdatesDeleteMissingChildren();
this.beanDescriptorManager = descMgr;
this.persistExecute = new DefaultPersistExecute(binder, pstmtBatch);
}
@@ -151,21 +153,34 @@ public final class DefaultPersister implements Persister {
}
/**
* Force an Update using the given bean.
* Update the bean.
*/
public void forceUpdate(EntityBean entityBean, Transaction t, boolean deleteMissingChildren) {
public void update(EntityBean entityBean, Transaction t) {
update(entityBean, t, updatesDeleteMissingChildren);
}
/**
* Update the bean specifying deleteMissingChildren.
*/
public void update(EntityBean entityBean, Transaction t, boolean deleteMissingChildren) {
PersistRequestBean<?> req = createRequest(entityBean, t, null, PersistRequest.Type.UPDATE);
if (req.isReference()) {
// skip update as only got the Id property set
return;
}
req.setStatelessUpdate(true, deleteMissingChildren);
req.setDeleteMissingChildren(deleteMissingChildren);
try {
req.initTransIfRequired();
update(req);
if (req.isReference()) {
// its a reference so see if there are manys to save...
if (req.isPersistCascade()) {
saveAssocMany(false, req);
}
req.checkUpdatedManysOnly();
} else {
update(req);
}
req.commitTransIfRequired();
// finished a 'normal' update
return;
} catch (RuntimeException ex) {
@@ -174,14 +189,22 @@ public final class DefaultPersister implements Persister {
}
}
/**
* Insert or update the bean.
*/
public void save(EntityBean bean, Transaction t) {
saveRecurse(bean, t, null);
if (bean._ebean_getIntercept().isLoaded()) {
// deleteMissingChildren is false when using 'save' on 'loaded' beans
update(bean, t, false);
} else {
insert(bean, t);
}
}
/**
* Explicitly specify to insert this bean.
* Insert this bean.
*/
public void forceInsert(EntityBean bean, Transaction t) {
public void insert(EntityBean bean, Transaction t) {
PersistRequestBean<?> req = createRequest(bean, t, null, PersistRequest.Type.INSERT);
try {
@@ -195,43 +218,17 @@ public final class DefaultPersister implements Persister {
}
}
private void saveRecurse(Object bean, Transaction t, Object parentBean) {
if (bean == null) {
throw new NullPointerException(Message.msg("bean.isnull"));
}
if (bean instanceof EntityBean == false) {
throw new IllegalArgumentException("This bean is of type ["+bean.getClass()+"] is not enhanced?");
}
PersistRequestBean<?> req = createRequest(bean, t, parentBean, PersistRequest.Type.DETERMINE);
try {
req.initTransIfRequired();
saveEnhanced(req);
req.commitTransIfRequired();
} catch (RuntimeException ex) {
req.rollbackTransIfRequired();
throw ex;
}
}
/**
* Insert or update the bean depending on PersistControl and the bean state.
*/
private void saveEnhanced(PersistRequestBean<?> request) {
EntityBeanIntercept intercept = request.getEntityBeanIntercept();
private void saveRecurse(EntityBean bean, Transaction t, Object parentBean) {
// determine insert or update taking into account stateless updates
PersistRequestBean<?> request = createRequest(bean, t, parentBean, PersistRequest.Type.DETERMINE);
if (request.isReference()) {
// its a reference...
if (request.isPersistCascade()) {
// save any associated List held beans
intercept.setLoaded();
saveAssocMany(false, request);
intercept.setReference(-1);
}
}
request.checkUpdatedManysOnly();
} else {
@@ -273,7 +270,7 @@ public final class DefaultPersister implements Persister {
}
/**
* Update the bean. Return NOT_SAVED if the bean values have not changed.
* Update the bean.
*/
private void update(PersistRequestBean<?> request) {
@@ -555,7 +552,7 @@ public final class DefaultPersister implements Persister {
// check for partial beans
if (request.isLoadedProperty(prop)) {
Object detailBean = prop.getValue(parentBean);
EntityBean detailBean = prop.getValueAsEntityBean(parentBean);
if (detailBean != null) {
if (prop.isSaveRecurseSkippable(detailBean)) {
// skip saving this bean
@@ -591,7 +588,6 @@ public final class DefaultPersister implements Persister {
private final EntityBean parentBean;
private final SpiTransaction transaction;
private final boolean cascade;
private final boolean statelessUpdate;
private final boolean deleteMissingChildren;
private SaveManyPropRequest(boolean insertedParent, BeanPropertyAssocMany<?> many, EntityBean parentBean, PersistRequestBean<?> request) {
@@ -600,7 +596,6 @@ public final class DefaultPersister implements Persister {
this.cascade = many.getCascadeInfo().isSave();
this.parentBean = parentBean;
this.transaction = request.getTransaction();
this.statelessUpdate = request.isStatelessUpdate();
this.deleteMissingChildren = request.isDeleteMissingChildren();
}
@@ -610,7 +605,6 @@ public final class DefaultPersister implements Persister {
this.parentBean = parentBean;
this.transaction = t;
this.cascade = true;
this.statelessUpdate = false;
this.deleteMissingChildren = false;
}
@@ -626,10 +620,6 @@ public final class DefaultPersister implements Persister {
return ModifyListenMode.REMOVALS.equals(many.getModifyListenMode());
}
private boolean isStatelessUpdate() {
return statelessUpdate;
}
private boolean isDeleteMissingChildren() {
return deleteMissingChildren;
}
@@ -672,12 +662,15 @@ public final class DefaultPersister implements Persister {
saveAssocManyIntersection(saveMany, saveMany.isDeleteMissingChildren());
}
} else {
if (saveMany.isCascade()) {
if (saveMany.isModifyListenMode()) {
// delete any removed beans via private owned. Needs to occur before
// a 'deleteMissingChildren' statement occurs
removeAssocManyPrivateOwned(saveMany);
}
if (saveMany.isCascade()) {
// potentially deletes 'missing children' for 'stateless update'
saveAssocManyDetails(saveMany, saveMany.isDeleteMissingChildren());
}
if (saveMany.isModifyListenMode()) {
removeAssocManyPrivateOwned(saveMany);
}
}
}
@@ -789,42 +782,32 @@ public final class DefaultPersister implements Persister {
}
}
if (skipSavingThisBean) {
// unmodified bean that does not recurse its save
// so we can skip the save for this bean.
// Reset skipSavingThisBean for the next detailBean
skipSavingThisBean = false;
if (skipSavingThisBean) {
// unmodified bean that does not recurse its save
// so we can skip the save for this bean.
// Reset skipSavingThisBean for the next detailBean
skipSavingThisBean = false;
} else if (!saveMany.isStatelessUpdate()) {
// normal save recurse
saveRecurse(detailBean, t, parentBean);
} else {
if (targetDescriptor.isStatelessUpdate(detail)) {
// update based on the value of Version/Id properties
// cascade update in stateless mode
forceUpdate(detail, t, deleteMissingChildren);
} else {
// cascade insert
forceInsert(detail, t);
}
}
if (detailIds != null) {
// remember the Id (other details not in the collection) will be removed
Object id = targetDescriptor.getId(detail);
if (!DmlUtil.isNullOrZero(id)) {
detailIds.add(id);
}
}
}
} else {
// normal save recurse
saveRecurse(detail, t, parentBean);
}
if (detailIds != null) {
// remember the Id (other details not in the collection) will be removed
Object id = targetDescriptor.getId(detail);
if (!DmlUtil.isNullOrZero(id)) {
detailIds.add(id);
}
}
}
}
if (detailIds != null) {
// deleteMissingChildren is true so deleting children that were not just processed
deleteManyDetails(t, prop.getBeanDescriptor(), parentBean, prop, detailIds);
}
t.depth(-1);
}
public int deleteManyToManyAssociations(EntityBean ownerBean, String propertyName, Transaction t) {
@@ -859,7 +842,7 @@ public final class DefaultPersister implements Persister {
} else if (prop instanceof BeanPropertyAssocOne<?>) {
BeanPropertyAssocOne<?> oneProp = (BeanPropertyAssocOne<?>) prop;
Object assocBean = oneProp.getValue(parentBean);
EntityBean assocBean = oneProp.getValueAsEntityBean(parentBean);
int depth = oneProp.isOneToOneExported() ? 1 : -1;
int revertDepth = -1 * depth;
@@ -1094,7 +1077,7 @@ public final class DefaultPersister implements Persister {
// check for partial objects
if (request.isLoadedProperty(prop)) {
Object detailBean = prop.getValue(request.getEntityBean());
EntityBean detailBean = prop.getValueAsEntityBean(request.getEntityBean());
if (detailBean != null) {
if (prop.isReference(detailBean)) {
// skip saving a reference