merge of develop-v4

This commit is contained in:
Rob Bygrave
2014-04-25 14:36:06 +12:00
243 changed files with 6065 additions and 6818 deletions
@@ -86,9 +86,9 @@ public class StatisticsNodeUsage implements Serializable {
}
if ((modified || queryTuningAddVersion) && desc != null) {
BeanProperty[] versionProps = desc.propertiesVersion();
if (versionProps.length > 0) {
pathProps.addToPath(path, versionProps[0].getName());
BeanProperty versionProp = desc.getVersionProperty();
if (versionProp != null) {
pathProps.addToPath(path, versionProp.getName());
}
}
}
@@ -1,50 +1,102 @@
package com.avaje.ebeaninternal.server.cache;
import java.util.Set;
import java.util.Arrays;
/**
* Data held in the bean cache for cached beans.
*/
public class CachedBeanData {
private final Object sharableBean;
private final Set<String> loadedProperties;
private final Object[] data;
private final int naturalKeyUpdate;
public CachedBeanData(Object sharableBean, Set<String> loadedProperties, Object[] data, int naturalKeyUpdate) {
this.sharableBean = sharableBean;
this.loadedProperties= loadedProperties;
this.data = data;
this.naturalKeyUpdate = naturalKeyUpdate;
}
public Object getSharableBean() {
return sharableBean;
}
private final long whenCreated;
private final Object sharableBean;
private final boolean[] loaded;
private final Object[] data;
private final boolean naturalKeyUpdate;
private final Object naturalKey;
private final Object oldNaturalKey;
public boolean isNaturalKeyUpdate() {
return naturalKeyUpdate > -1;
}
public Object getNaturalKey() {
return data[naturalKeyUpdate];
}
public CachedBeanData(Object sharableBean, boolean[] loaded, Object[] data, Object naturalKey, Object oldNaturalKey) {
this.whenCreated = System.currentTimeMillis();
this.sharableBean = sharableBean;
this.loaded = loaded;
this.data = data;
this.naturalKeyUpdate = naturalKey != null;
this.naturalKey = (naturalKey != null) ? naturalKey : oldNaturalKey;
this.oldNaturalKey = oldNaturalKey;
}
public boolean containsProperty(String propName) {
return loadedProperties == null || loadedProperties.contains(propName);
public String toString() {
return Arrays.toString(data);
}
/**
* Return a copy of the property data.
*/
public Object[] copyData() {
Object[] dest = new Object[data.length];
System.arraycopy(data, 0, dest, 0, data.length);
return dest;
}
/**
* Return a copy of the loaded status for the properties.
*/
public boolean[] copyLoaded() {
boolean[] dest = new boolean[data.length];
for (int i = 0; i < dest.length; i++) {
dest[i] = loaded[i];
}
public Object getData(int i){
return data[i];
}
public Set<String> getLoadedProperties() {
return loadedProperties;
}
public Object[] copyData() {
Object[] dest = new Object[data.length];
System.arraycopy(data, 0, dest, 0, data.length);
return dest;
}
return dest;
}
/**
* Return when the cached data was created.
*/
public long getWhenCreated() {
return whenCreated;
}
/**
* Return a sharable (immutable read only) bean.
*/
public Object getSharableBean() {
return sharableBean;
}
/**
* Return true if this data requires an update to the natural key cache.
*/
public boolean isNaturalKeyUpdate() {
return naturalKeyUpdate;
}
/**
* Return the new/current natural key value.
*/
public Object getNaturalKey() {
return naturalKey;
}
/**
* Return the old natural key (its entry should be removed).
*/
public Object getOldNaturalKey() {
return oldNaturalKey;
}
/**
* Return the data for the specific property.
*/
public Object getData(int i) {
return data[i];
}
/**
* Return true if the property is contained in this data.
*/
public boolean isLoaded(int i) {
return loaded[i];
}
}
@@ -1,8 +1,5 @@
package com.avaje.ebeaninternal.server.cache;
import java.util.HashSet;
import java.util.Set;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
@@ -10,94 +7,61 @@ import com.avaje.ebeaninternal.server.deploy.BeanProperty;
public class CachedBeanDataFromBean {
private final BeanDescriptor<?> desc;
private final Object bean;
private final EntityBeanIntercept ebi;
private final Set<String> loadedProps;
private final Set<String> extractProps;
public static CachedBeanData extract(BeanDescriptor<?> desc, Object bean){
if (bean instanceof EntityBean){
return new CachedBeanDataFromBean(desc, bean, ((EntityBean)bean)._ebean_getIntercept()).extract();
} else {
return new CachedBeanDataFromBean(desc, bean, null).extract();
}
}
public static CachedBeanData extract(BeanDescriptor<?> desc, Object bean, EntityBeanIntercept ebi){
return new CachedBeanDataFromBean(desc, bean, ebi).extract();
}
private CachedBeanDataFromBean(BeanDescriptor<?> desc, Object bean, EntityBeanIntercept ebi) {
this.desc = desc;
this.bean = bean;
this.ebi = ebi;
if (ebi != null){
this.loadedProps = ebi.getLoadedProps();
this.extractProps = (loadedProps == null) ? null : new HashSet<String>();
} else {
this.extractProps = new HashSet<String>();
this.loadedProps = null;
}
}
private CachedBeanData extract(){
public static CachedBeanData extract(BeanDescriptor<?> desc, EntityBean bean) {
BeanProperty[] props = desc.propertiesNonMany();
EntityBeanIntercept ebi = bean._ebean_getIntercept();
Object[] data = new Object[desc.getPropertyCount()];
boolean[] loaded = new boolean[desc.getPropertyCount()];
BeanProperty[] props = desc.propertiesNonMany();
Object[] data = new Object[props.length];
int naturalKeyUpdate = -1;
for (int i = 0; i < props.length; i++) {
BeanProperty prop = props[i];
if (includeNonManyProperty(prop.getName())){
data[i] = prop.getCacheDataValue(bean);
if (prop.isNaturalKey()) {
naturalKeyUpdate = i;
}
if (ebi != null){
if (extractProps != null){
extractProps.add(prop.getName());
}
} else if (data[i] != null){
if (extractProps != null){
extractProps.add(prop.getName());
}
}
}
Object naturalKey = null;
for (int i = 0; i < props.length; i++) {
BeanProperty prop = props[i];
if (ebi.isLoadedProperty(prop.getPropertyIndex())) {
int propertyIndex = prop.getPropertyIndex();
data[propertyIndex] = prop.getCacheDataValue(bean);
loaded[propertyIndex] = true;
if (prop.isNaturalKey()) {
naturalKey = prop.getValue(bean);
}
Object sharableBean = null;
if (desc.isCacheSharableBeans() && ebi != null && loadedProps == null){
if (ebi.isReadOnly()){
sharableBean = bean;
} else {
// create a readOnly sharable instance by copying the data
sharableBean = desc.createBean();
BeanProperty[] propertiesId = desc.propertiesId();
for (int i = 0; i < propertiesId.length; i++) {
Object v = propertiesId[i].getValue(bean);
propertiesId[i].setValue(sharableBean, v);
}
BeanProperty[] propertiesNonTransient = desc.propertiesNonTransient();
for (int i = 0; i < propertiesNonTransient.length; i++) {
Object v = propertiesNonTransient[i].getValue(bean);
propertiesNonTransient[i].setValue(sharableBean, v);
}
EntityBeanIntercept ebi = ((EntityBean)sharableBean)._ebean_intercept();
ebi.setReadOnly(true);
ebi.setLoaded();
}
}
return new CachedBeanData(sharableBean, extractProps, data, naturalKeyUpdate);
}
}
EntityBean sharableBean = createSharableBean(desc, bean, ebi);
return new CachedBeanData(sharableBean, loaded, data, naturalKey, null);
}
private static EntityBean createSharableBean(BeanDescriptor<?> desc, EntityBean bean, EntityBeanIntercept beanEbi) {
private boolean includeNonManyProperty(String name) {
return loadedProps == null || loadedProps.contains(name);
if (!desc.isCacheSharableBeans() || !beanEbi.isFullyLoadedBean()) {
return null;
}
if (beanEbi.isReadOnly()) {
return bean;
}
// create a readOnly sharable instance by copying the data
EntityBean sharableBean = desc.createBean();
BeanProperty idProp = desc.getIdProperty();
if (idProp != null) {
Object v = idProp.getValue(bean);
idProp.setValue(sharableBean, v);
}
BeanProperty[] propertiesNonTransient = desc.propertiesNonTransient();
for (int i = 0; i < propertiesNonTransient.length; i++) {
Object v = propertiesNonTransient[i].getValue(bean);
propertiesNonTransient[i].setValue(sharableBean, v);
}
EntityBeanIntercept intercept = sharableBean._ebean_intercept();
intercept.setReadOnly(true);
intercept.setLoaded();
return sharableBean;
}
}
@@ -1,8 +1,5 @@
package com.avaje.ebeaninternal.server.cache;
import java.util.HashSet;
import java.util.Set;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
@@ -11,107 +8,34 @@ import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
public class CachedBeanDataToBean {
private final BeanDescriptor<?> desc;
private final Object bean;
private final EntityBeanIntercept ebi;
private final CachedBeanData cacheBeandata;
private final Set<String> cacheLoadedProperties;
private final Set<String> loadedProps;
private final Set<String> excludeProps;
private final Object oldValuesBean;
private final boolean readOnly;
public static void load(BeanDescriptor<?> desc, Object bean, CachedBeanData cacheBeandata) {
if (bean instanceof EntityBean){
load(desc, bean, ((EntityBean)bean)._ebean_getIntercept(), cacheBeandata);
} else {
load(desc, bean, null, cacheBeandata);
}
}
public static void load(BeanDescriptor<?> desc, Object bean, EntityBeanIntercept ebi, CachedBeanData cacheBeandata) {
new CachedBeanDataToBean(desc, bean, ebi, cacheBeandata).load();
}
public static boolean load(BeanDescriptor<?> desc, EntityBean bean, CachedBeanData cacheBeanData) {
private CachedBeanDataToBean(BeanDescriptor<?> desc, Object bean, EntityBeanIntercept ebi, CachedBeanData cacheBeandata) {
this.desc = desc;
this.bean = bean;
this.ebi = ebi;
this.cacheBeandata = cacheBeandata;
this.cacheLoadedProperties = cacheBeandata.getLoadedProperties();
this.loadedProps = (cacheLoadedProperties == null) ? null : new HashSet<String>();
if (ebi != null){
this.excludeProps = ebi.getLoadedProps();
this.oldValuesBean = ebi.getOldValues();
this.readOnly = ebi.isReadOnly();
EntityBeanIntercept ebi = bean._ebean_getIntercept();
BeanProperty[] props = desc.propertiesNonMany();
for (int i = 0; i < props.length; i++) {
BeanProperty prop = props[i];
int propertyIndex = prop.getPropertyIndex();
if (cacheBeanData.isLoaded(propertyIndex)) {
if (ebi.isLoadedProperty(propertyIndex)) {
// already loaded (lazy load on partially loaded bean)
} else {
this.excludeProps = null;
this.oldValuesBean = null;
this.readOnly = false;
Object data = cacheBeanData.getData(propertyIndex);
prop.setCacheDataValue(bean, data);
}
}
}
private boolean load(){
BeanProperty[] propertiesNonTransient = desc.propertiesNonMany();
for (int i = 0; i < propertiesNonTransient.length; i++) {
BeanProperty prop = propertiesNonTransient[i];
if (includeNonManyProperty(prop.getName())){
Object data = cacheBeandata.getData(i);
prop.setCacheDataValue(bean, data, oldValuesBean, readOnly);
}
}
BeanPropertyAssocMany<?>[] manys = desc.propertiesMany();
for (int i = 0; i < manys.length; i++) {
BeanPropertyAssocMany<?> prop = manys[i];
if (includeManyProperty(prop.getName())){
// set a lazy loading proxy
prop.createReference(bean);
}
}
if (ebi != null){
if (loadedProps == null){
ebi.setLoadedProps(null);
} else {
HashSet<String> mergeProps = new HashSet<String>();
if (excludeProps != null) {
mergeProps.addAll(excludeProps);
}
mergeProps.addAll(loadedProps);
ebi.setLoadedProps(mergeProps);
}
ebi.setLoadedLazy();
}
return true;
BeanPropertyAssocMany<?>[] manys = desc.propertiesMany();
for (int i = 0; i < manys.length; i++) {
manys[i].createReferenceIfNull(bean);
}
private boolean includeManyProperty(String name) {
if (excludeProps != null && excludeProps.contains(name)){
// ignore this property (partial bean lazy loading)
return false;
}
if (loadedProps != null){
loadedProps.add(name);
}
return true;
}
private boolean includeNonManyProperty(String name) {
if (excludeProps != null && excludeProps.contains(name)){
// ignore this property (partial bean lazy loading)
return false;
}
if (cacheLoadedProperties != null && !cacheLoadedProperties.contains(name)){
return false;
}
if (loadedProps != null){
loadedProps.add(name);
}
return true;
}
ebi.setLoadedLazy();
return true;
}
}
@@ -1,49 +1,44 @@
package com.avaje.ebeaninternal.server.cache;
import java.util.HashSet;
import java.util.Set;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* Create a new CachedBeanData based on the existing CachedBeanData and the updated bean.
*/
public class CachedBeanDataUpdate {
public static CachedBeanData update(BeanDescriptor<?> desc, CachedBeanData data, PersistRequestBean<?> updateRequest){
/**
* Create a new CachedBeanData based on the existing CachedBeanData and the updated bean.
*/
public static CachedBeanData update(BeanDescriptor<?> desc, CachedBeanData existingData, EntityBean updateBean) {
Set<String> loadedProperties = data.getLoadedProperties();
Object[] copyOfData = data.copyData();
Object updateBean = updateRequest.getBean();
Set<String> updatedProperties = updateRequest.getUpdatedProperties();
int naturalKeyUpdate = -1;
boolean mergeProperties = false;
BeanProperty[] props = desc.propertiesNonMany();
for (int i = 0; i < props.length; i++) {
if (updatedProperties.contains(props[i].getName())){
if (props[i].isNaturalKey()){
naturalKeyUpdate = i;
}
copyOfData[i] = props[i].getCacheDataValue(updateBean);
if (loadedProperties != null && !mergeProperties && !loadedProperties.contains(props[i].getName())){
mergeProperties = true;
}
}
// take a copy of the raw data and loaded status
boolean[] copyLoaded = existingData.copyLoaded();
Object[] copyData = existingData.copyData();
EntityBeanIntercept ebi = updateBean._ebean_getIntercept();
Object newNaturalKey = null;
Object oldNaturalKey = existingData.getNaturalKey();
BeanProperty[] props = desc.propertiesNonMany();
for (int i = 0; i < props.length; i++) {
// check if the properties was in the update
int propertyIndex = props[i].getPropertyIndex();
if (ebi.isLoadedProperty(propertyIndex)) {
if (props[i].isNaturalKey()) {
newNaturalKey = updateBean._ebean_getField(propertyIndex);
}
if (mergeProperties){
HashSet<String> mergeProps = new HashSet<String>();
mergeProps.addAll(loadedProperties);
mergeProps.addAll(updatedProperties);
loadedProperties = mergeProps;
}
return new CachedBeanData(null, loadedProperties, copyOfData, naturalKeyUpdate);
// set the cache safe value for the property and mark it as loaded
copyData[propertyIndex] = props[i].getCacheDataValue(updateBean);
copyLoaded[propertyIndex] = true;
}
}
return new CachedBeanData(null, copyLoaded, copyData, newNaturalKey, oldNaturalKey);
}
}
@@ -2,16 +2,26 @@ package com.avaje.ebeaninternal.server.cache;
import java.util.List;
/**
* The cached data for O2M and M2M relationships.
* <p>
* This is effectively just the Id values for each of the beans in the collection.
* </p>
*/
public class CachedManyIds {
private final List<Object> idList;
public CachedManyIds(List<Object> idList) {
this.idList = idList;
}
private final List<Object> idList;
public List<Object> getIdList() {
return idList;
}
public CachedManyIds(List<Object> idList) {
this.idList = idList;
}
public String toString() {
return idList.toString();
}
public List<Object> getIdList() {
return idList;
}
}
@@ -11,7 +11,6 @@ import javax.persistence.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.config.CompoundType;
import com.avaje.ebean.config.ScalarTypeConverter;
import com.avaje.ebean.config.ServerConfig;
@@ -52,6 +51,7 @@ public class BootupClasses implements ClassPathSearchMatcher {
private ArrayList<Class<?>> beanQueryAdapterList = new ArrayList<Class<?>>();
private ArrayList<Class<?>> serverConfigStartupList = new ArrayList<Class<?>>();
private ArrayList<ServerConfigStartup> serverConfigStartupInstances = new ArrayList<ServerConfigStartup>();
@@ -311,7 +311,7 @@ public class BootupClasses implements ClassPathSearchMatcher {
} else if (isEntity(cls)) {
entityList.add(cls);
} else if (isInterestingInterface(cls)) {
return true;
@@ -4,87 +4,126 @@ package com.avaje.ebeaninternal.server.core;
* Options for controlling cache behaviour for a given type.
*/
public class CacheOptions {
private boolean useCache;
private boolean readOnly;
private String naturalKey;
private String warmingQuery;
/**
* Construct with options.
*/
public CacheOptions() {
}
/**
* Return true if this should use a cache for lazy loading.
*/
public boolean isUseCache() {
return useCache;
}
/**
* Set whether to use the bean cache for the associated type.
*/
public void setUseCache(boolean useCache) {
this.useCache = useCache;
private boolean useCache;
private boolean readOnly;
private String naturalKey;
private String warmingQuery;
private int maxIdleSecs;
private long maxSecsToLive;
/**
* Construct with options.
*/
public CacheOptions() {
}
/**
* Return true if this should use a cache for lazy loading.
*/
public boolean isUseCache() {
return useCache;
}
/**
* Set whether to use the bean cache for the associated type.
*/
public void setUseCache(boolean useCache) {
this.useCache = useCache;
}
/**
* Return the readOnly default setting.
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* Set read Only default setting.
*/
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
/**
* Return the query used to warm the cache.
*/
public String getWarmingQuery() {
return warmingQuery;
}
/**
* Set the cache warming query.
*/
public void setWarmingQuery(String warmingQuery) {
this.warmingQuery = warmingQuery;
}
/**
* Return true if a natural key is set.
*/
public boolean isUseNaturalKeyCache() {
return naturalKey != null;
}
/**
* Return the natural key property.
*/
public String getNaturalKey() {
return naturalKey;
}
/**
* Set the natural key property.
*/
public void setNaturalKey(String naturalKey) {
if (naturalKey == null || naturalKey.length() == 0) {
naturalKey = null;
} else {
this.naturalKey = naturalKey.trim();
}
}
/**
* Return the max age of entries in seconds.
*/
public long getMaxSecsToLive() {
return maxSecsToLive;
}
/**
* Return the readOnly default setting.
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* Set the max age of entries in seconds.
*/
public void setMaxSecsToLive(long maxSecsToLive) {
this.maxSecsToLive = maxSecsToLive;
}
/**
* Set read Only default setting.
*/
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
/**
* Set the max idle seconds.
*/
public void setMaxIdleSecs(int maxIdleSecs) {
this.maxIdleSecs = maxIdleSecs;
}
/**
* Return the query used to warm the cache.
*/
public String getWarmingQuery() {
return warmingQuery;
}
/**
* Return the max idle seconds.
*/
public int getMaxIdleSecs() {
return maxIdleSecs;
}
/**
* Set the cache warming query.
*/
public void setWarmingQuery(String warmingQuery) {
this.warmingQuery = warmingQuery;
}
/**
* Return true if the entry exceeds the maxIdleSecs or maxSecsToLive.
*/
public boolean isTooOldInMillis(long ageMillis) {
long secs = ageMillis / 1000;
return (maxIdleSecs > 0 && secs > maxIdleSecs) || (maxSecsToLive > 0 && secs > maxSecsToLive);
}
/**
* Return true if a natural key is set.
*/
public boolean isUseNaturalKeyCache() {
return naturalKey != null;
}
/**
* Return the natural key property.
*/
public String getNaturalKey() {
return naturalKey;
}
/**
* Set the natural key property.
*/
public void setNaturalKey(String naturalKey) {
if (naturalKey == null || naturalKey.length() == 0){
naturalKey = null;
} else {
this.naturalKey = naturalKey.trim();
}
}
}
@@ -73,7 +73,7 @@ public class DefaultBeanLoader {
return batchSize;
}
public void refreshMany(Object parentBean, String propertyName) {
public void refreshMany(EntityBean parentBean, String propertyName) {
refreshMany(parentBean, propertyName, null);
}
@@ -92,7 +92,7 @@ public class DefaultBeanLoader {
for (int i = 0; i < batch.size(); i++) {
BeanCollection<?> bc = batch.get(i);
Object ownerBean = bc.getOwnerBean();
EntityBean ownerBean = bc.getOwnerBean();
Object id = many.getParentId(ownerBean);
idList.add(id);
}
@@ -136,14 +136,14 @@ public class DefaultBeanLoader {
}
} else if (loadRequest.isLoadCache()) {
Object parentId = desc.getId(bc.getOwnerBean());
desc.cachePutMany(many, bc, parentId);
desc.cacheManyPropPut(many, bc, parentId);
}
}
}
public void loadMany(BeanCollection<?> bc, boolean onlyIds) {
Object parentBean = bc.getOwnerBean();
EntityBean parentBean = bc.getOwnerBean();
String propertyName = bc.getPropertyName();
//ObjectGraphNode node = ctx == null ? null : ctx.getObjectGraphNode();
@@ -151,11 +151,11 @@ public class DefaultBeanLoader {
loadManyInternal(parentBean, propertyName, null, false, null, onlyIds);
}
public void refreshMany(Object parentBean, String propertyName, Transaction t) {
public void refreshMany(EntityBean parentBean, String propertyName, Transaction t) {
loadManyInternal(parentBean, propertyName, t, true, null, false);
}
private void loadManyInternal(Object parentBean, String propertyName, Transaction t, boolean refresh, ObjectGraphNode node, boolean onlyIds) {
private void loadManyInternal(EntityBean parentBean, String propertyName, Transaction t, boolean refresh, ObjectGraphNode node, boolean onlyIds) {
EntityBeanIntercept ebi = ((EntityBean) parentBean)._ebean_getIntercept();
PersistenceContext pc = ebi.getPersistenceContext();
@@ -179,13 +179,13 @@ public class DefaultBeanLoader {
pc.put(parentId, parentBean);
}
boolean useManyIdCache = beanCollection != null && parentDesc.cacheIsUseManyId();
boolean useManyIdCache = beanCollection != null && parentDesc.isManyPropCaching();
if (useManyIdCache) {
Boolean readOnly = null;
if (ebi != null && ebi.isReadOnly()) {
readOnly = Boolean.TRUE;
}
if (parentDesc.cacheLoadMany(many, beanCollection, parentId, readOnly)) {
if (parentDesc.cacheManyPropLoad(many, beanCollection, parentId, readOnly)) {
return;
}
}
@@ -238,7 +238,7 @@ public class DefaultBeanLoader {
logger.debug("BeanCollection after load was empty. Owner:" + beanCollection.getOwnerBean());
}
} else if (useManyIdCache) {
parentDesc.cachePutMany(many, beanCollection, parentId);
parentDesc.cacheManyPropPut(many, beanCollection, parentId);
}
}
}
@@ -267,7 +267,7 @@ public class DefaultBeanLoader {
for (int i = 0; i < batch.size(); i++) {
EntityBeanIntercept ebi = batch.get(i);
Object bean = ebi.getOwner();
EntityBean bean = ebi.getOwner();
Object id = desc.getId(bean);
idList.add(id);
}
@@ -290,17 +290,6 @@ public class DefaultBeanLoader {
PersistenceContext persistenceContext = ctx.getPersistenceContext();
// query the database
for (int i = 0; i < ebis.length; i++) {
Object parentBean = ebis[i].getParentBean();
if (parentBean != null) {
// Special case for OneToOne
BeanDescriptor<?> parentDesc = server.getBeanDescriptor(parentBean.getClass());
Object parentId = parentDesc.getId(parentBean);
persistenceContext.put(parentId, parentBean);
}
}
SpiQuery<?> query = (SpiQuery<?>) server.createQuery(beanType);
query.setMode(Mode.LAZYLOAD_BEAN);
@@ -323,20 +312,18 @@ public class DefaultBeanLoader {
if (loadRequest.isLoadCache()) {
for (int i = 0; i < list.size(); i++) {
desc.cachePutBeanData(list.get(i));
desc.cacheBeanPutData((EntityBean)list.get(i));
}
}
for (int i = 0; i < ebis.length; i++) {
if (ebis[i].isReference()) {
// The underlying row in DB was deleted. Mark this bean as 'failed'
// but allow processing to continue until it is accessed by client code
ebis[i].setLazyLoadFailure();
}
// Check if the underlying row in DB was deleted. Mark this bean as 'failed' if
// necessary but allow processing to continue until it is accessed by client code
ebis[i].checkLazyLoadFailure();
}
}
public void refresh(Object bean) {
public void refresh(EntityBean bean) {
refreshBeanInternal(bean, SpiQuery.Mode.REFRESH_BEAN);
}
@@ -344,7 +331,7 @@ public class DefaultBeanLoader {
refreshBeanInternal(ebi.getOwner(), SpiQuery.Mode.LAZYLOAD_BEAN);
}
private void refreshBeanInternal(Object bean, SpiQuery.Mode mode) {
private void refreshBeanInternal(EntityBean bean, SpiQuery.Mode mode) {
EntityBeanIntercept ebi = ((EntityBean) bean)._ebean_getIntercept();;
PersistenceContext pc = ebi.getPersistenceContext();
@@ -364,7 +351,7 @@ public class DefaultBeanLoader {
if (ebi != null) {
if (SpiQuery.Mode.LAZYLOAD_BEAN.equals(mode) && desc.isBeanCaching()) {
// lazy loading and the bean cache is active
if (desc.loadFromCache(bean, ebi, id)) {
if (desc.cacheBeanLoad((EntityBean)bean, ebi, id)) {
return;
}
}
@@ -375,14 +362,6 @@ public class DefaultBeanLoader {
SpiQuery<?> query = (SpiQuery<?>) server.createQuery(desc.getBeanType());
if (ebi != null) {
Object parentBean = ebi.getParentBean();
if (parentBean != null) {
// Special case for OneToOne
BeanDescriptor<?> parentDesc = server.getBeanDescriptor(parentBean.getClass());
Object parentId = parentDesc.getId(parentBean);
pc.putIfAbsent(parentId, parentBean);
}
query.setLazyLoadProperty(ebi.getLazyLoadProperty());
}
@@ -1,10 +1,11 @@
package com.avaje.ebeaninternal.server.core;
import java.beans.PropertyChangeListener;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import com.avaje.ebean.BeanState;
import com.avaje.ebean.ValuePair;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
@@ -13,9 +14,9 @@ import com.avaje.ebean.bean.EntityBeanIntercept;
*/
public class DefaultBeanState implements BeanState {
final EntityBean entityBean;
private final EntityBean entityBean;
final EntityBeanIntercept intercept;
private final EntityBeanIntercept intercept;
public DefaultBeanState(EntityBean entityBean){
this.entityBean = entityBean;
@@ -39,14 +40,16 @@ public class DefaultBeanState implements BeanState {
}
public Set<String> getLoadedProps() {
Set<String> props = intercept.getLoadedProps();
return props == null ? null : Collections.unmodifiableSet(props);
return intercept.getLoadedPropertyNames();
}
public Set<String> getChangedProps() {
Set<String> props = intercept.getChangedProps();
return props == null ? null : Collections.unmodifiableSet(props);
}
return intercept.getDirtyPropertyNames();
}
public Map<String,ValuePair> getDirtyValues() {
return intercept.getDirtyValues();
}
public boolean isReadOnly() {
return intercept.isReadOnly();
@@ -64,14 +67,8 @@ public class DefaultBeanState implements BeanState {
entityBean.removePropertyChangeListener(listener);
}
public void setLoaded(Set<String> loadedProperties) {
intercept.setLoadedProps(loadedProperties);
intercept.setLoaded();
public void setLoaded() {
intercept.setLoaded();
}
public void setReference() {
intercept.setReference();
}
}
@@ -121,6 +121,10 @@ public final class DefaultServer implements SpiEbeanServer {
private static final Logger logger = LoggerFactory.getLogger(DefaultServer.class);
private static final int IGNORE_LEADING_ELEMENTS = 5;
private static final String AVAJE_EBEAN = Ebean.class.getName().substring(0, 15);
private final String serverName;
private final DatabasePlatform databasePlatform;
@@ -138,8 +142,8 @@ public final class DefaultServer implements SpiEbeanServer {
* false;
*/
private final boolean rollbackOnChecked;
private final boolean defaultDeleteMissingChildren;
private final boolean defaultUpdateNullProperties;
/**
* Handles the save, delete, updateSql CallableSql.
@@ -247,8 +251,6 @@ public final class DefaultServer implements SpiEbeanServer {
this.collectQueryStatsByNode = serverConfig.isCollectQueryStatsByNode();
this.maxCallStack = GlobalProperties.getInt("ebean.maxCallStack", 5);
this.defaultUpdateNullProperties = "true"
.equalsIgnoreCase(config.getServerConfig().getProperty("defaultUpdateNullProperties", "false"));
this.defaultDeleteMissingChildren = "true".equalsIgnoreCase(config.getServerConfig()
.getProperty("defaultDeleteMissingChildren", "true"));
@@ -311,10 +313,6 @@ public final class DefaultServer implements SpiEbeanServer {
return defaultDeleteMissingChildren;
}
public boolean isDefaultUpdateNullProperties() {
return defaultUpdateNullProperties;
}
public int getLazyLoadBatchSize() {
return lazyLoadBatchSize;
}
@@ -522,12 +520,12 @@ public final class DefaultServer implements SpiEbeanServer {
public void refreshMany(Object parentBean, String propertyName, Transaction t) {
beanLoader.refreshMany(parentBean, propertyName, t);
beanLoader.refreshMany(checkEntityBean(parentBean), propertyName, t);
}
public void refreshMany(Object parentBean, String propertyName) {
beanLoader.refreshMany(parentBean, propertyName);
beanLoader.refreshMany(checkEntityBean(parentBean), propertyName);
}
public void loadMany(LoadManyRequest loadRequest) {
@@ -542,7 +540,7 @@ public final class DefaultServer implements SpiEbeanServer {
public void refresh(Object bean) {
beanLoader.refresh(bean);
beanLoader.refresh(checkEntityBean(bean));
}
public void loadBean(LoadBeanRequest loadRequest) {
@@ -652,29 +650,21 @@ public final class DefaultServer implements SpiEbeanServer {
// we actually need to do a query because
// we don't know the type without the
// discriminator value
BeanProperty[] idProps = desc.propertiesId();
String idNames;
switch (idProps.length) {
case 0:
throw new PersistenceException("No ID properties for this type? " + desc);
case 1:
idNames = idProps[0].getName();
break;
default:
idNames = Arrays.toString(idProps);
idNames = idNames.substring(1, idNames.length() - 1);
BeanProperty idProp = desc.getIdProperty();
if (idProp == null) {
throw new PersistenceException("No ID properties for this type? " + desc);
}
// just select the id properties and
// the discriminator column (auto added)
Query<T> query = createQuery(type);
query.select(idNames).setId(id);
query.select(idProp.getName()).setId(id);
ref = query.findUnique();
} else {
// use the default reference options
ref = desc.createReference(null, id, null);
ref = desc.createReference(null, id);
}
if (ctx != null && (ref instanceof EntityBean)) {
@@ -1133,7 +1123,7 @@ public final class DefaultServer implements SpiEbeanServer {
if (Mode.LAZYLOAD_MANY.equals(query.getMode())) {
allowOneManyFetch = false;
} else if (query.hasMaxRowsOrFirstRow() && !query.isRawSql() && !query.isSqlSelect() && query.getBackgroundFetchAfter() == 0) {
} else if (query.hasMaxRowsOrFirstRow() && !query.isRawSql() && !query.isSqlSelect()) {
// convert ALL fetch joins to Many's to be query joins
// so that limit offset type SQL clauses work
allowOneManyFetch = false;
@@ -1190,23 +1180,7 @@ public final class DefaultServer implements SpiEbeanServer {
}
// Hit the L2 bean cache
Object cachedBean = beanDescriptor.cacheGetBean(query.getId(), query.isReadOnly());
if (cachedBean != null) {
if (context == null) {
context = new DefaultPersistenceContext();
}
context.put(query.getId(), cachedBean);
DLoadContext loadContext = new DLoadContext(this, beanDescriptor, query.isReadOnly(), query);
loadContext.setPersistenceContext(context);
EntityBeanIntercept ebi = ((EntityBean) cachedBean)._ebean_getIntercept();
ebi.setPersistenceContext(context);
loadContext.register(null, ebi);
}
return (T) cachedBean;
return beanDescriptor.cacheBeanGet(query, context);
}
@SuppressWarnings("unchecked")
@@ -1255,17 +1229,9 @@ public final class DefaultServer implements SpiEbeanServer {
BeanDescriptor<T> desc = beanDescriptorManager.getBeanDescriptor(q.getBeanType());
if (desc.calculateUseNaturalKeyCache(q.isUseBeanCache())) {
// check if it is a find by unique id
NaturalKeyBindParam keyBindParam = q.getNaturalKeyBindParam();
if (keyBindParam != null && desc.cacheIsNaturalKey(keyBindParam.getName())) {
Object id2 = desc.cacheGetNaturalKeyId(keyBindParam.getValue());
if (id2 != null) {
SpiQuery<T> copy = q.copy();
copy.convertWhereNaturalKeyToId(id2);
return findId(copy, t);
}
}
T bean = desc.cacheNaturalKeyLookup(q, (SpiTransaction)t);
if (bean != null) {
return bean;
}
// a query that is expected to return either 0 or 1 rows
@@ -1273,9 +1239,10 @@ public final class DefaultServer implements SpiEbeanServer {
if (list.size() == 0) {
return null;
} else if (list.size() > 1) {
String m = "Unique expecting 0 or 1 rows but got [" + list.size() + "]";
throw new PersistenceException(m);
throw new PersistenceException("Unique expecting 0 or 1 rows but got [" + list.size() + "]");
} else {
return list.get(0);
}
@@ -1604,51 +1571,32 @@ public final class DefaultServer implements SpiEbeanServer {
* Save the bean with an explicit transaction.
*/
public void save(Object bean, Transaction t) {
if (bean == null) {
throw new NullPointerException(Message.msg("bean.isnull"));
}
persister.save(bean, t);
persister.save(checkEntityBean(bean), t);
}
/**
* Force an update using the bean updating non-null properties.
*/
public void update(Object bean) {
update(bean, null, null);
update(bean, null);
}
/**
* Force an update using the bean explicitly stating which properties to
* include in the update.
*/
public void update(Object bean, Set<String> updateProps) {
update(bean, updateProps, null);
}
/**
* Force an update using the bean updating non-null properties.
*/
public void update(Object bean, Transaction t) {
update(bean, null, t);
update(bean, t, defaultDeleteMissingChildren);
}
/**
* Force an update using the bean explicitly stating which properties to
* include in the update.
*/
public void update(Object bean, Set<String> updateProps, Transaction t) {
update(bean, updateProps, t, defaultDeleteMissingChildren, defaultUpdateNullProperties);
}
/**
* Force an update using the bean explicitly stating which properties to
* include in the update.
*/
public void update(Object bean, Set<String> updateProps, Transaction t, boolean deleteMissingChildren, boolean updateNullProperties) {
if (bean == null) {
throw new NullPointerException(Message.msg("bean.isnull"));
}
persister.forceUpdate(bean, updateProps, t, deleteMissingChildren, updateNullProperties);
public void update(Object bean, Transaction t, boolean deleteMissingChildren) {
persister.forceUpdate(checkEntityBean(bean), t, deleteMissingChildren);
}
/**
@@ -1674,12 +1622,19 @@ public final class DefaultServer implements SpiEbeanServer {
* </p>
*/
public void insert(Object bean, Transaction t) {
persister.forceInsert(checkEntityBean(bean), t);
}
private EntityBean checkEntityBean(Object bean) {
if (bean == null) {
throw new NullPointerException(Message.msg("bean.isnull"));
}
persister.forceInsert(bean, t);
if (bean instanceof EntityBean == false) {
throw new IllegalArgumentException("Was expecting an EntityBean but got a "+bean.getClass());
}
return (EntityBean)bean;
}
/**
* Delete the associations (from the intersection table) of a ManyToMany given
* the owner bean and the propertyName of the ManyToMany collection.
@@ -1700,10 +1655,11 @@ public final class DefaultServer implements SpiEbeanServer {
*/
public int deleteManyToManyAssociations(Object ownerBean, String propertyName, Transaction t) {
EntityBean owner = checkEntityBean(ownerBean);
TransWrapper wrap = initTransIfRequired(t);
try {
SpiTransaction trans = wrap.transaction;
int rc = persister.deleteManyToManyAssociations(ownerBean, propertyName, trans);
int rc = persister.deleteManyToManyAssociations(owner, propertyName, trans);
wrap.commitIfCreated();
return rc;
@@ -1727,11 +1683,12 @@ public final class DefaultServer implements SpiEbeanServer {
*/
public void saveManyToManyAssociations(Object ownerBean, String propertyName, Transaction t) {
EntityBean owner = checkEntityBean(ownerBean);
TransWrapper wrap = initTransIfRequired(t);
try {
SpiTransaction trans = wrap.transaction;
persister.saveManyToManyAssociations(ownerBean, propertyName, trans);
persister.saveManyToManyAssociations(owner, propertyName, trans);
wrap.commitIfCreated();
@@ -1747,21 +1704,12 @@ public final class DefaultServer implements SpiEbeanServer {
public void saveAssociation(Object ownerBean, String propertyName, Transaction t) {
if (ownerBean instanceof EntityBean) {
Set<String> loadedProps = ((EntityBean) ownerBean)._ebean_getIntercept().getLoadedProps();
if (loadedProps != null && !loadedProps.contains(propertyName)) {
// skip as property is not actually loaded in this partially
// loaded bean
logger.debug("Skip saveAssociation as property " + propertyName + " is not loaded");
return;
}
}
EntityBean owner = checkEntityBean(ownerBean);
TransWrapper wrap = initTransIfRequired(t);
try {
SpiTransaction trans = wrap.transaction;
persister.saveAssociation(ownerBean, propertyName, trans);
persister.saveAssociation(owner, propertyName, trans);
wrap.commitIfCreated();
@@ -1797,7 +1745,7 @@ public final class DefaultServer implements SpiEbeanServer {
SpiTransaction trans = wrap.transaction;
int saveCount = 0;
while (it.hasNext()) {
Object bean = it.next();
EntityBean bean = checkEntityBean(it.next());
persister.save(bean, trans);
saveCount++;
}
@@ -1861,10 +1809,8 @@ public final class DefaultServer implements SpiEbeanServer {
* Delete the bean with the explicit transaction.
*/
public void delete(Object bean, Transaction t) {
if (bean == null) {
throw new NullPointerException(Message.msg("bean.isnull"));
}
persister.delete(bean, t);
persister.delete(checkEntityBean(bean), t);
}
/**
@@ -1892,7 +1838,7 @@ public final class DefaultServer implements SpiEbeanServer {
SpiTransaction trans = wrap.transaction;
int deleteCount = 0;
while (it.hasNext()) {
Object bean = it.next();
EntityBean bean = checkEntityBean(it.next());
persister.delete(bean, trans);
deleteCount++;
}
@@ -1995,13 +1941,14 @@ public final class DefaultServer implements SpiEbeanServer {
}
public Object getBeanId(Object bean) {
EntityBean eb = checkEntityBean(bean);
BeanDescriptor<?> desc = getBeanDescriptor(bean.getClass());
if (desc == null) {
String m = bean.getClass().getName() + " is NOT an Entity Bean registered with this server?";
throw new PersistenceException(m);
}
return desc.getId(bean);
return desc.getId(eb);
}
/**
@@ -2067,8 +2014,6 @@ public final class DefaultServer implements SpiEbeanServer {
return transactionManager.createQueryTransaction();
}
private static final int IGNORE_LEADING_ELEMENTS = 5;
private static final String AVAJE_EBEAN = Ebean.class.getName().substring(0, 15);
/**
* Create a CallStack object.
@@ -19,50 +19,55 @@ import com.avaje.ebeaninternal.util.ValueUtil;
public class DiffHelp {
/**
* Return a map of the differences between a and b.
* <p>
* A and B must be of the same type. B can be null, in which case the
* 'OldValues' of a is used to compare with (as B).
* </p>
* <p>
* This intentionally does not include as OneToMany or ManyToMany
* properties.
* </p>
*/
/**
* Return a map of the differences between a and b.
* <p>
* A and B must be of the same type. B can be null, in which case the 'dirty
* values' of a is returned.
* </p>
* <p>
* This intentionally does not include as OneToMany or ManyToMany properties.
* </p>
*/
public Map<String, ValuePair> diff(Object a, Object b, BeanDescriptor<?> desc) {
boolean oldValues = false;
if (a instanceof EntityBean == false) {
throw new IllegalArgumentException("First bean expected to be an enhanced EntityBean? bean:"+a);
}
if (b != null) {
if (b instanceof EntityBean == false) {
throw new IllegalArgumentException("Second bean expected to be an enhanced EntityBean? bean:"+b);
}
if (!a.getClass().isAssignableFrom(b.getClass())) {
throw new IllegalArgumentException("Second bean not assignable to the first bean?");
}
}
if (b == null) {
// get the old values from a
if (a instanceof EntityBean) {
EntityBean eb = (EntityBean) a;
b = eb._ebean_getIntercept().getOldValues();
oldValues = true;
}
return ((EntityBean) a)._ebean_getIntercept().getDirtyValues();
}
Map<String, ValuePair> map = new LinkedHashMap<String, ValuePair>();
if (b == null) {
return map;
}
Map<String, ValuePair> map = new LinkedHashMap<String, ValuePair>();
diff(null, map, (EntityBean)a, (EntityBean)b, desc);
return map;
}
public void diff(String prefix, Map<String, ValuePair> map, EntityBean first, EntityBean sec, BeanDescriptor<?> desc) {
// check the simple properties
BeanProperty[] base = desc.propertiesBaseScalar();
for (int i = 0; i < base.length; i++) {
Object aval = base[i].getValue(a);
Object bval = base[i].getValue(b);
Object aval = base[i].getValue(first);
Object bval = base[i].getValue(sec);
if (!ValueUtil.areEqual(aval, bval)) {
map.put(base[i].getName(), new ValuePair(aval, bval));
String propName = (prefix == null) ? base[i].getName() : prefix + base[i].getName();
map.put(propName, new ValuePair(aval, bval));
}
}
diffAssocOne(a, b, desc, map);
diffEmbedded(a, b, desc, map, oldValues);
return map;
diffAssocOne(prefix, first, sec, desc, map);
diffEmbedded(prefix, first, sec, desc, map);
}
/**
@@ -72,40 +77,24 @@ public class DiffHelp {
* determined to be different as is added to the map.
* </p>
*/
private void diffEmbedded(Object a, Object b, BeanDescriptor<?> desc, Map<String, ValuePair> map,
boolean oldValues) {
private void diffEmbedded(String prefix, EntityBean a, EntityBean b, BeanDescriptor<?> desc, Map<String, ValuePair> map) {
BeanPropertyAssocOne<?>[] emb = desc.propertiesEmbedded();
for (int i = 0; i < emb.length; i++) {
Object aval = emb[i].getValue(a);
Object bval = emb[i].getValue(b);
if (oldValues) {
bval = ((EntityBean) bval)._ebean_getIntercept().getOldValues();
if (bval == null) {
continue;
}
}
EntityBean aval = (EntityBean)emb[i].getValue(a);
EntityBean bval = (EntityBean)emb[i].getValue(b);
if (!isBothNull(aval, bval)) {
String propName = (prefix == null) ? emb[i].getName() : prefix + emb[i].getName();
if (isDiffNull(aval, bval)) {
// one of the embedded beans is null
map.put(emb[i].getName(), new ValuePair(aval, bval));
map.put(propName, new ValuePair(aval, bval));
} else {
// if ANY of the properties in an Embedded bean is
// different, treat the whole bean as being different
BeanProperty[] props = emb[i].getProperties();
for (int j = 0; j < props.length; j++) {
Object aEmbPropVal = props[j].getValue(aval);
Object bEmbPropVal = props[j].getValue(bval);
if (!ValueUtil.areEqual(aEmbPropVal, bEmbPropVal)) {
// if one prop is different put the
// embedded bean in the map
map.put(emb[i].getName(), new ValuePair(aval, bval));
}
}
// recursively diff into the embedded bean
BeanDescriptor<?> embDesc = emb[i].getTargetDescriptor();
diff(emb[i].getName()+".", map, aval, bval, embDesc);
}
}
}
@@ -115,7 +104,7 @@ public class DiffHelp {
* If the properties are different by null OR if the id value is different,
* then add the Assoc One bean to the map.
*/
private void diffAssocOne(Object a, Object b, BeanDescriptor<?> desc, Map<String, ValuePair> map) {
private void diffAssocOne(String prefix, EntityBean a, EntityBean b, BeanDescriptor<?> desc, Map<String, ValuePair> map) {
BeanPropertyAssocOne<?>[] ones = desc.propertiesOne();
@@ -124,20 +113,21 @@ public class DiffHelp {
Object bval = ones[i].getValue(b);
if (!isBothNull(aval, bval)) {
String propName = (prefix == null) ? ones[i].getName() : prefix + ones[i].getName();
if (isDiffNull(aval, bval)) {
// one of them is/was null
map.put(ones[i].getName(), new ValuePair(aval, bval));
map.put(propName, new ValuePair(aval, bval));
} else {
// check to see if the Id properties
// are different
BeanDescriptor<?> oneDesc = ones[i].getTargetDescriptor();
Object aOneId = oneDesc.getId(aval);
Object bOneId = oneDesc.getId(bval);
Object aOneId = oneDesc.getId((EntityBean)aval);
Object bOneId = oneDesc.getId((EntityBean)bval);
if (!ValueUtil.areEqual(aOneId, bOneId)) {
// the ids are different
map.put(ones[i].getName(), new ValuePair(aval, bval));
map.put(propName, new ValuePair(aval, bval));
}
}
}
@@ -116,7 +116,7 @@ public class InternalConfiguration {
this.transactionManager = new TransactionManager(clusterManager, backgroundExecutor,
serverConfig, beanDescriptorManager, this.getBootupClasses());
this.cQueryEngine = new CQueryEngine(serverConfig.getDatabasePlatform(), binder, backgroundExecutor);
this.cQueryEngine = new CQueryEngine(serverConfig.getDatabasePlatform(), binder);
ExternalTransactionManager externalTransactionManager = serverConfig.getExternalTransactionManager();
if (externalTransactionManager == null && serverConfig.isUseJtaTransactionManager()) {
@@ -55,13 +55,6 @@ public final class OrmQueryRequest<T> extends BeanRequest implements BeanQueryRe
private HashQueryPlan queryPlanHash;
/**
* Flag set if background fetching taking place. In this case the transaction
* is rolled back by the background fetching thread. Background fetching
* always takes place in its own transaction.
*/
private boolean backgroundFetching;
/**
* Create the InternalQueryRequest.
*/
@@ -163,12 +156,7 @@ public final class OrmQueryRequest<T> extends BeanRequest implements BeanQueryRe
@Override
public void initTransIfRequired() {
// first check if the query requires its own transaction
if (query.createOwnTransaction()) {
// using background fetch or query listener etc
transaction = ebeanServer.createQueryTransaction();
createdTransaction = true;
} else if (transaction == null) {
if (transaction == null) {
// maybe a current one
transaction = ebeanServer.getCurrentServerTransaction();
if (transaction == null) {
@@ -202,19 +190,12 @@ public final class OrmQueryRequest<T> extends BeanRequest implements BeanQueryRe
* </p>
*/
public void endTransIfRequired() {
if (createdTransaction && !backgroundFetching) {
if (createdTransaction) {
// we can rollback as readOnly transaction
transaction.rollback();
}
}
/**
* This query is using background fetching.
*/
public void setBackgroundFetching() {
backgroundFetching = true;
}
/**
* Return true if this is a find by id (rather than List Set or Map).
*/
@@ -277,12 +258,11 @@ public final class OrmQueryRequest<T> extends BeanRequest implements BeanQueryRe
public Map<?, ?> findMap() {
String mapKey = query.getMapKey();
if (mapKey == null) {
BeanProperty[] ids = beanDescriptor.propertiesId();
if (ids.length == 1) {
query.setMapKey(ids[0].getName());
BeanProperty idProp = beanDescriptor.getIdProperty();
if (idProp != null) {
query.setMapKey(idProp.getName());
} else {
String msg = "No mapKey specified for query";
throw new PersistenceException(msg);
throw new PersistenceException("No mapKey specified for query");
}
}
return (Map<?, ?>) queryEngine.findMany(this);
@@ -356,8 +336,7 @@ public final class OrmQueryRequest<T> extends BeanRequest implements BeanQueryRe
cacheKey = query.queryHash();
// TODO: Sort out returning BeanCollection from L2 cache
return null;
return beanDescriptor.queryCacheGet(cacheKey);
}
public void putToQueryCache(BeanCollection<T> queryResult) {
@@ -12,7 +12,7 @@ import com.avaje.ebeaninternal.server.persist.PersistExecute;
public abstract class PersistRequest extends BeanRequest implements BatchPostExecute {
public enum Type {
INSERT, UPDATE, DELETE, ORMUPDATE, UPDATESQL, CALLABLESQL
DETERMINE, INSERT, UPDATE, DELETE, ORMUPDATE, UPDATESQL, CALLABLESQL
};
boolean persistCascade;
@@ -31,7 +31,7 @@ public abstract class PersistRequest extends BeanRequest implements BatchPostExe
super(server, t);
this.persistExecute = persistExecute;
}
/**
* Execute a the request or queue/batch it for later execution.
*/
@@ -90,14 +90,6 @@ public abstract class PersistRequest extends BeanRequest implements BatchPostExe
return type;
}
/**
* Set the type of this request. One of INSERT, UPDATE, DELETE, UPDATESQL or
* CALLABLESQL.
*/
public void setType(Type type) {
this.type = type;
}
/**
* Return true if save and delete should cascade.
*/
@@ -1,11 +1,14 @@
package com.avaje.ebeaninternal.server.core;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.OptimisticLockException;
import com.avaje.ebean.ValuePair;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
@@ -19,6 +22,7 @@ import com.avaje.ebeaninternal.api.TransactionEvent;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanManager;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
import com.avaje.ebeaninternal.server.persist.BatchControl;
import com.avaje.ebeaninternal.server.persist.PersistExecute;
import com.avaje.ebeaninternal.server.persist.dml.GenerateDmlRequest;
@@ -41,6 +45,13 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
*/
protected final BeanPersistController controller;
/**
* The bean being persisted.
*/
protected final T bean;
protected final EntityBean entityBean;
/**
* The associated intercept.
*/
@@ -51,25 +62,10 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
*/
protected final Object parentBean;
protected final boolean isDirty;
protected final boolean dirty;
/**
* The bean being persisted.
*/
protected final T bean;
/**
* Old values used for concurrency checking.
*/
protected T oldValues;
/**
* The concurrency mode used for update or delete.
*/
protected ConcurrencyMode concurrencyMode;
protected final Set<String> loadedProps;
/**
* The unique id used for logging summary.
*/
@@ -81,97 +77,82 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
protected Integer beanHash;
protected Integer beanIdentityHash;
protected final Set<String> changedProps;
protected boolean notifyCache;
private boolean statelessUpdate;
private boolean deleteMissingChildren;
private boolean updateNullProperties;
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.
*/
private boolean updatedManysOnly;
/**
* Used for forced update of a bean.
* Many properties that were cascade saved (and hence might need cache update later).
*/
public PersistRequestBean(SpiEbeanServer server, T bean, Object parentBean, BeanManager<T> mgr, SpiTransaction t,
PersistExecute persistExecute, Set<String> updateProps, ConcurrencyMode concurrencyMode) {
private List<BeanPropertyAssocMany<?>> updatedManys;
super(server, t, persistExecute);
this.beanManager = mgr;
this.beanDescriptor = mgr.getBeanDescriptor();
this.beanPersistListener = beanDescriptor.getPersistListener();
this.bean = bean;
this.parentBean = parentBean;
this.controller = beanDescriptor.getPersistController();
this.concurrencyMode = beanDescriptor.getConcurrencyMode();
this.concurrencyMode = concurrencyMode;
this.loadedProps = updateProps;
this.changedProps = updateProps;
this.isDirty = true;
this.oldValues = bean;
if (bean instanceof EntityBean) {
this.intercept = ((EntityBean) bean)._ebean_getIntercept();
} else {
this.intercept = null;
}
}
@SuppressWarnings("unchecked")
public PersistRequestBean(SpiEbeanServer server, T bean, Object parentBean, BeanManager<T> mgr,
SpiTransaction t, PersistExecute persistExecute) {
SpiTransaction t, PersistExecute persistExecute, PersistRequest.Type type) {
super(server, t, persistExecute);
this.entityBean = (EntityBean)bean;
this.intercept = entityBean._ebean_getIntercept();
this.beanManager = mgr;
this.beanDescriptor = mgr.getBeanDescriptor();
this.beanPersistListener = beanDescriptor.getPersistListener();
if (PersistRequest.Type.DETERMINE != type) {
this.type = type;
} else {
this.type = beanDescriptor.isInsertMode(intercept) ? Type.INSERT : Type.UPDATE;
}
if (this.type == Type.UPDATE && intercept.isNew() ) {
intercept.setNewBeanForUpdate();
}
this.dirtyPropertyNames = (beanPersistListener == null) ? null : intercept.getDirtyPropertyNames();
this.bean = bean;
this.parentBean = parentBean;
this.controller = beanDescriptor.getPersistController();
this.concurrencyMode = beanDescriptor.getConcurrencyMode();
this.intercept = ((EntityBean) bean)._ebean_getIntercept();
if (intercept.isReference()) {
// allowed to delete reference objects
// with no concurrency checking
this.concurrencyMode = ConcurrencyMode.NONE;
}
this.concurrencyMode = beanDescriptor.getConcurrencyMode(intercept);
// this is ok to not use isNewOrDirty() as used for updates only
this.isDirty = intercept.isDirty();
if (!isDirty) {
this.changedProps = intercept.getChangedProps();
} else {
// merge changed properties on the bean with changed embedded beans
Set<String> beanChangedProps = intercept.getChangedProps();
Set<String> dirtyEmbedded = beanDescriptor.getDirtyEmbeddedProperties(bean);
this.changedProps = mergeChangedProperties(beanChangedProps, dirtyEmbedded);
}
this.loadedProps = intercept.getLoadedProps();
this.oldValues = (T) intercept.getOldValues();
this.dirty = intercept.isDirty();
}
/**
* Merge the changed properties for the bean and embedded beans.
* Return true if this is an insert request.
*/
private Set<String> mergeChangedProperties(Set<String> beanChangedProps, Set<String> embChanged) {
if (embChanged == null) {
return beanChangedProps;
} else if (beanChangedProps == null) {
return embChanged;
} else {
beanChangedProps.addAll(embChanged);
return beanChangedProps;
}
}
public boolean isInsert() {
return Type.INSERT == type;
}
@Override
public Set<String> getLoadedProperties() {
return intercept.getLoadedPropertyNames();
}
@Override
public Set<String> getUpdatedProperties() {
return intercept.getDirtyPropertyNames();
}
@Override
public Map<String, ValuePair> getUpdatedValues() {
return intercept.getDirtyValues();
}
public boolean isNotify(TransactionEvent txnEvent) {
this.notifyCache = beanDescriptor.isCacheNotify();
return notifyCache || isNotifyPersistListener();
}
public boolean isNotifyCache() {
return notifyCache;
}
public boolean isNotifyPersistListener() {
return beanPersistListener != null;
}
@@ -183,10 +164,10 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
if (notifyCache) {
switch (type) {
case INSERT:
beanDescriptor.cacheInsert(idValue, this);
beanDescriptor.cacheHandleInsert(idValue, this);
break;
case UPDATE:
beanDescriptor.cacheUpdate(idValue, this);
beanDescriptor.cacheHandleUpdate(idValue, this);
break;
case DELETE:
// Bean deleted from cache early via postDelete()
@@ -199,7 +180,7 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
public void addToPersistMap(BeanPersistIdMap beanPersistMap) {
beanPersistMap.add(beanDescriptor, type, idValue);
beanPersistMap.add(beanDescriptor, type, idValue);
}
public boolean notifyLocalPersistListener() {
@@ -212,7 +193,7 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
return beanPersistListener.inserted(bean);
case UPDATE:
return beanPersistListener.updated(bean, getUpdatedProperties());
return beanPersistListener.updated(bean, dirtyPropertyNames);
case DELETE:
return beanPersistListener.deleted(bean);
@@ -229,7 +210,7 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
/**
* Return true if this bean has been already been persisted
* (inserted/updated or deleted) in this transaction.
* (inserted or updated) in this transaction.
*/
public boolean isRegisteredBean() {
return transaction.isRegisteredBean(bean);
@@ -247,7 +228,7 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
*/
private Integer getBeanHash() {
if (beanHash == null) {
Object id = beanDescriptor.getId(bean);
Object id = beanDescriptor.getId(entityBean);
int hc = 31 * bean.getClass().getName().hashCode();
if (id != null) {
hc += id.hashCode();
@@ -276,21 +257,6 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
}
}
/**
* Set the type of this request. One of INSERT, UPDATE, DELETE, UPDATESQL or
* CALLABLESQL.
*/
@Override
public void setType(Type type) {
this.type = type;
notifyCache = beanDescriptor.isCacheNotify();
if (type == Type.DELETE || type == Type.UPDATE) {
if (oldValues == null) {
oldValues = bean;
}
}
}
public BeanManager<T> getBeanManager() {
return beanManager;
}
@@ -317,14 +283,6 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
return deleteMissingChildren;
}
/**
* Return true if null properties should be updated (treated as loaded) for
* stateless updates.
*/
public boolean isUpdateNullProperties() {
return updateNullProperties;
}
/**
* Set to true if this is a stateless update.
* <p>
@@ -333,10 +291,9 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
* that was probably created from JSON or XML.
* </p>
*/
public void setStatelessUpdate(boolean statelessUpdate, boolean deleteMissingChildren, boolean updateNullProperties) {
public void setStatelessUpdate(boolean statelessUpdate, boolean deleteMissingChildren) {
this.statelessUpdate = statelessUpdate;
this.deleteMissingChildren = deleteMissingChildren;
this.updateNullProperties = updateNullProperties;
}
/**
@@ -344,7 +301,7 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
* for EntityBeans that have not been modified.
*/
public boolean isDirty() {
return isDirty;
return dirty;
}
/**
@@ -354,20 +311,6 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
return concurrencyMode;
}
/**
* Set loaded properties when generated values has added properties such as
* created and updated timestamps.
*/
public void setLoadedProps(Set<String> additionalProps) {
if (intercept != null) {
intercept.setLoadedProps(additionalProps);
}
}
public Set<String> getLoadedProperties() {
return loadedProps;
}
/**
* Returns a description of the request. This is typically the bean class
* name or the base table for MapBeans.
@@ -387,25 +330,22 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
return bean;
}
/**
public EntityBean getEntityBean() {
return entityBean;
}
/**
* Return the Id value for the bean.
*/
public Object getBeanId() {
return beanDescriptor.getId(bean);
return beanDescriptor.getId(entityBean);
}
public BeanDelta createDeltaBean() {
return new BeanDelta(beanDescriptor, getBeanId());
}
/**
* Get the old values bean. This is used to perform optimistic concurrency
* checking on updates and deletes.
*/
public T getOldValues() {
return oldValues;
}
/**
* Return the parent bean for cascading save with unidirectional
* relationship.
@@ -434,11 +374,7 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
* bean).
*/
public boolean isLoadedProperty(BeanProperty prop) {
if (loadedProps == null) {
return true;
} else {
return loadedProps.contains(prop.getName());
}
return intercept.isLoadedProperty(prop.getPropertyIndex());
}
@Override
@@ -485,13 +421,8 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
*/
public void setGeneratedKey(Object idValue) {
if (idValue != null) {
// set back to the bean so that we can use the same bean later
// for update [refer ebeanIntercept.setLoaded(true)].
idValue = beanDescriptor.convertSetId(idValue, bean);
// remember it for logging summary
this.idValue = idValue;
this.idValue = beanDescriptor.convertSetId(idValue, entityBean);
}
}
@@ -518,7 +449,7 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
// Delete the bean from the PersistenceContent
transaction.getPersistenceContext().clear(beanDescriptor.getBeanType(), idValue);
// Delete from cache early even if transaction fails
beanDescriptor.cacheDelete(idValue, this);
beanDescriptor.cacheHandleDelete(idValue, this);
}
/**
@@ -597,18 +528,18 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
* </p>
*/
public ConcurrencyMode determineConcurrencyMode() {
if (loadedProps != null) {
// 'partial bean' update/delete...
if (concurrencyMode.equals(ConcurrencyMode.VERSION)) {
// check the version property was loaded
BeanProperty prop = beanDescriptor.firstVersionProperty();
if (prop != null && loadedProps.contains(prop.getName())) {
// OK to use version property
} else {
concurrencyMode = ConcurrencyMode.ALL;
}
// 'partial bean' update/delete...
if (concurrencyMode.equals(ConcurrencyMode.VERSION)) {
// check the version property was loaded
BeanProperty prop = beanDescriptor.getVersionProperty();
if (prop != null && intercept.isLoadedProperty(prop.getPropertyIndex())) {
// OK to use version property
} else {
concurrencyMode = ConcurrencyMode.NONE;
}
}
return concurrencyMode;
}
@@ -619,7 +550,7 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
* </p>
*/
public boolean isDynamicUpdateSql() {
return beanDescriptor.isUpdateChangesOnly() || (loadedProps != null);
return beanDescriptor.isUpdateChangesOnly() || !intercept.isFullyLoadedBean();
}
/**
@@ -630,37 +561,74 @@ public class PersistRequestBean<T> extends PersistRequest implements BeanPersist
* </p>
*/
public GenerateDmlRequest createGenerateDmlRequest(boolean emptyStringAsNull) {
if (beanDescriptor.isUpdateChangesOnly()) {
return new GenerateDmlRequest(emptyStringAsNull, changedProps, loadedProps, oldValues);
} else {
return new GenerateDmlRequest(emptyStringAsNull, loadedProps, loadedProps, oldValues);
}
}
/**
* Return the updated properties. If this returns null then all the
* properties on the bean where updated.
*/
public Set<String> getUpdatedProperties() {
if (changedProps != null) {
return changedProps;
}
return loadedProps;
return new GenerateDmlRequest(emptyStringAsNull, intercept, beanDescriptor.isUpdateChangesOnly());
}
/**
* Test if the property value has changed and if so include it in the
* update.
*/
public boolean hasChanged(BeanProperty prop) {
if (changedProps == null) {
return false;
}
return changedProps.contains(prop.getName());
public boolean isAddToUpdate(BeanProperty prop) {
return intercept.isDirtyProperty(prop.getPropertyIndex());
}
public List<DerivedRelationshipData> getDerivedRelationships() {
return transaction.getDerivedRelationship(bean);
public List<DerivedRelationshipData> getDerivedRelationships() {
return transaction.getDerivedRelationship(bean);
}
public void postInsert() {
// mark all properties as loaded after an insert to support immediate update
int len = intercept.getPropertyLength();
for (int i = 0; i < len; i++) {
intercept.setLoadedProperty(i);
}
}
public boolean isReference() {
return beanDescriptor.isReference(intercept);
}
/**
* This many property has been cascade saved. Keep note of this and update the 'many property'
* cache on post commit.
*/
public void addUpdatedManyProperty(BeanPropertyAssocMany<?> updatedAssocMany) {
//if (notifyCache) {
if (updatedManys == null) {
updatedManys = new ArrayList<BeanPropertyAssocMany<?>>(5);
}
updatedManys.add(updatedAssocMany);
//}
}
/**
* Return the list of cascade updated many properties (can be null).
*/
public List<BeanPropertyAssocMany<?>> getUpdatedManyCollections() {
return updatedManys;
}
/**
* 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.
*/
public void checkUpdatedManysOnly() {
if (!dirty && updatedManys != null) {
// set the flag and register for post commit processing if there
// is caching or registered listeners
if (idValue == null) {
this.idValue = beanDescriptor.getId(entityBean);
}
updatedManysOnly = true;
addEvent();
}
}
/**
* Return true if only many properties where updated.
*/
public boolean isUpdatedManysOnly() {
return updatedManysOnly;
}
}
@@ -1,12 +1,12 @@
package com.avaje.ebeaninternal.server.core;
import java.util.Collection;
import java.util.Set;
import com.avaje.ebean.CallableSql;
import com.avaje.ebean.SqlUpdate;
import com.avaje.ebean.Transaction;
import com.avaje.ebean.Update;
import com.avaje.ebean.bean.EntityBean;
/**
@@ -17,23 +17,23 @@ public interface Persister {
/**
* Force an Update using the given bean.
*/
public void forceUpdate(Object entityBean, Set<String> updateProps, Transaction t, boolean deleteMissingChildren, boolean updateNullProperties);
public void forceUpdate(EntityBean entityBean, Transaction t, boolean deleteMissingChildren);
/**
* Force an Insert using the given bean.
*/
public void forceInsert(Object entityBean, Transaction t);
public void forceInsert(EntityBean entityBean, Transaction t);
/**
* Insert or update the bean depending on its state.
*/
public void save(Object entityBean, Transaction t);
public void save(EntityBean entityBean, Transaction t);
/**
* Save the associations of a ManyToMany given the owner bean and the
* propertyName of the ManyToMany collection.
*/
public void saveManyToManyAssociations(Object ownerBean, String propertyName, Transaction t);
public void saveManyToManyAssociations(EntityBean ownerBean, String propertyName, Transaction t);
/**
* Save an association (OneToMany, ManyToOne, OneToOne or ManyToMany).
@@ -45,12 +45,12 @@ public interface Persister {
* @param t
* the transaction to use.
*/
public void saveAssociation(Object parentBean, String propertyName, Transaction t);
public void saveAssociation(EntityBean parentBean, String propertyName, Transaction t);
/**
* Delete the associations of a ManyToMany given the owner bean and the property name of the ManyToMany.
*/
public int deleteManyToManyAssociations(Object ownerBean, String propertyName, Transaction t);
public int deleteManyToManyAssociations(EntityBean ownerBean, String propertyName, Transaction t);
/**
* Delete a bean given it's type and id value.
@@ -63,7 +63,7 @@ public interface Persister {
/**
* Delete the bean.
*/
public void delete(Object entityBean, Transaction t);
public void delete(EntityBean entityBean, Transaction t);
/**
* Delete multiple beans given a collection of Id values.
@@ -201,12 +201,12 @@ public class CreateTableVisitor extends AbstractBeanVisitor {
}
BeanProperty[] ids = descriptor.propertiesId();
BeanProperty idProp = descriptor.getIdProperty();
if (ids.length == 0){
if (idProp == null){
// No comma + new line
ctx.removeLast().removeLast();
} else if (ids.length > 1 || ddl.isInlinePrimaryKeyConstraint()) {
} else if (ddl.isInlinePrimaryKeyConstraint()) {
// The Primary Key constraint was inlined with the column
// ... No comma + new line
ctx.removeLast().removeLast();
@@ -216,7 +216,7 @@ public class CreateTableVisitor extends AbstractBeanVisitor {
String pkName = ddl.getPrimaryKeyName(table);
ctx.write(" constraint ").write(pkName).write(" primary key (");
VisitorUtil.visit(ids, new AbstractPropertyVisitor() {
VisitorUtil.visit(idProp, new AbstractPropertyVisitor() {
@Override
public void visitEmbeddedScalar(BeanProperty p, BeanPropertyAssocOne<?> embedded) {
@@ -43,36 +43,36 @@ public class VisitorUtil {
/**
* Visit the bean using a visitor.
*/
public static void visitBean(BeanDescriptor<?> desc, BeanVisitor visitor) {
public static void visitBean(BeanDescriptor<?> desc, BeanVisitor visitor) {
if (visitor.visitBean(desc)) {
if (visitor.visitBean(desc)) {
BeanProperty[] propertiesId = desc.propertiesId();
for (int i = 0; i < propertiesId.length; i++) {
visit(visitor, propertiesId[i]);
}
BeanPropertyAssocOne<?> unidirectional = desc.getUnidirectional();
if (unidirectional != null){
visit(visitor, unidirectional);
}
BeanProperty[] propertiesNonTransient = desc.propertiesNonTransient();
for (int i = 0; i < propertiesNonTransient.length; i++) {
BeanProperty p = propertiesNonTransient[i];
if (!p.isFormula() && !p.isSecondaryTable()){
visit(visitor, p);
}
}
visitor.visitBeanEnd(desc);
}
}
private static void visit(BeanVisitor visitor, BeanProperty p) {
PropertyVisitor pv = visitor.visitProperty(p);
if (pv != null){
visit(p, pv);
BeanProperty idProp = desc.getIdProperty();
if (idProp != null) {
visit(visitor, idProp);
}
BeanPropertyAssocOne<?> unidirectional = desc.getUnidirectional();
if (unidirectional != null) {
visit(visitor, unidirectional);
}
BeanProperty[] propertiesNonTransient = desc.propertiesNonTransient();
for (int i = 0; i < propertiesNonTransient.length; i++) {
BeanProperty p = propertiesNonTransient[i];
if (!p.isFormula() && !p.isSecondaryTable()) {
visit(visitor, p);
}
}
}
visitor.visitBeanEnd(desc);
}
}
private static void visit(BeanVisitor visitor, BeanProperty p) {
PropertyVisitor pv = visitor.visitProperty(p);
if (pv != null) {
visit(p, pv);
}
}
/**
* Visit all the properties.
@@ -8,6 +8,7 @@ import com.avaje.ebean.Transaction;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.BeanCollectionAdd;
import com.avaje.ebean.bean.BeanCollectionLoader;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
/**
@@ -41,22 +42,22 @@ public interface BeanCollectionHelp<T> {
/**
* Add a bean to the List Set or Map.
*/
public void add(BeanCollection<?> collection, Object bean);
public void add(BeanCollection<?> collection, EntityBean bean);
/**
* Create a lazy loading proxy for a List Set or Map.
*/
public BeanCollection<T> createReference(Object parentBean, String propertyName);
public BeanCollection<T> createReference(EntityBean parentBean, String propertyName);
/**
* Refresh the List Set or Map.
*/
public void refresh(EbeanServer server, Query<?> query, Transaction t, Object parentBean);
public void refresh(EbeanServer server, Query<?> query, Transaction t, EntityBean parentBean);
/**
* Apply the new refreshed BeanCollection to the appropriate property of the parent bean.
*/
public void refresh(BeanCollection<?> bc, Object parentBean);
public void refresh(BeanCollection<?> bc, EntityBean parentBean);
/**
* Write the collection out as json.
@@ -0,0 +1,42 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.Collection;
import java.util.Map;
import javax.persistence.PersistenceException;
import com.avaje.ebean.bean.BeanCollection;
/**
* Utility methods for BeanCollections.
*/
public class BeanCollectionUtil {
/**
* Return the details of the collection or map taking care to avoid
* unnecessary fetching of the data.
*/
public static Collection<?> getActualEntries(Object o) {
if (o == null) {
return null;
}
if (o instanceof BeanCollection<?>) {
BeanCollection<?> bc = (BeanCollection<?>) o;
if (!bc.isPopulated()) {
return null;
}
// For maps this is a collection of Map.Entry, otherwise it
// returns a collection of beans
return bc.getActualEntries();
}
if (o instanceof Map<?, ?>) {
// yes, we want the entrySet (to set the keys)
return ((Map<?, ?>) o).entrySet();
} else if (o instanceof Collection<?>) {
return ((Collection<?>) o);
}
throw new PersistenceException("expecting a Map or Collection but got [" + o.getClass().getName() + "]");
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,600 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.Query;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebean.bean.PersistenceContext;
import com.avaje.ebean.cache.ServerCache;
import com.avaje.ebean.cache.ServerCacheManager;
import com.avaje.ebeaninternal.api.SpiQuery;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.api.TransactionEventTable.TableIUD;
import com.avaje.ebeaninternal.server.cache.CachedBeanData;
import com.avaje.ebeaninternal.server.cache.CachedBeanDataFromBean;
import com.avaje.ebeaninternal.server.cache.CachedBeanDataToBean;
import com.avaje.ebeaninternal.server.cache.CachedBeanDataUpdate;
import com.avaje.ebeaninternal.server.cache.CachedManyIds;
import com.avaje.ebeaninternal.server.core.CacheOptions;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.loadcontext.DLoadContext;
import com.avaje.ebeaninternal.server.querydefn.NaturalKeyBindParam;
import com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext;
/**
* Helper for BeanDescriptor that manages the bean, query and collection caches.
*
* @param <T> The entity bean type
*/
public final class BeanDescriptorCacheHelp<T> {
public static final Logger queryLog = LoggerFactory.getLogger("org.avaje.ebean.cache.QUERY");
public static final Logger beanLog = LoggerFactory.getLogger("org.avaje.ebean.cache.BEAN");
public static final Logger manyLog = LoggerFactory.getLogger("org.avaje.ebean.cache.COLL");
public static final Logger natLog = LoggerFactory.getLogger("org.avaje.ebean.cache.NATKEY");
private final BeanDescriptor<T> desc;
private final ServerCacheManager cacheManager;
private final CacheOptions cacheOptions;
/**
* Flag indicating this bean has no relationships.
*/
private final boolean cacheSharableBeans;
private final Class<T> beanType;
private final String cacheName;
private final BeanPropertyAssocOne<?>[] propertiesOneImported;
private ServerCache beanCache;
private ServerCache naturalKeyCache;
private ServerCache queryCache;
public BeanDescriptorCacheHelp(BeanDescriptor<T> desc, ServerCacheManager cacheManager, CacheOptions cacheOptions,
boolean cacheSharableBeans, BeanPropertyAssocOne<?>[] propertiesOneImported) {
this.desc = desc;
this.beanType = desc.getBeanType();
this.cacheName = beanType.getSimpleName();
this.cacheManager = cacheManager;
this.cacheOptions = cacheOptions;
this.cacheSharableBeans = cacheSharableBeans;
this.propertiesOneImported = propertiesOneImported;
}
/**
* Initialise the cache once the server has started.
*/
public void initialise() {
if (cacheOptions.isUseNaturalKeyCache()) {
this.naturalKeyCache = cacheManager.getNaturalKeyCache(beanType);
}
if (cacheOptions.isUseCache()) {
this.beanCache = cacheManager.getBeanCache(beanType);
}
}
/**
* Execute the warming cache query (if defined) and load the cache.
*/
public void runCacheWarming(EbeanServer ebeanServer) {
if (cacheOptions == null) {
return;
}
String warmingQuery = cacheOptions.getWarmingQuery();
if (warmingQuery != null && warmingQuery.trim().length() > 0) {
Query<?> query = ebeanServer.createQuery(beanType, warmingQuery);
query.setUseCache(true);
query.setReadOnly(true);
query.setLoadBeanCache(true);
List<?> list = query.findList();
if (beanLog.isInfoEnabled()) {
beanLog.info("Loaded {} cache with [{}] beans", cacheName, list.size());
}
}
}
/**
* Return true if there is currently query caching for this type of bean.
*/
public boolean isQueryCaching() {
return queryCache != null;
}
/**
* Return true if there is currently bean caching for this type of bean.
*/
public boolean isBeanCaching() {
return beanCache != null;
}
/**
* Return true if the persist request needs to notify the cache.
*/
public boolean isCacheNotify() {
if (isBeanCaching() || isQueryCaching()) {
return true;
}
for (int i = 0; i < propertiesOneImported.length; i++) {
if (propertiesOneImported[i].getTargetDescriptor().isBeanCaching()) {
return true;
}
}
return false;
}
public CacheOptions getCacheOptions() {
return cacheOptions;
}
/**
* Clear the query cache.
*/
public void queryCacheClear() {
if (queryCache != null) {
if (queryLog.isDebugEnabled()) {
queryLog.debug(" CLEAR {}", cacheName);
}
queryCache.clear();
}
}
/**
* Get a query result from the query cache.
*/
@SuppressWarnings("unchecked")
public BeanCollection<T> queryCacheGet(Object id) {
if (queryCache == null) {
return null;
} else {
return (BeanCollection<T>) queryCache.get(id);
}
}
/**
* Put a query result into the query cache.
*/
public void queryCachePut(Object id, BeanCollection<T> query) {
if (queryCache == null) {
queryCache = cacheManager.getQueryCache(beanType);
}
if (queryLog.isDebugEnabled()) {
queryLog.debug(" PUT {} {}", cacheName, id);
}
queryCache.put(id, query);
}
public void manyPropRemove(Object parentId, String propertyName) {
ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, propertyName);
if (manyLog.isDebugEnabled()) {
manyLog.debug(" REMOVE {}({}).{}", cacheName, parentId, propertyName);
}
collectionIdsCache.remove(parentId);
}
public void manyPropClear(String propertyName) {
ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, propertyName);
if (manyLog.isDebugEnabled()) {
manyLog.debug(" CLEAR {}(*).{} ", cacheName, propertyName);
}
collectionIdsCache.clear();
}
/**
* Return the CachedManyIds for a given bean many property. Returns null if not in the cache.
*/
public CachedManyIds manyPropGet(Object parentId, String propertyName) {
ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, propertyName);
CachedManyIds entry = (CachedManyIds) collectionIdsCache.get(parentId);
if (entry == null) {
if (manyLog.isTraceEnabled()) {
manyLog.trace(" GET {}({}).{} - cache miss", cacheName, parentId, propertyName);
}
} else if (manyLog.isDebugEnabled()) {
manyLog.debug(" GET {}({}).{} - hit", cacheName, parentId, propertyName);
}
return entry;
}
/**
* Try to load the bean collection from cache return true if successful.
*/
public boolean manyPropLoad(BeanPropertyAssocMany<?> many, BeanCollection<?> bc, Object parentId, Boolean readOnly) {
CachedManyIds entry = manyPropGet(parentId, many.getName());
if (entry == null) {
// not in cache so return unsuccessful
return false;
}
Object ownerBean = bc.getOwnerBean();
EntityBeanIntercept ebi = ((EntityBean) ownerBean)._ebean_getIntercept();
PersistenceContext persistenceContext = ebi.getPersistenceContext();
BeanDescriptor<?> targetDescriptor = many.getTargetDescriptor();
List<Object> idList = entry.getIdList();
bc.checkEmptyLazyLoad();
for (int i = 0; i < idList.size(); i++) {
Object id = idList.get(i);
Object refBean = targetDescriptor.createReference(readOnly, id);
EntityBeanIntercept refEbi = ((EntityBean) refBean)._ebean_getIntercept();
many.add(bc, (EntityBean) refBean);
persistenceContext.put(id, refBean);
refEbi.setPersistenceContext(persistenceContext);
}
return true;
}
/**
* Put the beanCollection into the cache.
*/
public void manyPropPut(BeanPropertyAssocMany<?> many, Object details, Object parentId) {
BeanDescriptor<?> targetDescriptor = many.getTargetDescriptor();
ArrayList<Object> idList = new ArrayList<Object>();
// get the underlying collection of beans (in the List, Set or Map)
Collection<?> actualDetails = BeanCollectionUtil.getActualEntries(details);
for (Object bean : actualDetails) {
// Collect the id values
idList.add(targetDescriptor.getId((EntityBean) bean));
}
CachedManyIds entry = new CachedManyIds(idList);
ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, many.getName());
if (manyLog.isDebugEnabled()) {
manyLog.debug(" PUT {}({}).{} - ids:{}", cacheName, parentId, many.getName(), entry);
}
collectionIdsCache.put(parentId, entry);
}
public T naturalKeyLookup(SpiQuery<T> query, SpiTransaction t) {
if (!isNaturalKeyCaching(query.isUseBeanCache())) {
// no natural key caching for this query
return null;
}
// check if it is a find by unique id (using the natural key)
NaturalKeyBindParam keyBindParam = query.getNaturalKeyBindParam();
if (keyBindParam == null || !isNaturalKey(keyBindParam.getName())) {
// query is not appropriate
return null;
}
// try to lookup the id using the natural key
Object id = naturalKeyCache.get(keyBindParam.getValue());
if (natLog.isTraceEnabled()) {
natLog.trace(" LOOKUP {}({}) - id:{}", cacheName, keyBindParam.getValue(), id);
}
if (id == null) {
return null;
}
// try looking up into the bean cache using the id
T cacheBean = beanCacheGetInternal(id, query.isReadOnly());
if (cacheBean != null) {
setupContext(cacheBean, query, getPersistenceContext(t));
}
return cacheBean;
}
private PersistenceContext getPersistenceContext(SpiTransaction t) {
PersistenceContext context = null;
if (t == null) {
t = desc.getEbeanServer().getCurrentServerTransaction();
}
if (t != null) {
context = t.getPersistenceContext();
}
return context;
}
private boolean isNaturalKeyCaching(Boolean queryUseCache) {
return naturalKeyCache != null && (queryUseCache == null || queryUseCache.booleanValue());
}
private boolean isNaturalKey(String propName) {
return propName != null && propName.equals(cacheOptions.getNaturalKey());
}
/**
* For a bean built from the cache this sets up its persistence context for future lazy loading etc.
*/
private void setupContext(Object bean, SpiQuery<T> query, PersistenceContext context) {
if (context == null) {
context = new DefaultPersistenceContext();
}
context.put(query.getId(), bean);
DLoadContext loadContext = new DLoadContext(desc.getEbeanServer(), desc, query.isReadOnly(), query);
loadContext.setPersistenceContext(context);
EntityBeanIntercept ebi = ((EntityBean) bean)._ebean_getIntercept();
ebi.setPersistenceContext(context);
loadContext.register(null, ebi);
}
/**
* Return the beanCache creating it if necessary.
*/
private ServerCache getBeanCache() {
if (beanCache == null) {
beanCache = cacheManager.getBeanCache(beanType);
}
return beanCache;
}
/**
* Clear the bean cache.
*/
public void beanCacheClear() {
if (beanCache != null) {
if (beanLog.isDebugEnabled()) {
beanLog.debug(" CLEAR {}", cacheName);
}
beanCache.clear();
}
}
/**
* Put a bean into the bean cache.
*/
public void beanCachePut(EntityBean bean) {
CachedBeanData beanData = CachedBeanDataFromBean.extract(desc, bean);
Object id = desc.getId(bean);
if (beanLog.isDebugEnabled()) {
beanLog.debug(" PUT {}({})", cacheName, id);
}
getBeanCache().put(id, beanData);
if (beanData.isNaturalKeyUpdate() && naturalKeyCache != null) {
Object naturalKey = beanData.getNaturalKey();
if (naturalKey != null) {
if (natLog.isDebugEnabled()) {
natLog.debug(" PUT {}({}, {})", cacheName, naturalKey, id);
}
naturalKeyCache.put(naturalKey, id);
}
}
}
public CachedBeanData beanCacheGetData(Object id) {
return (CachedBeanData) getBeanCache().get(id);
}
public T beanCacheGet(SpiQuery<T> query, PersistenceContext context) {
T bean = beanCacheGetInternal(query.getId(), query.isReadOnly());
if (bean != null) {
setupContext(bean, query, context);
}
return bean;
}
/**
* Return a bean from the bean cache.
*/
@SuppressWarnings("unchecked")
private T beanCacheGetInternal(Object id, Boolean readOnly) {
CachedBeanData d = (CachedBeanData) getBeanCache().get(id);
if (d == null) {
if (beanLog.isTraceEnabled()) {
beanLog.trace(" GET {}({}) - cache miss", cacheName, id);
}
return null;
}
if (cacheSharableBeans && !Boolean.FALSE.equals(readOnly)) {
Object bean = d.getSharableBean();
if (bean != null) {
if (beanLog.isTraceEnabled()) {
beanLog.trace(" GET {}({}) - hit shared bean", cacheName, id);
}
return (T) bean;
}
}
EntityBean bean = desc.createBean();
desc.convertSetId(id, bean);
if (Boolean.TRUE.equals(readOnly)) {
bean._ebean_getIntercept().setReadOnly(true);
}
CachedBeanDataToBean.load(desc, bean, d);
if (beanLog.isTraceEnabled()) {
beanLog.trace(" GET {}({}) - hit", cacheName, id);
}
return (T) bean;
}
/**
* Remove a bean from the cache given its Id.
*/
public void beanCacheRemove(Object id) {
if (beanCache != null) {
if (beanLog.isDebugEnabled()) {
beanLog.debug(" REMOVE {}({})", cacheName, id);
}
beanCache.remove(id);
}
for (int i = 0; i < propertiesOneImported.length; i++) {
propertiesOneImported[i].cacheClear();
}
}
/**
* Returns true if it managed to populate/load the bean from the cache.
*/
public boolean beanCacheLoad(EntityBean bean, EntityBeanIntercept ebi, Object id) {
CachedBeanData cacheData = (CachedBeanData) getBeanCache().get(id);
if (cacheData == null) {
if (beanLog.isTraceEnabled()) {
beanLog.trace(" LOAD {}({}) - cache miss", cacheName, id);
}
return false;
}
int lazyLoadProperty = ebi.getLazyLoadPropertyIndex();
if (lazyLoadProperty > -1 && !cacheData.isLoaded(lazyLoadProperty)) {
if (beanLog.isTraceEnabled()) {
beanLog.trace(" LOAD {}({}) - cache miss on property", cacheName, id);
}
return false;
}
CachedBeanDataToBean.load(desc, bean, cacheData);
if (beanLog.isDebugEnabled()) {
beanLog.debug(" LOAD {}({}) - hit", cacheName, id);
}
return true;
}
/**
* Remove a bean from the cache given its Id.
*/
public void handleDelete(Object id, PersistRequestBean<T> deleteRequest) {
if (queryCache != null) {
if (queryLog.isDebugEnabled()) {
queryLog.debug(" CLEAR {}(*) - delete trigger", cacheName);
}
queryCache.clear();
}
if (beanCache != null) {
if (beanLog.isDebugEnabled()) {
beanLog.debug(" REMOVE {}({})", cacheName, id);
}
beanCache.remove(id);
}
for (int i = 0; i < propertiesOneImported.length; i++) {
BeanPropertyAssocMany<?> many = propertiesOneImported[i].getRelationshipProperty();
if (many != null) {
propertiesOneImported[i].cacheDelete(true, deleteRequest.getEntityBean());
}
}
}
public void handleInsert(Object id, PersistRequestBean<T> insertRequest) {
if (queryCache != null) {
if (queryLog.isDebugEnabled()) {
queryLog.debug(" CLEAR {}(*) - insert trigger", cacheName);
}
queryCache.clear();
}
for (int i = 0; i < propertiesOneImported.length; i++) {
propertiesOneImported[i].cacheDelete(false, insertRequest.getEntityBean());
}
}
/**
* Update the cached bean data.
*/
public void handleUpdate(Object id, PersistRequestBean<T> updateRequest) {
if (queryCache != null) {
if (queryLog.isDebugEnabled()) {
queryLog.debug(" CLEAR {}(*) - update trigger", cacheName);
}
queryCache.clear();
}
List<BeanPropertyAssocMany<?>> manyCollections = updateRequest.getUpdatedManyCollections();
if (manyCollections != null) {
// clear the appropriate manyProp caches first
for (int i = 0; i < manyCollections.size(); i++) {
manyPropRemove(id, manyCollections.get(i).getName());
}
}
// check if the bean itself was updated
if (!updateRequest.isUpdatedManysOnly()) {
// update the bean cache entry if it exists
ServerCache cache = getBeanCache();
CachedBeanData existingData = (CachedBeanData) cache.get(id);
if (existingData != null) {
if (isCachedDataTooOld(existingData)) {
// just remove the entry from the cache
if (beanLog.isDebugEnabled()) {
beanLog.debug(" REMOVE {}({}) - entry too old", cacheName, id);
}
cache.remove(id);
} else {
// Update the cache data with the changes from our update
CachedBeanData newData = CachedBeanDataUpdate.update(desc, existingData, updateRequest.getEntityBean());
if (beanLog.isDebugEnabled()) {
beanLog.debug(" UPDATE {}({})", cacheName, id);
}
cache.put(id, newData);
if (newData.isNaturalKeyUpdate() && naturalKeyCache != null) {
Object oldKey = newData.getOldNaturalKey();
Object newKey = newData.getNaturalKey();
if (natLog.isDebugEnabled()) {
natLog.debug(".. update {} PUT({}, {}) REMOVE({})", cacheName, newKey, id, oldKey);
}
if (oldKey != null) {
naturalKeyCache.remove(oldKey);
}
if (newKey != null) {
naturalKeyCache.put(newKey, id);
}
}
}
}
}
if (manyCollections != null) {
for (int i = 0; i < manyCollections.size(); i++) {
BeanPropertyAssocMany<?> many = manyCollections.get(i);
Object manyValue = many.getValue(updateRequest.getEntityBean());
manyPropPut(many, manyValue, id);
}
}
}
private boolean isCachedDataTooOld(CachedBeanData existingData) {
return cacheOptions.isTooOldInMillis(System.currentTimeMillis() - existingData.getWhenCreated());
}
/**
* Invalidate parts of cache due to SqlUpdate or external modification etc.
*/
public void handleBulkUpdate(TableIUD tableIUD) {
// inserts don't invalidate the bean cache
if (tableIUD.isUpdateOrDelete()) {
beanCacheClear();
}
// any change invalidates the query cache
queryCacheClear();
}
}
@@ -61,6 +61,7 @@ import com.avaje.ebeaninternal.server.lib.util.Dnode;
import com.avaje.ebeaninternal.server.reflect.BeanReflect;
import com.avaje.ebeaninternal.server.reflect.BeanReflectFactory;
import com.avaje.ebeaninternal.server.reflect.BeanReflectGetter;
import com.avaje.ebeaninternal.server.reflect.BeanReflectProperties;
import com.avaje.ebeaninternal.server.reflect.BeanReflectSetter;
import com.avaje.ebeaninternal.server.reflect.EnhanceBeanReflectFactory;
import com.avaje.ebeaninternal.server.type.TypeManager;
@@ -221,8 +222,8 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
}
}
public IdBinder createIdBinder(BeanProperty[] uids) {
return idBinderFactory.createIdBinder(uids);
public IdBinder createIdBinder(BeanProperty idProperty) {
return idBinderFactory.createIdBinder(idProperty);
}
public void deploy() {
@@ -280,7 +281,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
List<BeanDescriptor<?>> list = getBeanDescriptors(tableIUD.getTableName());
if (list != null) {
for (int i = 0; i < list.size(); i++) {
list.get(i).cacheNotify(tableIUD);
list.get(i).cacheHandleBulkUpdate(tableIUD);
}
}
}
@@ -1298,43 +1299,34 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
// abstract classes as well.
Class<?> beanType = desc.getBeanType();
Class<?> factType = desc.getFactoryType();
BeanReflect beanReflect = reflectFactory.create(beanType, factType);
BeanReflectProperties reflectProps = new BeanReflectProperties(beanType);
BeanReflect beanReflect = reflectFactory.create(beanType);
desc.setBeanReflect(beanReflect);
desc.setProperties(reflectProps.getProperties());
try {
Iterator<DeployBeanProperty> it = desc.propertiesAll();
while (it.hasNext()) {
DeployBeanProperty prop = it.next();
String propName = prop.getName();
Iterator<DeployBeanProperty> it = desc.propertiesAll();
while (it.hasNext()) {
DeployBeanProperty prop = it.next();
String propName = prop.getName();
Integer pos = reflectProps.getPropertyIndex(propName);
if (pos == null) {
throw new IllegalStateException("Property "+propName+" not found in "+reflectProps);
}
if (desc.isAbstract() || beanReflect.isVanillaOnly()) {
// use reflection in the case of imported abstract class
// with
// inheritance. Refer Bug 166
prop.setGetter(ReflectGetter.create(prop));
prop.setSetter(ReflectSetter.create(prop));
} else {
// use generated code for getting setting property values
BeanReflectGetter getter = beanReflect.getGetter(propName);
BeanReflectSetter setter = beanReflect.getSetter(propName);
prop.setGetter(getter);
prop.setSetter(setter);
if (getter == null) {
// should never happen
String m = "BeanReflectGetter for " + prop.getFullBeanName() + " was not found?";
throw new RuntimeException(m);
}
}
BeanReflectGetter getter = beanReflect.getGetter(propName, pos.intValue());
BeanReflectSetter setter = beanReflect.getSetter(propName, pos.intValue());
prop.setGetter(getter);
prop.setSetter(setter);
prop.setPropertyIndex(pos.intValue());
if (getter == null) {
String m = "BeanReflectGetter for " + prop.getFullBeanName() + " was not found?";
throw new RuntimeException(m);
}
} catch (IllegalArgumentException e) {
Class<?> superClass = desc.getBeanType().getSuperclass();
String msg = "Error with [" + desc.getFullName() + "] I believe it is not enhanced but it's superClass [" + superClass + "] is?"
+ " (You are not allowed to mix enhancement in a single inheritance hierarchy)";
throw new PersistenceException(msg, e);
}
}
@@ -1345,13 +1337,15 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
*/
private void setConcurrencyMode(DeployBeanDescriptor<?> desc) {
if (!desc.getConcurrencyMode().equals(ConcurrencyMode.ALL)) {
if (desc.getConcurrencyMode() != null) {
// concurrency mode explicitly set during deployment
return;
}
if (checkForVersionProperties(desc)) {
desc.setConcurrencyMode(ConcurrencyMode.VERSION);
} else {
desc.setConcurrencyMode(ConcurrencyMode.NONE);
}
}
@@ -1390,91 +1384,35 @@ public class BeanDescriptorManager implements BeanDescriptorMap {
Class<?> beanClass = desc.getBeanType();
if (desc.isAbstract()) {
if (hasEntityBeanInterface(beanClass)) {
checkEnhanced(desc, beanClass);
} else {
checkSubclass(desc, beanClass);
}
return;
if (!hasEntityBeanInterface(beanClass)) {
throw new IllegalStateException("Bean "+beanClass+" is not enhanced?");
}
try {
Object testBean = null;
try {
testBean = beanClass.newInstance();
} catch (InstantiationException e) {
// expected when no default constructor
logger.debug("no default constructor on " + beanClass + " e:" + e);
} catch (IllegalAccessException e) {
// expected when no default constructor
logger.debug("no default constructor on " + beanClass + " e:" + e);
}
if (testBean instanceof EntityBean == false) {
checkSubclass(desc, beanClass);
} else {
String className = beanClass.getName();
try {
// check that it really is enhanced (rather than mixed
// enhancement)
String marker = ((EntityBean) testBean)._ebean_getMarker();
if (!marker.equals(className)) {
String msg = "Error with [" + desc.getFullName() + "] It has not been enhanced but it's superClass ["
+ beanClass.getSuperclass() + "] is?" + " (You are not allowed to mix enhancement in a single inheritance hierarchy)"
+ " marker[" + marker + "] className[" + className + "]";
throw new PersistenceException(msg);
}
} catch (AbstractMethodError e) {
throw new PersistenceException("Old Ebean v1.0 enhancement detected in Ebean v1.1 - please do a clean enhancement.", e);
}
checkEnhanced(desc, beanClass);
}
} catch (PersistenceException ex) {
throw ex;
} catch (Exception ex) {
throw new PersistenceException(ex);
}
}
private void checkEnhanced(DeployBeanDescriptor<?> desc, Class<?> beanClass) {
// the bean already implements EntityBean
checkInheritedClasses(true, beanClass);
desc.setFactoryType(beanClass);
enhancedClassCount++;
}
checkInheritedClasses(beanClass);
private void checkSubclass(DeployBeanDescriptor<?> desc, Class<?> beanClass) {
throw new PersistenceException("Entity type "+beanClass+" is not an enhanced entity bean. Subclassing is not longer supported in Ebean");
if (!beanClass.getName().startsWith("com.avaje.ebean.meta")) {
enhancedClassCount++;
}
}
/**
* Check that the inherited classes are the same as the entity bean (aka all
* enhanced or all dynamically subclassed).
*/
private void checkInheritedClasses(boolean ensureEnhanced, Class<?> beanClass) {
private void checkInheritedClasses(Class<?> beanClass) {
Class<?> superclass = beanClass.getSuperclass();
if (Object.class.equals(superclass)) {
// we got to the top of the inheritance
return;
}
boolean isClassEnhanced = EntityBean.class.isAssignableFrom(superclass);
if (ensureEnhanced != isClassEnhanced) {
String msg;
if (ensureEnhanced) {
msg = "Class [" + superclass + "] is not enhanced and [" + beanClass + "] is - (you can not mix!!)";
} else {
msg = "Class [" + superclass + "] is enhanced and [" + beanClass + "] is not - (you can not mix!!)";
}
throw new IllegalStateException(msg);
if (!EntityBean.class.isAssignableFrom(superclass)) {
throw new IllegalStateException("Super type "+superclass+" is not enhanced?");
}
// recursively continue up the inheritance hierarchy
checkInheritedClasses(ensureEnhanced, superclass);
checkInheritedClasses(superclass);
}
/**
@@ -32,6 +32,6 @@ public interface BeanDescriptorMap {
*/
public EncryptKey getEncryptKey(String tableName, String columnName);
public IdBinder createIdBinder(BeanProperty[] uids);
public IdBinder createIdBinder(BeanProperty id);
}
@@ -16,16 +16,4 @@ public class BeanEmbeddedMeta {
return properties;
}
/**
* Return true if at least one property is a version property.
*/
public boolean isEmbeddedVersion() {
for (int i = 0; i < properties.length; i++) {
if (properties[i].isVersion()){
return true;
}
}
return false;
}
}
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.text.StringFormatter;
import com.avaje.ebean.text.StringParser;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
@@ -95,7 +96,7 @@ public final class BeanFkeyProperty implements ElPropertyValue {
/**
* Returns null as not an AssocOne.
*/
public Object[] getAssocOneIdValues(Object value) {
public Object[] getAssocOneIdValues(EntityBean value) {
return null;
}
@@ -159,7 +160,7 @@ public final class BeanFkeyProperty implements ElPropertyValue {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public void elSetReference(Object bean) {
public void elSetReference(EntityBean bean) {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
@@ -167,15 +168,15 @@ public final class BeanFkeyProperty implements ElPropertyValue {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public void elSetValue(Object bean, Object value, boolean populate, boolean reference) {
public void elSetValue(EntityBean bean, Object value, boolean populate) {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public Object elGetValue(Object bean) {
public Object elGetValue(EntityBean bean) {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public Object elGetReference(Object bean) {
public Object elGetReference(EntityBean bean) {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
@@ -10,6 +10,7 @@ import com.avaje.ebean.Transaction;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.BeanCollectionAdd;
import com.avaje.ebean.bean.BeanCollectionLoader;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.common.BeanList;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
@@ -35,11 +36,11 @@ public final class BeanListHelp<T> implements BeanCollectionHelp<T> {
public void setLoader(BeanCollectionLoader loader) {
this.loader = loader;
}
/**
* Internal add bypassing any modify listening.
*/
public void add(BeanCollection<?> collection, Object bean) {
public void add(BeanCollection<?> collection, EntityBean bean) {
collection.internalAdd(bean);
}
@@ -70,7 +71,7 @@ public final class BeanListHelp<T> implements BeanCollectionHelp<T> {
this.list = list;
}
public void addBean(Object bean) {
public void addBean(EntityBean bean) {
list.add(bean);
}
}
@@ -90,20 +91,20 @@ public final class BeanListHelp<T> implements BeanCollectionHelp<T> {
return beanList;
}
public BeanCollection<T> createReference(Object parentBean, String propertyName) {
public BeanCollection<T> createReference(EntityBean parentBean, String propertyName) {
BeanList<T> beanList = new BeanList<T>(loader, parentBean, propertyName);
beanList.setModifyListening(many.getModifyListenMode());
return beanList;
}
public void refresh(EbeanServer server, Query<?> query, Transaction t, Object parentBean) {
public void refresh(EbeanServer server, Query<?> query, Transaction t, EntityBean parentBean) {
BeanList<?> newBeanList = (BeanList<?>) server.findList(query, t);
refresh(newBeanList, parentBean);
}
public void refresh(BeanCollection<?> bc, Object parentBean) {
public void refresh(BeanCollection<?> bc, EntityBean parentBean) {
BeanList<?> newBeanList = (BeanList<?>) bc;
@@ -152,7 +153,7 @@ public final class BeanListHelp<T> implements BeanCollectionHelp<T> {
ctx.appendComma();
}
Object detailBean = list.get(j);
targetDescriptor.jsonWrite(ctx, detailBean);
targetDescriptor.jsonWrite(ctx, (EntityBean)detailBean);
}
ctx.endAssocMany();
}
@@ -11,6 +11,7 @@ import com.avaje.ebean.Transaction;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.BeanCollectionAdd;
import com.avaje.ebean.bean.BeanCollectionLoader;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.common.BeanMap;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
@@ -93,7 +94,7 @@ public final class BeanMapHelp<T> implements BeanCollectionHelp<T> {
this.map = map;
}
public void addBean(Object bean) {
public void addBean(EntityBean bean) {
Object keyValue = beanProperty.getValue(bean);
map.put(keyValue, bean);
}
@@ -111,18 +112,15 @@ public final class BeanMapHelp<T> implements BeanCollectionHelp<T> {
return beanMap;
}
/**
* Internal add bypassing any modify listening.
*/
public void add(BeanCollection<?> collection, Object bean) {
public void add(BeanCollection<?> collection, EntityBean bean) {
Object keyValue = beanProperty.getValueIntercept(bean);
((BeanMap<?,?>) collection).internalPut(keyValue, bean);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public BeanCollection<T> createReference(Object parentBean, String propertyName) {
public BeanCollection<T> createReference(EntityBean parentBean, String propertyName) {
BeanMap beanMap = new BeanMap(loader, parentBean, propertyName);
if (many != null) {
@@ -131,12 +129,12 @@ public final class BeanMapHelp<T> implements BeanCollectionHelp<T> {
return beanMap;
}
public void refresh(EbeanServer server, Query<?> query, Transaction t, Object parentBean) {
public void refresh(EbeanServer server, Query<?> query, Transaction t, EntityBean parentBean) {
BeanMap<?, ?> newBeanMap = (BeanMap<?, ?>) server.findMap(query, t);
refresh(newBeanMap, parentBean);
}
public void refresh(BeanCollection<?> bc, Object parentBean) {
public void refresh(BeanCollection<?> bc, EntityBean parentBean) {
BeanMap<?, ?> newBeanMap = (BeanMap<?, ?>) bc;
Map<?, ?> current = (Map<?, ?>) many.getValue(parentBean);
@@ -187,7 +185,7 @@ public final class BeanMapHelp<T> implements BeanCollectionHelp<T> {
}
//FIXME: json write map key ...
Object detailBean = entry.getValue();
targetDescriptor.jsonWrite(ctx, detailBean);
targetDescriptor.jsonWrite(ctx, (EntityBean)detailBean);
}
ctx.endAssocMany();
}
@@ -33,7 +33,6 @@ import com.avaje.ebeaninternal.server.text.json.ReadJsonContext;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
import com.avaje.ebeaninternal.server.type.DataBind;
import com.avaje.ebeaninternal.server.type.ScalarType;
import com.avaje.ebeaninternal.util.ValueUtil;
/**
* Description of a property of a bean. Includes its deployment information such
@@ -141,6 +140,8 @@ public class BeanProperty implements ElPropertyValue {
*/
final String name;
final int propertyIndex;
/**
* The reflected field.
*/
@@ -249,8 +250,6 @@ public class BeanProperty implements ElPropertyValue {
final DbEncryptFunction dbEncryptFunction;
final boolean dynamicSubclassWithInheritance;
int deployOrder;
final boolean jsonSerialize;
@@ -265,11 +264,8 @@ public class BeanProperty implements ElPropertyValue {
this.descriptor = descriptor;
this.name = InternString.intern(deploy.getName());
if (descriptor != null) {
this.dynamicSubclassWithInheritance = (descriptor.isDynamicSubclass() && descriptor.hasInheritance());
} else {
this.dynamicSubclassWithInheritance = false;
}
this.propertyIndex = deploy.getPropertyIndex();
this.unidirectionalShadow = deploy.isUndirectionalShadow();
this.localEncrypted = deploy.isLocalEncrypted();
this.dbEncrypted = deploy.isDbEncrypted();
@@ -363,7 +359,7 @@ public class BeanProperty implements ElPropertyValue {
this.descriptor = source.descriptor;
this.name = InternString.intern(source.getName());
this.dynamicSubclassWithInheritance = source.dynamicSubclassWithInheritance;
this.propertyIndex = source.propertyIndex;
this.dbColumn = InternString.intern(override.getDbColumn());
this.sqlFormulaJoin = InternString.intern(override.getSqlFormulaJoin());
@@ -473,14 +469,7 @@ public class BeanProperty implements ElPropertyValue {
return formula;
}
public boolean hasChanged(Object bean, Object oldValues) {
Object value = getValue(bean);
Object oldVal = getValue(oldValues);
return !ValueUtil.areEqual(value, oldVal);
}
public void copyProperty(Object sourceBean, Object destBean) {
public void copyProperty(EntityBean sourceBean, EntityBean destBean) {
Object value = getValue(sourceBean);
setValue(destBean, value);
}
@@ -561,7 +550,7 @@ public class BeanProperty implements ElPropertyValue {
return owningType.isAssignableFrom(type);
}
public Object readSetOwning(DbReadContext ctx, Object bean, Class<?> type) throws SQLException {
public Object readSetOwning(DbReadContext ctx, EntityBean bean, Class<?> type) throws SQLException {
try {
Object value = scalarType.read(ctx.getDataReader());
@@ -599,7 +588,7 @@ public class BeanProperty implements ElPropertyValue {
return scalarType.read(ctx.getDataReader());
}
public Object readSet(DbReadContext ctx, Object bean, Class<?> type) throws SQLException {
public Object readSet(DbReadContext ctx, EntityBean bean, Class<?> type) throws SQLException {
try {
Object value = scalarType.read(ctx.getDataReader());
@@ -690,15 +679,9 @@ public class BeanProperty implements ElPropertyValue {
* Set the value of the property without interception or
* PropertyChangeSupport.
*/
public void setValue(Object bean, Object value) {
public void setValue(EntityBean bean, Object value) {
try {
if (bean instanceof EntityBean) {
setter.set(bean, value);
} else {
Object[] args = new Object[1];
args[0] = value;
writeMethod.invoke(bean, args);
}
setter.set(bean, value);
} catch (Exception ex) {
String beanType = bean == null ? "null" : bean.getClass().getName();
String msg = "set " + name + " on [" + descriptor + "] arg[" + value + "] type[" + beanType
@@ -710,15 +693,9 @@ public class BeanProperty implements ElPropertyValue {
/**
* Set the value of the property.
*/
public void setValueIntercept(Object bean, Object value) {
public void setValueIntercept(EntityBean bean, Object value) {
try {
if (bean instanceof EntityBean) {
setter.setIntercept(bean, value);
} else {
Object[] args = new Object[1];
args[0] = value;
writeMethod.invoke(bean, args);
}
setter.setIntercept(bean, value);
} catch (Exception ex) {
String beanType = bean == null ? "null" : bean.getClass().getName();
String msg = "setIntercept " + name + " on [" + descriptor + "] arg[" + value + "] type[" + beanType
@@ -729,34 +706,20 @@ public class BeanProperty implements ElPropertyValue {
private static Object[] NO_ARGS = new Object[0];
/**
* Return the property value taking inheritance into account.
*/
public Object getValueWithInheritance(Object bean) {
if (dynamicSubclassWithInheritance) {
return descriptor.getBeanPropertyWithInheritance(bean, name);
}
return getValue(bean);
}
public Object getCacheDataValue(Object bean){
public Object getCacheDataValue(EntityBean bean){
return getValue(bean);
}
public void setCacheDataValue(Object bean, Object cacheData, Object oldValues, boolean readOnly){
public void setCacheDataValue(EntityBean bean, Object cacheData){
setValue(bean, cacheData);
}
/**
* Return the value of the property method.
*/
public Object getValue(Object bean) {
public Object getValue(EntityBean bean) {
try {
if (bean instanceof EntityBean) {
return getter.get(bean);
} else {
return readMethod.invoke(bean, NO_ARGS);
}
return getter.get(bean);
} catch (Exception ex) {
String beanType = bean == null ? "null" : bean.getClass().getName();
String msg = "get " + name + " on [" + descriptor + "] type[" + beanType + "] threw error.";
@@ -777,13 +740,9 @@ public class BeanProperty implements ElPropertyValue {
}
}
public Object getValueIntercept(Object bean) {
public Object getValueIntercept(EntityBean bean) {
try {
if (bean instanceof EntityBean) {
return getter.getIntercept(bean);
} else {
return readMethod.invoke(bean, NO_ARGS);
}
return getter.getIntercept(bean);
} catch (Exception ex) {
String beanType = bean == null ? "null" : bean.getClass().getName();
String msg = "getIntercept " + name + " on [" + descriptor + "] type[" + beanType + "] threw error.";
@@ -798,24 +757,21 @@ public class BeanProperty implements ElPropertyValue {
return convertToLogicalType(value);
}
public void elSetReference(Object bean) {
throw new RuntimeException("Should not be called");
}
public void elSetValue(Object bean, Object value, boolean populate, boolean reference) {
public void elSetValue(EntityBean bean, Object value, boolean populate) {
if (bean != null) {
setValueIntercept(bean, value);
// Not using setValueIntercept at this stage
setValue(bean, value);
}
}
public Object elGetValue(Object bean) {
public Object elGetValue(EntityBean bean) {
if (bean == null) {
return null;
}
return getValueIntercept(bean);
}
public Object elGetReference(Object bean) {
public Object elGetReference(EntityBean bean) {
throw new RuntimeException("Not expected to call this");
}
@@ -826,6 +782,13 @@ public class BeanProperty implements ElPropertyValue {
return name;
}
/**
* Return the position of this property in the enhanced bean.
*/
public int getPropertyIndex() {
return propertyIndex;
}
public String getElName() {
return name;
}
@@ -851,7 +814,7 @@ public class BeanProperty implements ElPropertyValue {
return false;
}
public Object[] getAssocOneIdValues(Object bean) {
public Object[] getAssocOneIdValues(EntityBean bean) {
// Returns null as not an AssocOne.
return null;
}
@@ -1177,7 +1140,7 @@ public class BeanProperty implements ElPropertyValue {
}
@SuppressWarnings("unchecked")
public void jsonWrite(WriteJsonContext ctx, Object bean) {
public void jsonWrite(WriteJsonContext ctx, EntityBean bean) {
if(!jsonSerialize){
return;
}
@@ -1189,7 +1152,7 @@ public class BeanProperty implements ElPropertyValue {
}
}
public void jsonRead(ReadJsonContext ctx, Object bean) {
public void jsonRead(ReadJsonContext ctx, EntityBean bean) {
if(!jsonDeserialize){
return;
}
@@ -4,18 +4,18 @@ import java.util.ArrayList;
import javax.persistence.PersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.id.IdBinder;
import com.avaje.ebeaninternal.server.deploy.id.ImportedId;
import com.avaje.ebeaninternal.server.deploy.id.ImportedIdEmbedded;
import com.avaje.ebeaninternal.server.deploy.id.ImportedIdMultiple;
import com.avaje.ebeaninternal.server.deploy.id.ImportedIdSimple;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanPropertyAssoc;
import com.avaje.ebeaninternal.server.el.ElPropertyChainBuilder;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract base for properties mapped to an associated bean, list, set or map.
@@ -216,14 +216,12 @@ public abstract class BeanPropertyAssoc<T> extends BeanProperty {
/**
* Return true if the unique id properties are all not null for this bean.
*/
public boolean hasId(Object bean) {
public boolean hasId(EntityBean bean) {
BeanDescriptor<?> targetDesc = getTargetDescriptor();
BeanProperty[] uids = targetDesc.propertiesId();
for (int i = 0; i < uids.length; i++) {
Object value = uids[i].getValue(bean);
BeanProperty idProp = targetDesc.getIdProperty();
if (idProp != null) {
Object value = idProp.getValue(bean);
if (value == null) {
return false;
}
@@ -311,39 +309,36 @@ public abstract class BeanPropertyAssoc<T> extends BeanProperty {
*/
protected ImportedId createImportedId(BeanPropertyAssoc<?> owner, BeanDescriptor<?> target, TableJoin join) {
BeanProperty[] props = target.propertiesId();
BeanProperty idProp = target.getIdProperty();
BeanProperty[] others = target.propertiesBaseScalar();
if (descriptor.isSqlSelectBased()){
String dbColumn = owner.getDbColumn();
return new ImportedIdSimple(owner, dbColumn, props[0], 0);
return new ImportedIdSimple(owner, dbColumn, idProp, 0);
}
TableJoinColumn[] cols = join.columns();
if (props.length == 1) {
if (!props[0].isEmbedded()) {
// simple single scalar id
if (cols.length != 1){
String msg = "No Imported Id column for ["+props[0]+"] in table ["+join.getTable()+"]";
logger.error(msg);
return null;
} else {
return createImportedScalar(owner, cols[0], props, others);
}
if (idProp == null) {
return null;
}
if (!idProp.isEmbedded()) {
// simple single scalar id
if (cols.length != 1){
String msg = "No Imported Id column for ["+idProp+"] in table ["+join.getTable()+"]";
logger.error(msg);
return null;
} else {
// embedded id
BeanPropertyAssocOne<?> embProp = (BeanPropertyAssocOne<?>)props[0];
BeanProperty[] embBaseProps = embProp.getTargetDescriptor().propertiesBaseScalar();
ImportedIdSimple[] scalars = createImportedList(owner, cols, embBaseProps, others);
return new ImportedIdEmbedded(owner, embProp, scalars);
BeanProperty[] idProps = {idProp};
return createImportedScalar(owner, cols[0], idProps, others);
}
} else {
// Concatenated key that is not embedded
ImportedIdSimple[] scalars = createImportedList(owner, cols, props, others);
return new ImportedIdMultiple(owner, scalars);
// embedded id
BeanPropertyAssocOne<?> embProp = (BeanPropertyAssocOne<?>)idProp;
BeanProperty[] embBaseProps = embProp.getTargetDescriptor().propertiesBaseScalar();
ImportedIdSimple[] scalars = createImportedList(owner, cols, embBaseProps, others);
return new ImportedIdEmbedded(owner, embProp, scalars);
}
}
@@ -17,6 +17,7 @@ import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.BeanCollection.ModifyListenMode;
import com.avaje.ebean.bean.BeanCollectionAdd;
import com.avaje.ebean.bean.BeanCollectionLoader;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiQuery;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.deploy.id.ImportedId;
@@ -148,7 +149,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
/**
* Add the bean to the appropriate collection on the parent bean.
*/
public void addBeanToCollectionWithCreate(Object parentBean, Object detailBean) {
public void addBeanToCollectionWithCreate(EntityBean parentBean, EntityBean detailBean) {
BeanCollection<?> bc = (BeanCollection<?>)super.getValue(parentBean);
if (bc == null) {
bc = (BeanCollection<?>)help.createEmpty(false);
@@ -157,23 +158,35 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
help.add(bc, detailBean);
}
public boolean isEmptyBeanCollection(EntityBean bean) {
Object val = getValue(bean);
if (val == null) {
return true;
}
if (val instanceof BeanCollection<?>) {
// if empty and not been cleared or elements removed
return ((BeanCollection<?>)val).isEmptyAndUntouched();
}
return false;
}
@Override
public Object getValue(Object bean) {
public Object getValue(EntityBean bean) {
return super.getValue(bean);
}
@Override
public Object getValueIntercept(Object bean) {
public Object getValueIntercept(EntityBean bean) {
return super.getValueIntercept(bean);
}
@Override
public void setValue(Object bean, Object value) {
public void setValue(EntityBean bean, Object value) {
super.setValue(bean, value);
}
@Override
public void setValueIntercept(Object bean, Object value) {
public void setValueIntercept(EntityBean bean, Object value) {
super.setValueIntercept(bean, value);
}
@@ -324,7 +337,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
}
@Override
public Object readSet(DbReadContext ctx, Object bean, Class<?> type) throws SQLException {
public Object readSet(DbReadContext ctx, EntityBean bean, Class<?> type) throws SQLException {
return null;
}
@@ -342,21 +355,21 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
return true;
}
public void add(BeanCollection<?> collection, Object bean) {
public void add(BeanCollection<?> collection, EntityBean bean) {
help.add(collection, bean);
}
/**
* Refresh the appropriate list set or map.
*/
public void refresh(EbeanServer server, Query<?> query, Transaction t, Object parentBean) {
public void refresh(EbeanServer server, Query<?> query, Transaction t, EntityBean parentBean) {
help.refresh(server, query, t, parentBean);
}
/**
* Apply the refreshed BeanCollection to the property of the parentBean.
*/
public void refresh(BeanCollection<?> bc, Object parentBean) {
public void refresh(BeanCollection<?> bc, EntityBean parentBean) {
help.refresh(bc, parentBean);
}
@@ -364,7 +377,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
* Return the Id values from the given bean.
*/
@Override
public Object[] getAssocOneIdValues(Object bean) {
public Object[] getAssocOneIdValues(EntityBean bean) {
return targetDescriptor.getIdBinder().getIdValues(bean);
}
@@ -435,7 +448,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
* Set the join properties from the parent bean to the child bean.
* This is only valid for OneToMany and NOT valid for ManyToMany.
*/
public void setJoinValuesToChild(Object parent, Object child, Object mapKeyValue) {
public void setJoinValuesToChild(EntityBean parent, EntityBean child, Object mapKeyValue) {
if (mapKeyProperty != null){
mapKeyProperty.setValue(child, mapKeyValue);
@@ -468,7 +481,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
return mapKey;
}
public BeanCollection<?> createReferenceIfNull(Object parentBean) {
public BeanCollection<?> createReferenceIfNull(EntityBean parentBean) {
Object v = getValue(parentBean);
if (v instanceof BeanCollection<?>){
@@ -479,7 +492,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
}
}
public BeanCollection<?> createReference(Object parentBean) {
public BeanCollection<?> createReference(EntityBean parentBean) {
BeanCollection<?> ref = help.createReference(parentBean, name);
setValue(parentBean, ref);
@@ -494,7 +507,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
return help.getBeanCollectionAdd(bc, mapKey);
}
public Object getParentId(Object parentBean) {
public Object getParentId(EntityBean parentBean) {
return descriptor.getId(parentBean);
}
@@ -506,7 +519,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
for (int i=0; i < parentIds.size(); i++) {
for (int y = 0; y < exportedProperties.length; y++) {
Object compId = parentIds.get(i);
expandedList.add(exportedProperties[y].getValue(compId));
expandedList.add(exportedProperties[y].getValue((EntityBean)compId));
}
}
return expandedList;
@@ -518,8 +531,9 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
sqlUpd.addParameter(parentId);
return;
}
EntityBean parent = (EntityBean)parentId;
for (int i = 0; i < exportedProperties.length; i++) {
Object embVal = exportedProperties[i].getValue(parentId);
Object embVal = exportedProperties[i].getValue(parent);
sqlUpd.addParameter(embVal);
}
}
@@ -531,8 +545,9 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
} else {
EntityBean parent = (EntityBean)parentId;
for (int i = 0; i < exportedProperties.length; i++) {
Object embVal = exportedProperties[i].getValue(parentId);
Object embVal = exportedProperties[i].getValue(parent);
q.setParameter(pos++, embVal);
}
}
@@ -574,7 +589,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
return sb.toString();
}
public void setPredicates(SpiQuery<?> query, Object parentBean) {
public void setPredicates(SpiQuery<?> query, EntityBean parentBean) {
if (manyToMany){
// for ManyToMany lazy loading we need to include a
@@ -585,8 +600,8 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
if (embeddedExportedProperties) {
// use the EmbeddedId object instead of the parentBean
BeanProperty[] uids = descriptor.propertiesId();
parentBean = uids[0].getValue(parentBean);
BeanProperty idProp = descriptor.getIdProperty();
parentBean = (EntityBean)idProp.getValue(parentBean);
}
for (int i = 0; i < exportedProperties.length; i++) {
@@ -618,13 +633,13 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
*/
private ExportedProperty[] createExported() {
BeanProperty[] uids = descriptor.propertiesId();
BeanProperty idProp = descriptor.getIdProperty();
ArrayList<ExportedProperty> list = new ArrayList<ExportedProperty>();
if (uids.length == 1 && uids[0].isEmbedded()) {
if (idProp != null && idProp.isEmbedded()) {
BeanPropertyAssocOne<?> one = (BeanPropertyAssocOne<?>) uids[0];
BeanPropertyAssocOne<?> one = (BeanPropertyAssocOne<?>) idProp;
BeanDescriptor<?> targetDesc = one.getTargetDescriptor();
BeanProperty[] emIds = targetDesc.propertiesBaseScalar();
try {
@@ -638,8 +653,8 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
}
} else {
for (int i = 0; i < uids.length; i++) {
ExportedProperty expProp = findMatch(false, uids[i]);
if (idProp != null) {
ExportedProperty expProp = findMatch(false, idProp);
list.add(expProp);
}
}
@@ -741,7 +756,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
throw new PersistenceException(msg);
}
public IntersectionRow buildManyDeleteChildren(Object parentBean, ArrayList<Object> excludeDetailIds) {
public IntersectionRow buildManyDeleteChildren(EntityBean parentBean, ArrayList<Object> excludeDetailIds) {
IntersectionRow row = new IntersectionRow(tableJoin.getTable());
if (excludeDetailIds != null && !excludeDetailIds.isEmpty()) {
@@ -751,14 +766,14 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
return row;
}
public IntersectionRow buildManyToManyDeleteChildren(Object parentBean) {
public IntersectionRow buildManyToManyDeleteChildren(EntityBean parentBean) {
IntersectionRow row = new IntersectionRow(intersectionJoin.getTable());
buildExport(row, parentBean);
return row;
}
public IntersectionRow buildManyToManyMapBean(Object parent, Object other) {
public IntersectionRow buildManyToManyMapBean(EntityBean parent, EntityBean other) {
IntersectionRow row = new IntersectionRow(intersectionJoin.getTable());
@@ -767,11 +782,11 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
return row;
}
private void buildExport(IntersectionRow row, Object parentBean) {
private void buildExport(IntersectionRow row, EntityBean parentBean) {
if (embeddedExportedProperties) {
BeanProperty[] uids = descriptor.propertiesId();
parentBean = uids[0].getValue(parentBean);
BeanProperty idProp = descriptor.getIdProperty();
parentBean = (EntityBean)idProp.getValue(parentBean);
}
for (int i = 0; i < exportedProperties.length; i++) {
Object val = exportedProperties[i].getValue(parentBean);
@@ -785,7 +800,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
* Set the predicates for lazy loading of the association.
* Handles predicates for both OneToMany and ManyToMany.
*/
private void buildImport(IntersectionRow row, Object otherBean) {
private void buildImport(IntersectionRow row, EntityBean otherBean) {
importedId.buildImport(row, otherBean);
}
@@ -793,12 +808,12 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
/**
* Return true if the otherBean has an Id value.
*/
public boolean hasImportedId(Object otherBean) {
public boolean hasImportedId(EntityBean otherBean) {
return null != targetDescriptor.getId(otherBean);
}
public void jsonWrite(WriteJsonContext ctx, Object bean) {
public void jsonWrite(WriteJsonContext ctx, EntityBean bean) {
if(!this.jsonSerialize){
return;
}
@@ -819,7 +834,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
}
}
public void jsonRead(ReadJsonContext ctx, Object bean){
public void jsonRead(ReadJsonContext ctx, EntityBean bean){
if(!this.jsonDeserialize){
return;
}
@@ -836,7 +851,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
// probably empty array
break;
}
Object detailBean = detailBeanState.getBean();
EntityBean detailBean = (EntityBean)detailBeanState.getBean();
add.addBean(detailBean);
if (bean != null && childMasterProperty != null){
@@ -844,15 +859,12 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
childMasterProperty.setValue(detailBean, bean);
detailBeanState.setLoaded(childMasterProperty.getName());
}
detailBeanState.setLoadedState();
if (!ctx.readArrayNext()){
break;
}
} while(true);
setValue(bean, collection);
}
}
@@ -34,8 +34,6 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
private final boolean oneToOneExported;
private final boolean embeddedVersion;
private final boolean importedPrimaryKey;
private final LocalHelp localHelp;
@@ -78,11 +76,6 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
// Overriding of the columns and use table alias of owning BeanDescriptor
BeanEmbeddedMeta overrideMeta = BeanEmbeddedMetaFactory.create(owner, deploy, descriptor);
embeddedProps = overrideMeta.getProperties();
if (id) {
embeddedVersion = false;
} else {
embeddedVersion = overrideMeta.isEmbeddedVersion();
}
embeddedPropsMap = new HashMap<String, BeanProperty>();
for (int i = 0; i < embeddedProps.length; i++) {
embeddedPropsMap.put(embeddedProps[i].getName(), embeddedProps[i]);
@@ -91,7 +84,6 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
} else {
embeddedProps = null;
embeddedPropsMap = null;
embeddedVersion = false;
}
localHelp = createHelp(embedded, oneToOneExported);
}
@@ -126,22 +118,22 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
public void cacheClear() {
if (targetDescriptor.isBeanCaching() && relationshipProperty != null) {
targetDescriptor.cacheClearCachedManyIds(relationshipProperty.getName());
targetDescriptor.cacheManyPropClear(relationshipProperty.getName());
}
}
public void cacheDelete(boolean clearOnNull, Object bean) {
public void cacheDelete(boolean clearOnNull, EntityBean bean) {
if (targetDescriptor.isBeanCaching() && relationshipProperty != null) {
Object assocBean = getValue(bean);
if (assocBean != null) {
Object parentId = targetDescriptor.getId(assocBean);
Object parentId = targetDescriptor.getId((EntityBean)assocBean);
if (parentId != null) {
targetDescriptor.cacheRemoveCachedManyIds(parentId, relationshipProperty.getName());
targetDescriptor.cacheManyPropRemove(parentId, relationshipProperty.getName());
return;
}
}
if (clearOnNull) {
targetDescriptor.cacheClearCachedManyIds(relationshipProperty.getName());
targetDescriptor.cacheManyPropClear(relationshipProperty.getName());
}
}
}
@@ -249,8 +241,9 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
} else {
int pos = 1;
EntityBean parent = (EntityBean)parentId;
for (int i = 0; i < exportedProperties.length; i++) {
Object embVal = exportedProperties[i].getValue(parentId);
Object embVal = exportedProperties[i].getValue(parent);
q.setParameter(pos++, embVal);
}
}
@@ -270,41 +263,6 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
return true;
}
private boolean hasChangedEmbedded(Object bean, Object oldValues) {
Object embValue = getValue(oldValues);
if (embValue instanceof EntityBean) {
// the embedded bean .. has its own old values
return ((EntityBean) embValue)._ebean_getIntercept().isNewOrDirty();
}
if (embValue == null) {
return getValue(bean) != null;
} else {
return false;
}
}
@Override
public boolean hasChanged(Object bean, Object oldValues) {
if (embedded) {
return hasChangedEmbedded(bean, oldValues);
}
Object value = getValue(bean);
Object oldVal = getValue(oldValues);
if (oneToOneExported) {
// FKey on other side
return false;
} else {
if (value == null) {
return oldVal != null;
} else if (oldValues == null) {
return true;
}
return importedId.hasChanged(value, oldVal);
}
}
/**
* Return meta data for the deployment of the embedded bean specific to this
* property.
@@ -342,13 +300,6 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
return oneToOneExported;
}
/**
* Returns true if the associated bean has version properties.
*/
public boolean isEmbeddedVersion() {
return embeddedVersion;
}
/**
* If true this bean maps to the primary key.
*/
@@ -364,7 +315,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
return getPropertyType();
}
public Object getCacheDataValue(Object bean){
public Object getCacheDataValue(EntityBean bean){
if (embedded) {
throw new RuntimeException();
} else {
@@ -372,24 +323,19 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
if (ap == null){
return null;
} else {
return targetDescriptor.getId(ap);
return targetDescriptor.getId((EntityBean)ap);
}
}
}
public void setCacheDataValue(Object bean, Object cacheData, Object oldValues, boolean readOnly){
@Override
public void setCacheDataValue(EntityBean bean, Object cacheData){
if (cacheData != null) {
if (embedded){
throw new RuntimeException();
} else {
T ref = targetDescriptor.createReference(Boolean.FALSE, cacheData, null);
T ref = targetDescriptor.createReference(Boolean.FALSE, cacheData);
setValue(bean, ref);
if (oldValues != null){
setValue(oldValues, ref);
}
if (readOnly){
((EntityBean)ref)._ebean_intercept().setReadOnly(true);
}
}
}
}
@@ -398,7 +344,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
* Return the Id values from the given bean.
*/
@Override
public Object[] getAssocOneIdValues(Object bean) {
public Object[] getAssocOneIdValues(EntityBean bean) {
return targetDescriptor.getIdBinder().getIdValues(bean);
}
@@ -451,15 +397,8 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
return targetDescriptor.createEntityBean();
}
public void elSetReference(Object bean) {
Object value = getValueIntercept(bean);
if (value != null) {
((EntityBean) value)._ebean_getIntercept().setReference();
}
}
@Override
public Object elGetReference(Object bean) {
public Object elGetReference(EntityBean bean) {
Object value = getValueIntercept(bean);
if (value == null) {
value = targetDescriptor.createEntityBean();
@@ -495,13 +434,13 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
*/
private ExportedProperty[] createExported() {
BeanProperty[] uids = descriptor.propertiesId();
BeanProperty idProp = descriptor.getIdProperty();
ArrayList<ExportedProperty> list = new ArrayList<ExportedProperty>();
if (uids.length == 1 && uids[0].isEmbedded()) {
if (idProp != null && idProp.isEmbedded()) {
BeanPropertyAssocOne<?> one = (BeanPropertyAssocOne<?>) uids[0];
BeanPropertyAssocOne<?> one = (BeanPropertyAssocOne<?>) idProp;
BeanDescriptor<?> targetDesc = one.getTargetDescriptor();
BeanProperty[] emIds = targetDesc.propertiesBaseScalar();
try {
@@ -515,8 +454,8 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
}
} else {
for (int i = 0; i < uids.length; i++) {
ExportedProperty expProp = findMatch(false, uids[i]);
if (idProp != null) {
ExportedProperty expProp = findMatch(false, idProp);
list.add(expProp);
}
}
@@ -565,7 +504,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
}
@Override
public Object readSet(DbReadContext ctx, Object bean, Class<?> type) throws SQLException {
public Object readSet(DbReadContext ctx, EntityBean bean, Class<?> type) throws SQLException {
boolean assignable = (type == null || owningType.isAssignableFrom(type));
return localHelp.readSet(ctx, bean, assignable);
}
@@ -579,6 +518,24 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
// pass in null for the bean so any data read is ignored
return localHelp.read(ctx);
}
@Override
public void setValue(EntityBean bean, Object value) {
super.setValue(bean, value);
if (value instanceof EntityBean) {
EntityBean embedded = (EntityBean)value;
embedded._ebean_getIntercept().setEmbeddedOwner(bean, propertyIndex);
}
}
@Override
public void setValueIntercept(EntityBean bean, Object value) {
super.setValueIntercept(bean, value);
if (value instanceof EntityBean) {
EntityBean embedded = (EntityBean)value;
embedded._ebean_getIntercept().setEmbeddedOwner(bean, propertyIndex);
}
}
@Override
public void loadIgnore(DbReadContext ctx) {
@@ -615,7 +572,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
abstract Object read(DbReadContext ctx) throws SQLException;
abstract Object readSet(DbReadContext ctx, Object bean, boolean assignAble) throws SQLException;
abstract Object readSet(DbReadContext ctx, EntityBean bean, boolean assignAble) throws SQLException;
abstract void appendSelect(DbSqlContext ctx, boolean subQuery);
@@ -632,7 +589,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
}
@Override
Object readSet(DbReadContext ctx, Object bean, boolean assignable) throws SQLException {
Object readSet(DbReadContext ctx, EntityBean bean, boolean assignable) throws SQLException {
Object dbVal = read(ctx);
if (bean != null && assignable) {
// set back to the parent bean
@@ -694,7 +651,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
}
}
Object readSet(DbReadContext ctx, Object bean, boolean assignable) throws SQLException {
Object readSet(DbReadContext ctx, EntityBean bean, boolean assignable) throws SQLException {
Object val = read(ctx);
if (bean != null && assignable) {
setValue(bean, val);
@@ -733,16 +690,13 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
return existing;
}
// parent always null for this case (but here to document)
Object parent = null;
Boolean readOnly = ctx.isReadOnly();
Object ref;
if (targetInheritInfo != null) {
// for inheritance hierarchy create the correct type for this row...
ref = rowDescriptor.createReference(readOnly, id, parent);
// for inheritance hierarchy create the correct type for this row...
ref = rowDescriptor.createReference(readOnly, id);
} else {
ref = targetDescriptor.createReference(readOnly, id, parent);
ref = targetDescriptor.createReference(readOnly, id);
}
Object existingBean = ctx.getPersistenceContext().putIfAbsent(id, ref);
@@ -802,7 +756,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
* Read and set a Reference bean.
*/
@Override
Object readSet(DbReadContext ctx, Object bean, boolean assignable) throws SQLException {
Object readSet(DbReadContext ctx, EntityBean bean, boolean assignable) throws SQLException {
Object dbVal = read(ctx);
if (bean != null && assignable) {
@@ -828,8 +782,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
if (existing != null) {
return existing;
}
Object parent = null;
Object ref = targetDescriptor.createReference(ctx.isReadOnly(), id, parent);
Object ref = targetDescriptor.createReference(ctx.isReadOnly(), id);
EntityBeanIntercept ebi = ((EntityBean) ref)._ebean_getIntercept();
if (Boolean.TRUE.equals(ctx.isReadOnly())) {
@@ -846,8 +799,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
@Override
void appendSelect(DbSqlContext ctx, boolean subQuery) {
// set appropriate tableAlias for
// the exported id columns
// set appropriate tableAlias for the exported id columns
String relativePrefix = ctx.getRelativePrefix(getName());
ctx.pushTableAlias(relativePrefix);
@@ -867,7 +819,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
}
@Override
public void jsonWrite(WriteJsonContext ctx, Object bean) {
public void jsonWrite(WriteJsonContext ctx, EntityBean bean) {
Object value = getValueIntercept(bean);
if (value == null){
@@ -878,20 +830,29 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
// bi-directional and already rendered parent
} else {
// Hmmm, not writing complex non-entity bean
if (value instanceof EntityBean) {
ctx.pushParentBean(bean);
ctx.beginAssocOne(name);
BeanDescriptor<?> refDesc = descriptor.getBeanDescriptor(value.getClass());
refDesc.jsonWrite(ctx, value);
refDesc.jsonWrite(ctx, (EntityBean)value);
ctx.endAssocOne();
ctx.popParentBean();
}
}
}
}
@Override
public void jsonRead(ReadJsonContext ctx, Object bean){
T assocBean = targetDescriptor.jsonReadBean(ctx, name);
setValue(bean, assocBean);
public void jsonRead(ReadJsonContext ctx, EntityBean bean){
if (targetDescriptor != null) {
T assocBean = targetDescriptor.jsonReadBean(ctx, name);
setValue(bean, assocBean);
}
}
public boolean isReference(Object detailBean) {
EntityBean eb = (EntityBean)detailBean;
return targetDescriptor.isReference(eb._ebean_getIntercept());
}
}
@@ -4,6 +4,7 @@ import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.config.ScalarTypeConverter;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanPropertyCompound;
import com.avaje.ebeaninternal.server.el.ElPropertyChainBuilder;
@@ -89,7 +90,7 @@ public class BeanPropertyCompound extends BeanProperty {
* Get the underlying compound type.
*/
@SuppressWarnings("unchecked")
public Object getValueUnderlying(Object bean) {
public Object getValueUnderlying(EntityBean bean) {
Object value = getValue(bean);
if (typeConverter != null){
@@ -97,27 +98,7 @@ public class BeanPropertyCompound extends BeanProperty {
}
return value;
}
@Override
public Object getValue(Object bean) {
return super.getValue(bean);
}
@Override
public Object getValueIntercept(Object bean) {
return super.getValueIntercept(bean);
}
@Override
public void setValue(Object bean, Object value) {
super.setValue(bean, value);
}
@Override
public void setValueIntercept(Object bean, Object value) {
super.setValueIntercept(bean, value);
}
public ElPropertyValue buildElPropertyValue(String propName, String remainder, ElPropertyChainBuilder chain, boolean propertyDeploy) {
if (chain == null) {
@@ -154,7 +135,7 @@ public class BeanPropertyCompound extends BeanProperty {
}
@Override
public Object readSet(DbReadContext ctx, Object bean, Class<?> type) throws SQLException {
public Object readSet(DbReadContext ctx, EntityBean bean, Class<?> type) throws SQLException {
boolean assignable = (type == null || owningType.isAssignableFrom(type));
@@ -192,17 +173,17 @@ public class BeanPropertyCompound extends BeanProperty {
}
@Override
public Object elGetReference(Object bean) {
public Object elGetReference(EntityBean bean) {
return bean;
}
public void jsonWrite(WriteJsonContext ctx, Object bean) {
public void jsonWrite(WriteJsonContext ctx, EntityBean bean) {
Object valueObject = getValueIntercept(bean);
compoundType.jsonWrite(ctx, valueObject, name);
}
public void jsonRead(ReadJsonContext ctx, Object bean){
public void jsonRead(ReadJsonContext ctx, EntityBean bean){
Object objValue = compoundType.jsonRead(ctx);
setValue(bean, objValue);
@@ -73,7 +73,7 @@ public class BeanPropertyCompoundRoot {
* Set the value of the property without interception or
* PropertyChangeSupport.
*/
public void setRootValue(Object bean, Object value) {
public void setRootValue(EntityBean bean, Object value) {
try {
if (bean instanceof EntityBean) {
setter.set(bean, value);
@@ -92,7 +92,7 @@ public class BeanPropertyCompoundRoot {
/**
* Set the value of the property.
*/
public void setRootValueIntercept(Object bean, Object value) {
public void setRootValueIntercept(EntityBean bean, Object value) {
try {
if (bean instanceof EntityBean) {
setter.setIntercept(bean, value);
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.config.ScalarTypeConverter;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import com.avaje.ebeaninternal.server.type.CtCompoundProperty;
@@ -30,20 +31,21 @@ public class BeanPropertyCompoundScalar extends BeanProperty {
@SuppressWarnings("unchecked")
@Override
public Object getValue(Object valueObject) {
if (typeConverter != null){
valueObject = typeConverter.unwrapValue(valueObject);
public Object getValue(EntityBean valueObject) {
Object val = valueObject;
if (typeConverter != null){
val = typeConverter.unwrapValue(val);
}
return ctProperty.getValue(valueObject);
return ctProperty.getValue(val);
}
@Override
public void setValue(Object bean, Object value) {
public void setValue(EntityBean bean, Object value) {
setValueInCompound(bean, value, false);
}
@SuppressWarnings("unchecked")
public void setValueInCompound(Object bean, Object value, boolean intercept) {
public void setValueInCompound(EntityBean bean, Object value, boolean intercept) {
Object compoundValue = ctProperty.setValue(bean, value);
@@ -65,7 +67,7 @@ public class BeanPropertyCompoundScalar extends BeanProperty {
* No interception on embedded scalar values inside a CVO.
*/
@Override
public void setValueIntercept(Object bean, Object value) {
public void setValueIntercept(EntityBean bean, Object value) {
setValueInCompound(bean, value, true);
}
@@ -73,28 +75,23 @@ public class BeanPropertyCompoundScalar extends BeanProperty {
* No interception on embedded scalar values inside a CVO.
*/
@Override
public Object getValueIntercept(Object bean) {
public Object getValueIntercept(EntityBean bean) {
return getValue(bean);
}
@Override
public Object elGetReference(Object bean) {
public Object elGetReference(EntityBean bean) {
return getValue(bean);
}
@Override
public Object elGetValue(Object bean) {
public Object elGetValue(EntityBean bean) {
return getValue(bean);
}
@Override
public void elSetReference(Object bean) {
super.elSetReference(bean);
}
@Override
public void elSetValue(Object bean, Object value, boolean populate, boolean reference) {
super.elSetValue(bean, value, populate, reference);
public void elSetValue(EntityBean bean, Object value, boolean populate) {//, boolean reference) {
super.elSetValue(bean, value, populate);
}
@@ -10,6 +10,7 @@ import com.avaje.ebean.Transaction;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.BeanCollectionAdd;
import com.avaje.ebean.bean.BeanCollectionLoader;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.common.BeanSet;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
@@ -72,15 +73,12 @@ public final class BeanSetHelp<T> implements BeanCollectionHelp<T> {
this.set = set;
}
public void addBean(Object bean) {
public void addBean(EntityBean bean) {
set.add(bean);
}
}
/**
* Internal add bypassing any modify listening.
*/
public void add(BeanCollection<?> collection, Object bean) {
public void add(BeanCollection<?> collection, EntityBean bean) {
collection.internalAdd(bean);
}
@@ -95,20 +93,20 @@ public final class BeanSetHelp<T> implements BeanCollectionHelp<T> {
return beanSet;
}
public BeanCollection<T> createReference(Object parentBean, String propertyName) {
public BeanCollection<T> createReference(EntityBean parentBean, String propertyName) {
BeanSet<T> beanSet = new BeanSet<T>(loader, parentBean, propertyName);
beanSet.setModifyListening(many.getModifyListenMode());
return beanSet;
}
public void refresh(EbeanServer server, Query<?> query, Transaction t, Object parentBean) {
public void refresh(EbeanServer server, Query<?> query, Transaction t, EntityBean parentBean) {
BeanSet<?> newBeanSet = (BeanSet<?>)server.findSet(query, t);
refresh(newBeanSet, parentBean);
}
public void refresh(BeanCollection<?> bc, Object parentBean) {
public void refresh(BeanCollection<?> bc, EntityBean parentBean) {
BeanSet<?> newBeanSet = (BeanSet<?>)bc;
@@ -158,7 +156,7 @@ public final class BeanSetHelp<T> implements BeanCollectionHelp<T> {
if (count++ > 0){
ctx.appendComma();
}
targetDescriptor.jsonWrite(ctx, detailBean);
targetDescriptor.jsonWrite(ctx, (EntityBean)detailBean);
}
ctx.endAssocMany();
}
@@ -12,6 +12,7 @@ import com.avaje.ebean.event.BeanPersistListener;
public class ChainedBeanPersistListener<T> implements BeanPersistListener<T> {
private final List<BeanPersistListener<T>> list;
private final BeanPersistListener<T>[] chain;
/**
@@ -127,7 +127,7 @@ public class DRawSqlSelect {
sqlTree.setSummary(desc.getName());
LinkedHashSet<String> includedProps = new LinkedHashSet<String>();
SqlTreeProperties selectProps = new SqlTreeProperties();
SqlTreeProperties selectProps = new SqlTreeProperties(desc);
for (int i = 0; i < selectColumns.length; i++) {
@@ -156,7 +156,6 @@ public class DRawSqlSelect {
}
}
selectProps.setIncludedProperties(includedProps);
SqlTreeNode sqlRoot = new SqlTreeNodeRoot(desc, selectProps, null, withId);
sqlTree.setRootNode(sqlRoot);
@@ -193,11 +193,10 @@ public final class DRawSqlSelectColumnsParser {
}
}
BeanProperty[] propertiesId = desc.propertiesId();
for (int i = 0; i < propertiesId.length; i++) {
BeanProperty prop = propertiesId[i];
if (isMatch(prop, searchColumn)) {
return prop;
BeanProperty idProp = desc.getIdProperty();
if (idProp != null) {
if (isMatch(idProp, searchColumn)) {
return idProp;
}
}
@@ -3,6 +3,7 @@ package com.avaje.ebeaninternal.server.deploy;
import java.util.Map;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebean.bean.PersistenceContext;
import com.avaje.ebeaninternal.api.SpiQuery;
@@ -72,12 +73,12 @@ public interface DbReadContext {
/**
* Set back the bean that has just been loaded with its id.
*/
public void setLoadedBean(Object loadedBean, Object id, Object lazyLoadParentId);
public void setLoadedBean(EntityBean loadedBean, Object id, Object lazyLoadParentId);
/**
* Set back the 'detail' bean that has just been loaded.
*/
public void setLoadedManyBean(Object loadedBean);
public void setLoadedManyBean(EntityBean loadedBean);
/**
* Return the query mode.
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.InternString;
/**
@@ -32,7 +33,7 @@ public class ExportedProperty {
/**
* Return the property value from the bean.
*/
public Object getValue(Object bean){
public Object getValue(EntityBean bean){
return property.getValue(bean);
}
@@ -6,6 +6,7 @@ import java.util.HashMap;
import javax.persistence.PersistenceException;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.id.IdBinder;
import com.avaje.ebeaninternal.server.deploy.parse.DeployInheritInfo;
@@ -223,7 +224,7 @@ public class InheritInfo {
/**
* Create an EntityBean for this type.
*/
public Object createBean() {
public EntityBean createBean() {
return descriptor.createBean();
}
@@ -1,85 +0,0 @@
package com.avaje.ebeaninternal.server.deploy;
import java.lang.reflect.Method;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import com.avaje.ebeaninternal.server.reflect.BeanReflectGetter;
/**
* For abstract classes that hold the id property we need to
* use reflection to get the id values some times.
* <p>
* This provides the BeanReflectGetter objects to do that.
* </p>
* @author rbygrave
*/
public class ReflectGetter {
/**
* Create a reflection based BeanReflectGetter for getting the
* id from abstract inheritance hierarchy object.
*/
public static BeanReflectGetter create(DeployBeanProperty prop) {
if (!prop.isId()){
// not expecting this to ever be used/called
return new NonIdGetter(prop.getFullBeanName());
} else {
String property = prop.getFullBeanName();
Method readMethod = prop.getReadMethod();
if (readMethod == null){
String m = "Abstract class with no readMethod for "+property;
throw new RuntimeException(m);
}
return new IdGetter(property, readMethod);
}
}
public static class IdGetter implements BeanReflectGetter {
public static final Object[] NO_ARGS = new Object[0];
private final Method readMethod;
private final String property;
public IdGetter(String property, Method readMethod) {
this.property = property;
this.readMethod = readMethod;
}
public Object get(Object bean) {
try {
return readMethod.invoke(bean, NO_ARGS);
} catch (Exception e) {
String m = "Error on ["+property+"] using readMethod "+readMethod;
throw new RuntimeException(m, e);
}
}
public Object getIntercept(Object bean) {
return get(bean);
}
}
public static class NonIdGetter implements BeanReflectGetter {
private final String property;
public NonIdGetter(String property) {
this.property = property;
}
public Object get(Object bean) {
String m = "Not expecting this method to be called on ["+property
+"] as it is a NON ID property on an abstract class";
throw new RuntimeException(m);
}
public Object getIntercept(Object bean) {
return get(bean);
}
}
}
@@ -1,53 +0,0 @@
package com.avaje.ebeaninternal.server.deploy;
import java.lang.reflect.Method;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import com.avaje.ebeaninternal.server.reflect.BeanReflectSetter;
/**
* A place holder for BeanReflectSetter that should never be called.
* <p>
* This is for properties of classes that are abstract and at the root
* of an inheritance hierarchy.
* </p>
* @author rbygrave
*/
public class ReflectSetter {
/**
* Creates place holder objects that should never be called.
*/
public static BeanReflectSetter create(DeployBeanProperty prop) {
String fullName = prop.getFullBeanName();
Method writeMethod = prop.getWriteMethod();
return new RefCalled(fullName, writeMethod);
}
static class RefCalled implements BeanReflectSetter {
final String fullName;
final Method writeMethod;
RefCalled(String fullName, Method writeMethod) {
this.fullName = fullName;
this.writeMethod = writeMethod;
}
public void set(Object bean, Object value) {
Object[] a = new Object[1];
a[0] = value;
try {
writeMethod.invoke(bean, a);
} catch (Exception e) {
String beanType = bean == null ? "null" : bean.getClass().toString();
String msg = "Error setting value on "+fullName+" value["+value+"] on type["+beanType+"]";
throw new RuntimeException(msg, e);
}
}
public void setIntercept(Object bean, Object value) {
String msg = "Not expecting setIntercept to be called. Refer Bug 368";
throw new RuntimeException(msg);
}
}
}
@@ -3,6 +3,7 @@ package com.avaje.ebeaninternal.server.deploy;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import com.avaje.ebeaninternal.server.deploy.meta.DeployTableJoin;
@@ -103,7 +104,7 @@ public final class TableJoin {
}
}
public Object readSet(DbReadContext ctx, Object bean, Class<?> type) throws SQLException {
public Object readSet(DbReadContext ctx, EntityBean bean, Class<?> type) throws SQLException {
for (int i = 0, x = properties.length; i < x; i++) {
properties[i].readSet(ctx, bean, type);
}
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.BasicTypeConverter;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
@@ -17,7 +18,7 @@ public class GeneratedCounter implements GeneratedProperty {
/**
* Always returns a 1.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
Integer i = Integer.valueOf(1);
return BasicTypeConverter.convert(i, numberType);
}
@@ -25,7 +26,7 @@ public class GeneratedCounter implements GeneratedProperty {
/**
* Increments the current value by one.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
Number currVal = (Number) prop.getValue(bean);
Integer nextVal = Integer.valueOf(currVal.intValue() + 1);
return BasicTypeConverter.convert(nextVal, numberType);
@@ -38,6 +39,11 @@ public class GeneratedCounter implements GeneratedProperty {
return true;
}
@Override
public boolean includeInAllUpdates() {
return false;
}
/**
* Include this in every insert setting initial counter value to 1.
*/
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
@@ -14,14 +15,14 @@ public class GeneratedCounterInteger implements GeneratedProperty {
/**
* Always returns a 1.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
return Integer.valueOf(1);
}
/**
* Increments the current value by one.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
Integer i = (Integer) prop.getValue(bean);
return Integer.valueOf(i.intValue() + 1);
}
@@ -32,6 +33,11 @@ public class GeneratedCounterInteger implements GeneratedProperty {
public boolean includeInUpdate() {
return true;
}
@Override
public boolean includeInAllUpdates() {
return false;
}
/**
* Include this in every insert setting initial counter value to 1.
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
@@ -14,14 +15,14 @@ public class GeneratedCounterLong implements GeneratedProperty {
/**
* Always returns a 1.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
return Long.valueOf(1);
}
/**
* Increments the current value by one.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
Long i = (Long) prop.getValue(bean);
return Long.valueOf(i.longValue() + 1);
}
@@ -33,6 +34,11 @@ public class GeneratedCounterLong implements GeneratedProperty {
return true;
}
@Override
public boolean includeInAllUpdates() {
return false;
}
/**
* Include this in every insert setting initial counter value to 1.
*/
@@ -2,6 +2,7 @@ package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.util.Date;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
@@ -12,14 +13,14 @@ public class GeneratedInsertDate implements GeneratedProperty {
/**
* Return the current time as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
return new Date(System.currentTimeMillis());
}
/**
* Just returns the beans original insert timestamp value.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
return prop.getValue(bean);
}
@@ -30,6 +31,11 @@ public class GeneratedInsertDate implements GeneratedProperty {
return false;
}
@Override
public boolean includeInAllUpdates() {
return false;
}
/**
* Return true.
*/
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
@@ -10,14 +11,14 @@ public class GeneratedInsertLong implements GeneratedProperty {
/**
* Return the current time as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
return Long.valueOf(System.currentTimeMillis());
}
/**
* Just returns the beans original insert timestamp value.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
return prop.getValue(bean);
}
@@ -28,6 +29,11 @@ public class GeneratedInsertLong implements GeneratedProperty {
return false;
}
@Override
public boolean includeInAllUpdates() {
return false;
}
/**
* Return true.
*/
@@ -2,6 +2,7 @@ package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.sql.Timestamp;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
@@ -12,14 +13,14 @@ public class GeneratedInsertTimestamp implements GeneratedProperty {
/**
* Return the current time as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
return new Timestamp(System.currentTimeMillis());
}
/**
* Just returns the beans original insert timestamp value.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
return prop.getValue(bean);
}
@@ -29,6 +30,11 @@ public class GeneratedInsertTimestamp implements GeneratedProperty {
public boolean includeInUpdate() {
return false;
}
@Override
public boolean includeInAllUpdates() {
return false;
}
/**
* Return true.
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
@@ -11,12 +12,12 @@ public interface GeneratedProperty {
/**
* Get the generated insert value for a specific property of a bean.
*/
public Object getInsertValue(BeanProperty prop, Object bean);
public Object getInsertValue(BeanProperty prop, EntityBean bean);
/**
* Get the generated update value for a specific property of a bean.
*/
public Object getUpdateValue(BeanProperty prop, Object bean);
public Object getUpdateValue(BeanProperty prop, EntityBean bean);
/**
* Return true if this should always be includes in an update statement.
@@ -25,6 +26,12 @@ public interface GeneratedProperty {
* </p>
*/
public boolean includeInUpdate();
/**
* Return true if the property should be included in an update even if
* it is not loaded (ie. Last Updated Timestamp).
*/
public boolean includeInAllUpdates();
/**
* Return true if this should be included in insert statements.
@@ -2,6 +2,7 @@ package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.util.Date;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
@@ -13,14 +14,14 @@ public class GeneratedUpdateDate implements GeneratedProperty {
/**
* Return now as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
return new Date(System.currentTimeMillis());
}
/**
* Return now as a Timestamp.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
return new Date(System.currentTimeMillis());
}
@@ -30,6 +31,11 @@ public class GeneratedUpdateDate implements GeneratedProperty {
public boolean includeInUpdate() {
return true;
}
@Override
public boolean includeInAllUpdates() {
return true;
}
/**
* Include this in every insert.
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
@@ -10,14 +11,14 @@ public class GeneratedUpdateLong implements GeneratedProperty {
/**
* Return now as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
return Long.valueOf(System.currentTimeMillis());
}
/**
* Return now as a Timestamp.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
return Long.valueOf(System.currentTimeMillis());
}
@@ -28,6 +29,11 @@ public class GeneratedUpdateLong implements GeneratedProperty {
return true;
}
@Override
public boolean includeInAllUpdates() {
return true;
}
/**
* Include this in every insert.
*/
@@ -2,6 +2,7 @@ package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.sql.Timestamp;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
@@ -12,14 +13,14 @@ public class GeneratedUpdateTimestamp implements GeneratedProperty {
/**
* Return now as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
return new Timestamp(System.currentTimeMillis());
}
/**
* Return now as a Timestamp.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
return new Timestamp(System.currentTimeMillis());
}
@@ -30,6 +31,11 @@ public class GeneratedUpdateTimestamp implements GeneratedProperty {
return true;
}
@Override
public boolean includeInAllUpdates() {
return true;
}
/**
* Include this in every insert.
*/
@@ -6,6 +6,8 @@ import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
@@ -42,6 +44,11 @@ public interface IdBinder {
*/
public String getIdProperty();
/**
* Return the Id BeanProperty.
*/
public BeanProperty getBeanProperty();
/**
* Find a BeanProperty that is mapped to the database column.
*/
@@ -81,7 +88,7 @@ public interface IdBinder {
/**
* Return the id values for a given bean.
*/
public Object[] getIdValues(Object bean);
public Object[] getIdValues(EntityBean bean);
/**
* Build a string of the logical expressions.
@@ -129,7 +136,7 @@ public interface IdBinder {
* Read the id value from the result set and set it to the bean also returning
* it.
*/
public Object readSet(DbReadContext ctx, Object bean) throws SQLException;
public Object readSet(DbReadContext ctx, EntityBean bean) throws SQLException;
/**
* Ignore the appropriate number of scalar properties for this id.
@@ -152,11 +159,6 @@ public interface IdBinder {
*/
public String getBindIdSql(String baseTableAlias);
/**
* Return the id properties in flat form.
*/
public BeanProperty[] getProperties();
/**
* Cast or convert the Id value if necessary and optionally set it.
* <p>
@@ -168,6 +170,6 @@ public interface IdBinder {
* If the bean is not null, then the value is set to the bean.
* </p>
*/
public Object convertSetId(Object idValue, Object bean);
public Object convertSetId(Object idValue, EntityBean bean);
}
@@ -6,6 +6,7 @@ import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
@@ -21,378 +22,382 @@ import com.avaje.ebeaninternal.server.type.DataBind;
*/
public final class IdBinderEmbedded implements IdBinder {
private final BeanPropertyAssocOne<?> embIdProperty;
private final BeanPropertyAssocOne<?> embIdProperty;
private final boolean idInExpandedForm;
private BeanProperty[] props;
private final boolean idInExpandedForm;
private BeanDescriptor<?> idDesc;
private BeanProperty[] props;
private String idInValueSql;
public IdBinderEmbedded(boolean idInExpandedForm, BeanPropertyAssocOne<?> embIdProperty) {
this.idInExpandedForm = idInExpandedForm;
this.embIdProperty = embIdProperty;
private BeanDescriptor<?> idDesc;
private String idInValueSql;
public IdBinderEmbedded(boolean idInExpandedForm, BeanPropertyAssocOne<?> embIdProperty) {
this.idInExpandedForm = idInExpandedForm;
this.embIdProperty = embIdProperty;
}
public void initialise() {
this.idDesc = embIdProperty.getTargetDescriptor();
this.props = embIdProperty.getProperties();
this.idInValueSql = idInExpandedForm ? idInExpanded() : idInCompressed();
}
private String idInExpanded() {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" and ");
}
sb.append(embIdProperty.getName());
sb.append(".");
sb.append(props[i].getName());
sb.append("=?");
}
sb.append(")");
return sb.toString();
}
private String idInCompressed() {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(",");
}
sb.append("?");
}
sb.append(")");
return sb.toString();
}
@Override
public BeanProperty getBeanProperty() {
return embIdProperty;
}
public String getOrderBy(String pathPrefix, boolean ascending) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(", ");
}
if (pathPrefix != null) {
sb.append(pathPrefix).append(".");
}
sb.append(embIdProperty.getName()).append(".");
sb.append(props[i].getName());
if (!ascending) {
sb.append(" desc");
}
}
return sb.toString();
}
public BeanDescriptor<?> getIdBeanDescriptor() {
return idDesc;
}
public int getPropertyCount() {
return props.length;
}
public String getIdProperty() {
return embIdProperty.getName();
}
public void buildSelectExpressionChain(String prefix, List<String> selectChain) {
prefix = SplitName.add(prefix, embIdProperty.getName());
for (int i = 0; i < props.length; i++) {
props[i].buildSelectExpressionChain(prefix, selectChain);
}
}
public BeanProperty findBeanProperty(String dbColumnName) {
for (int i = 0; i < props.length; i++) {
if (dbColumnName.equalsIgnoreCase(props[i].getDbColumn())) {
return props[i];
}
}
return null;
}
public boolean isComplexId() {
return true;
}
public String getDefaultOrderBy() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(",");
}
sb.append(embIdProperty.getName());
sb.append(".");
sb.append(props[i].getName());
}
public void initialise() {
this.idDesc = embIdProperty.getTargetDescriptor();
this.props = embIdProperty.getProperties();
this.idInValueSql = idInExpandedForm ? idInExpanded() : idInCompressed();
return sb.toString();
}
public BeanProperty[] getProperties() {
return props;
}
public void addIdInBindValue(SpiExpressionRequest request, Object value) {
for (int i = 0; i < props.length; i++) {
request.addBindValue(props[i].getValue((EntityBean) value));
}
}
public String getIdInValueExprDelete(int size) {
if (!idInExpandedForm) {
return getIdInValueExpr(size);
}
private String idInExpanded() {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" and ");
}
sb.append(embIdProperty.getName());
sb.append(".");
sb.append(props[i].getName());
sb.append("=?");
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int j = 0; j < size; j++) {
if (j > 0) {
sb.append(" or ");
}
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" and ");
}
sb.append(")");
return sb.toString();
sb.append(props[i].getDbColumn());
sb.append("=?");
}
sb.append(")");
}
private String idInCompressed() {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(",");
}
sb.append("?");
}
sb.append(")");
sb.append(") ");
return sb.toString();
}
return sb.toString();
public String getIdInValueExpr(int size) {
StringBuilder sb = new StringBuilder();
if (!idInExpandedForm) {
sb.append(" in");
}
public String getOrderBy(String pathPrefix, boolean ascending){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(", ");
}
if (pathPrefix != null){
sb.append(pathPrefix).append(".");
}
sb.append(embIdProperty.getName()).append(".");
sb.append(props[i].getName());
if (!ascending){
sb.append(" desc");
}
}
return sb.toString();
}
public BeanDescriptor<?> getIdBeanDescriptor() {
return idDesc;
}
public int getPropertyCount() {
return props.length;
}
public String getIdProperty() {
return embIdProperty.getName();
}
public void buildSelectExpressionChain(String prefix, List<String> selectChain) {
prefix = SplitName.add(prefix, embIdProperty.getName());
for (int i = 0; i < props.length; i++) {
props[i].buildSelectExpressionChain(prefix, selectChain);
}
}
public BeanProperty findBeanProperty(String dbColumnName) {
for (int i = 0; i < props.length; i++) {
if (dbColumnName.equalsIgnoreCase(props[i].getDbColumn())) {
return props[i];
}
}
return null;
}
public boolean isComplexId() {
return true;
}
public String getDefaultOrderBy() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(",");
}
sb.append(embIdProperty.getName());
sb.append(".");
sb.append(props[i].getName());
}
return sb.toString();
}
public BeanProperty[] getProperties() {
return props;
}
public void addIdInBindValue(SpiExpressionRequest request, Object value) {
for (int i = 0; i < props.length; i++) {
request.addBindValue(props[i].getValue(value));
}
}
public String getIdInValueExprDelete(int size) {
if (!idInExpandedForm){
return getIdInValueExpr(size);
}
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int j = 0; j < size; j++) {
if (j > 0){
sb.append(" or ");
}
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" and ");
}
sb.append(props[i].getDbColumn());
sb.append("=?");
}
sb.append(")");
}
sb.append(") ");
return sb.toString();
}
public String getIdInValueExpr(int size) {
StringBuilder sb = new StringBuilder();
if (!idInExpandedForm){
sb.append(" in");
}
sb.append(" (");
for (int i = 0; i < size; i++) {
if (i > 0){
if (idInExpandedForm) {
sb.append(" or ");
} else {
sb.append(",");
}
}
sb.append(idInValueSql);
}
sb.append(") ");
return sb.toString();
}
public String getIdInValueExpr() {
return idInValueSql;
}
public Object[] getIdValues(Object bean) {
bean = embIdProperty.getValue(bean);
Object[] bindvalues = new Object[props.length];
for (int i = 0; i < props.length; i++) {
bindvalues[i] = props[i].getValue(bean);
}
return bindvalues;
}
public Object[] getBindValues(Object value) {
Object[] bindvalues = new Object[props.length];
for (int i = 0; i < props.length; i++) {
bindvalues[i] = props[i].getValue(value);
}
return bindvalues;
}
public void bindId(DefaultSqlUpdate sqlUpdate, Object value) {
for (int i = 0; i < props.length; i++) {
Object embFieldValue = props[i].getValue(value);
sqlUpdate.addParameter(embFieldValue);
}
}
public void bindId(DataBind dataBind, Object value) throws SQLException {
for (int i = 0; i < props.length; i++) {
Object embFieldValue = props[i].getValue(value);
props[i].bind(dataBind, embFieldValue);
}
}
public Object readData(DataInput dataInput) throws IOException {
Object embId = idDesc.createBean();
boolean notNull = true;
for (int i = 0; i < props.length; i++) {
Object value = props[i].readData(dataInput);
props[i].setValue(embId, value);
if (value == null) {
notNull = false;
}
}
if (notNull) {
return embId;
sb.append(" (");
for (int i = 0; i < size; i++) {
if (i > 0) {
if (idInExpandedForm) {
sb.append(" or ");
} else {
return null;
sb.append(",");
}
}
sb.append(idInValueSql);
}
sb.append(") ");
return sb.toString();
}
public String getIdInValueExpr() {
return idInValueSql;
}
public Object[] getIdValues(EntityBean bean) {
Object val = embIdProperty.getValue(bean);
Object[] bindvalues = new Object[props.length];
for (int i = 0; i < props.length; i++) {
bindvalues[i] = props[i].getValue((EntityBean) val);
}
return bindvalues;
}
public Object[] getBindValues(Object value) {
Object[] bindvalues = new Object[props.length];
for (int i = 0; i < props.length; i++) {
bindvalues[i] = props[i].getValue((EntityBean) value);
}
return bindvalues;
}
public void bindId(DefaultSqlUpdate sqlUpdate, Object value) {
for (int i = 0; i < props.length; i++) {
Object embFieldValue = props[i].getValue((EntityBean) value);
sqlUpdate.addParameter(embFieldValue);
}
}
public void bindId(DataBind dataBind, Object value) throws SQLException {
for (int i = 0; i < props.length; i++) {
Object embFieldValue = props[i].getValue((EntityBean) value);
props[i].bind(dataBind, embFieldValue);
}
}
public Object readData(DataInput dataInput) throws IOException {
EntityBean embId = idDesc.createBean();
boolean notNull = true;
for (int i = 0; i < props.length; i++) {
Object value = props[i].readData(dataInput);
props[i].setValue(embId, value);
if (value == null) {
notNull = false;
}
}
public void writeData(DataOutput dataOutput, Object idValue) throws IOException {
for (int i = 0; i < props.length; i++) {
Object embFieldValue = props[i].getValue(idValue);
props[i].writeData(dataOutput, embFieldValue);
}
if (notNull) {
return embId;
} else {
return null;
}
}
public void writeData(DataOutput dataOutput, Object idValue) throws IOException {
for (int i = 0; i < props.length; i++) {
Object embFieldValue = props[i].getValue((EntityBean) idValue);
props[i].writeData(dataOutput, embFieldValue);
}
}
public void loadIgnore(DbReadContext ctx) {
for (int i = 0; i < props.length; i++) {
props[i].loadIgnore(ctx);
}
}
public Object read(DbReadContext ctx) throws SQLException {
EntityBean embId = idDesc.createBean();
boolean notNull = true;
for (int i = 0; i < props.length; i++) {
Object value = props[i].readSet(ctx, embId, null);
if (value == null) {
notNull = false;
}
}
public void loadIgnore(DbReadContext ctx) {
for (int i = 0; i < props.length; i++) {
props[i].loadIgnore(ctx);
}
if (notNull) {
return embId;
} else {
return null;
}
}
public Object readSet(DbReadContext ctx, EntityBean bean) throws SQLException {
Object embId = read(ctx);
if (embId != null) {
embIdProperty.setValue(bean, embId);
return embId;
} else {
return null;
}
}
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
for (int i = 0; i < props.length; i++) {
props[i].appendSelect(ctx, subQuery);
}
}
public String getAssocIdInExpr(String prefix) {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(",");
}
if (prefix != null) {
sb.append(prefix);
sb.append(".");
}
sb.append(props[i].getName());
}
sb.append(")");
return sb.toString();
}
public String getAssocOneIdExpr(String prefix, String operator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" and ");
}
if (prefix != null) {
sb.append(prefix);
sb.append(".");
}
sb.append(embIdProperty.getName());
sb.append(".");
sb.append(props[i].getName());
sb.append(operator);
}
return sb.toString();
}
public String getBindIdSql(String baseTableAlias) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" and ");
}
if (baseTableAlias != null) {
sb.append(baseTableAlias);
sb.append(".");
}
sb.append(props[i].getDbColumn());
sb.append(" = ? ");
}
return sb.toString();
}
public String getBindIdInSql(String baseTableAlias) {
if (idInExpandedForm) {
return "";
}
public Object read(DbReadContext ctx) throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(",");
}
if (baseTableAlias != null) {
sb.append(baseTableAlias);
sb.append(".");
}
sb.append(props[i].getDbColumn());
}
sb.append(")");
return sb.toString();
}
Object embId = idDesc.createBean();
boolean notNull = true;
public Object convertSetId(Object idValue, EntityBean bean) {
for (int i = 0; i < props.length; i++) {
Object value = props[i].readSet(ctx, embId, null);
if (value == null) {
notNull = false;
}
}
if (notNull) {
return embId;
} else {
return null;
}
// can not cast/convert if it is embedded
if (bean != null) {
// support PropertyChangeSupport
embIdProperty.setValueIntercept(bean, idValue);
}
public Object readSet(DbReadContext ctx, Object bean) throws SQLException {
Object embId = read(ctx);
if (embId != null) {
embIdProperty.setValue(bean, embId);
return embId;
} else {
return null;
}
}
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
for (int i = 0; i < props.length; i++) {
props[i].appendSelect(ctx, subQuery);
}
}
public String getAssocIdInExpr(String prefix) {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(",");
}
if (prefix != null) {
sb.append(prefix);
sb.append(".");
}
sb.append(props[i].getName());
}
sb.append(")");
return sb.toString();
}
public String getAssocOneIdExpr(String prefix, String operator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" and ");
}
if (prefix != null) {
sb.append(prefix);
sb.append(".");
}
sb.append(embIdProperty.getName());
sb.append(".");
sb.append(props[i].getName());
sb.append(operator);
}
return sb.toString();
}
public String getBindIdSql(String baseTableAlias) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" and ");
}
if (baseTableAlias != null) {
sb.append(baseTableAlias);
sb.append(".");
}
sb.append(props[i].getDbColumn());
sb.append(" = ? ");
}
return sb.toString();
}
public String getBindIdInSql(String baseTableAlias) {
if (idInExpandedForm){
return "";
}
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(",");
}
if (baseTableAlias != null){
sb.append(baseTableAlias);
sb.append(".");
}
sb.append(props[i].getDbColumn());
}
sb.append(")");
return sb.toString();
}
public Object convertSetId(Object idValue, Object bean) {
// can not cast/convert if it is embedded
if (bean != null) {
// support PropertyChangeSupport
embIdProperty.setValueIntercept(bean, idValue);
}
return idValue;
}
return idValue;
}
}
@@ -6,6 +6,8 @@ import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
@@ -20,8 +22,6 @@ public final class IdBinderEmpty implements IdBinder {
private static final String bindIdSql = "";
private static final BeanProperty[] properties = new BeanProperty[0];
public IdBinderEmpty() {
}
@@ -41,6 +41,11 @@ public final class IdBinderEmpty implements IdBinder {
return 0;
}
@Override
public BeanProperty getBeanProperty() {
return null;
}
public String getIdProperty() {
return null;
}
@@ -58,10 +63,6 @@ public final class IdBinderEmpty implements IdBinder {
return "";
}
public BeanProperty[] getProperties() {
return properties;
}
public String getBindIdSql(String baseTableAlias) {
return bindIdSql;
}
@@ -90,7 +91,7 @@ public final class IdBinderEmpty implements IdBinder {
return null;
}
public Object[] getIdValues(Object bean) {
public Object[] getIdValues(EntityBean bean) {
return null;
}
@@ -109,7 +110,7 @@ public final class IdBinderEmpty implements IdBinder {
public void loadIgnore(DbReadContext ctx) {
}
public Object readSet(DbReadContext ctx, Object bean) throws SQLException {
public Object readSet(DbReadContext ctx, EntityBean bean) throws SQLException {
return null;
}
@@ -120,7 +121,7 @@ public final class IdBinderEmpty implements IdBinder {
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
}
public Object convertSetId(Object idValue, Object bean) {
public Object convertSetId(Object idValue, EntityBean bean) {
return idValue;
}
@@ -129,7 +130,6 @@ public final class IdBinderEmpty implements IdBinder {
}
public void writeData(DataOutput dataOutput, Object idValue) throws IOException {
}
}
@@ -19,21 +19,17 @@ public class IdBinderFactory {
/**
* Create the IdConvertSet for the given type of Id properties.
*/
public IdBinder createIdBinder(BeanProperty[] uids) {
public IdBinder createIdBinder(BeanProperty id) {
if (uids.length == 0){
if (id == null){
// for report type beans that don't need an id
return EMPTY;
} else if (uids.length == 1){
if (uids[0].isEmbedded()){
return new IdBinderEmbedded(idInExpandedForm, (BeanPropertyAssocOne<?>)uids[0]);
} else {
return new IdBinderSimple(uids[0]);
}
}
if (id.isEmbedded()){
return new IdBinderEmbedded(idInExpandedForm, (BeanPropertyAssocOne<?>)id);
} else {
return new IdBinderMultiple(uids);
return new IdBinderSimple(id);
}
}
@@ -1,399 +0,0 @@
package com.avaje.ebeaninternal.server.deploy.id;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
import com.avaje.ebeaninternal.server.lib.util.MapFromString;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* Bind an Id that is made up of multiple separate properties.
* <p>
* The id passed in for binding is expected to be a map with the key being the
* String name of the property and the value being that properties bind value.
* </p>
*/
public final class IdBinderMultiple implements IdBinder {
private final BeanProperty[] props;
private final String idProperties;
private final String idInValueSql;
public IdBinderMultiple(BeanProperty[] idProps) {
this.props = idProps;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < idProps.length; i++) {
if (i > 0){
sb.append(",");
}
sb.append(idProps[i].getName());
}
idProperties = InternString.intern(sb.toString());
sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0){
sb.append(",");
}
sb.append("?");
}
sb.append(")");
idInValueSql = sb.toString();
}
public void initialise(){
// do nothing
}
public String getOrderBy(String pathPrefix, boolean ascending){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" ");
}
if (pathPrefix != null){
sb.append(pathPrefix).append(".");
}
sb.append(props[i].getName());
if (!ascending){
sb.append(" desc");
}
}
return sb.toString();
}
public void buildSelectExpressionChain(String prefix, List<String> selectChain) {
for (int i = 0; i < props.length; i++) {
props[i].buildSelectExpressionChain(prefix, selectChain);
}
}
public int getPropertyCount() {
return props.length;
}
public String getIdProperty() {
return idProperties;
}
public BeanProperty findBeanProperty(String dbColumnName) {
for (int i = 0; i < props.length; i++) {
if (dbColumnName.equalsIgnoreCase(props[i].getDbColumn())){
return props[i];
}
}
return null;
}
public boolean isComplexId(){
return true;
}
public String getDefaultOrderBy() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0){
sb.append(",");
}
sb.append(props[i].getName());
}
return sb.toString();
}
public BeanProperty[] getProperties() {
return props;
}
public void addIdInBindValue(SpiExpressionRequest request, Object value) {
for (int i = 0; i < props.length; i++) {
request.addBindValue(props[i].getValue(value));
}
}
public String getIdInValueExprDelete(int size) {
return getIdInValueExpr(size);
}
public String getIdInValueExpr(int size) {
StringBuilder sb = new StringBuilder();
sb.append(" in");
sb.append(" (");
sb.append(idInValueSql);
for (int i = 1; i < size; i++) {
sb.append(",").append(idInValueSql);
}
sb.append(") ");
return sb.toString();
}
public String getBindIdInSql(String baseTableAlias) {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(",");
}
if (baseTableAlias != null){
sb.append(baseTableAlias);
sb.append(".");
}
sb.append(props[i].getDbColumn());
}
sb.append(")");
return sb.toString();
}
public Object[] getIdValues(Object bean){
Object[] bindvalues = new Object[props.length];
for (int i = 0; i < props.length; i++) {
bindvalues[i] = props[i].getValue(bean);
}
return bindvalues;
}
@SuppressWarnings("unchecked")
public Object[] getBindValues(Object idValue){
Object[] bindvalues = new Object[props.length];
// concatenated id as a Map
try {
Map<String, ?> uidMap = (Map<String, ?>) idValue;
for (int i = 0; i < props.length; i++) {
Object value = uidMap.get(props[i].getName());
bindvalues[i] = value;
}
return bindvalues;
} catch (ClassCastException e) {
String msg = "Expecting concatinated idValue to be a Map";
throw new PersistenceException(msg, e);
}
}
public Object readData(DataInput dataInput) throws IOException {
LinkedHashMap<String,Object> map = new LinkedHashMap<String, Object>();
boolean notNull = true;
for (int i = 0; i < props.length; i++) {
Object value = props[i].readData(dataInput);
map.put(props[i].getName(), value);
if (value == null) {
notNull = false;
}
}
if (notNull) {
return map;
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public void writeData(DataOutput dataOutput, Object idValue) throws IOException {
Map<String,Object> map = (Map<String,Object>)idValue;
for (int i = 0; i < props.length; i++) {
Object embFieldValue = map.get(props[i].getName());
//Object embFieldValue = props[i].getValue(idValue);
props[i].writeData(dataOutput, embFieldValue);
}
}
public void loadIgnore(DbReadContext ctx) {
for (int i = 0; i < props.length; i++) {
props[i].loadIgnore(ctx);
}
}
public Object readSet(DbReadContext ctx, Object bean) throws SQLException {
LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
boolean notNull = false;
for (int i = 0; i < props.length; i++) {
Object value = props[i].readSet(ctx, bean, null);
if (value != null){
map.put(props[i].getName(), value);
notNull = true;
}
}
if (notNull){
return map;
} else {
return null;
}
}
public Object read(DbReadContext ctx) throws SQLException {
LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
boolean notNull = false;
for (int i = 0; i < props.length; i++) {
Object value = props[i].read(ctx);
if (value != null){
map.put(props[i].getName(), value);
notNull = true;
}
}
if (notNull){
return map;
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public void bindId(DefaultSqlUpdate sqlUpdate, Object idValue) {
// concatenated id as a Map
try {
Map<String, ?> uidMap = (Map<String, ?>) idValue;
for (int i = 0; i < props.length; i++) {
Object value = uidMap.get(props[i].getName());
sqlUpdate.addParameter(value);
}
} catch (ClassCastException e) {
String msg = "Expecting concatinated idValue to be a Map";
throw new PersistenceException(msg, e);
}
}
@SuppressWarnings("unchecked")
public void bindId(DataBind bind, Object idValue) throws SQLException {
// concatenated id as a Map
try {
Map<String, ?> uidMap = (Map<String, ?>) idValue;
for (int i = 0; i < props.length; i++) {
Object value = uidMap.get(props[i].getName());
props[i].bind(bind, value);
}
} catch (ClassCastException e) {
String msg = "Expecting concatinated idValue to be a Map";
throw new PersistenceException(msg, e);
}
}
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
for (int i = 0; i < props.length; i++) {
props[i].appendSelect(ctx, subQuery);
}
}
public String getAssocIdInExpr(String prefix) {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(",");
}
if (prefix != null) {
sb.append(prefix);
sb.append(".");
}
sb.append(props[i].getName());
}
sb.append(")");
return sb.toString();
}
public String getAssocOneIdExpr(String prefix, String operator){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" and ");
}
if (prefix != null){
sb.append(prefix);
sb.append(".");
}
sb.append(props[i].getName());
sb.append(operator);
}
return sb.toString();
}
public String getBindIdSql(String baseTableAlias) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" and ");
}
if (baseTableAlias != null){
sb.append(baseTableAlias);
sb.append(".");
}
sb.append(props[i].getDbColumn());
sb.append(" = ? ");
}
return sb.toString();
}
public Object convertSetId(Object idValue, Object bean) {
// allow Map or String for concatenated id
Map<?,?> mapVal = null;
if (idValue instanceof Map<?,?>) {
mapVal = (Map<?,?>) idValue;
} else {
mapVal = MapFromString.parse(idValue.toString());
}
// Use a new LinkedHashMap to control the order
LinkedHashMap<String,Object> newMap = new LinkedHashMap<String, Object>();
for (int i = 0; i < props.length; i++) {
BeanProperty prop = props[i];
Object value = mapVal.get(prop.getName());
// Convert the property type if required
value = props[i].getScalarType().toBeanType(value);
newMap.put(prop.getName(), value);
if (bean != null) {
// support PropertyChangeSupport
prop.setValueIntercept(bean, value);
}
}
return newMap;
}
}
@@ -6,6 +6,8 @@ import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.core.InternString;
@@ -24,8 +26,6 @@ public final class IdBinderSimple implements IdBinder {
private final String bindIdSql;
private final BeanProperty[] properties;
private final Class<?> expectedType;
@SuppressWarnings("rawtypes")
@@ -35,8 +35,6 @@ public final class IdBinderSimple implements IdBinder {
this.idProperty = idProperty;
this.scalarType = idProperty.getScalarType();
this.expectedType = idProperty.getPropertyType();
this.properties = new BeanProperty[1];
properties[0] = idProperty;
bindIdSql = InternString.intern(idProperty.getDbColumn()+" = ? ");
}
@@ -44,32 +42,37 @@ public final class IdBinderSimple implements IdBinder {
// do nothing
}
public String getOrderBy(String pathPrefix, boolean ascending){
StringBuilder sb = new StringBuilder();
if (pathPrefix != null){
sb.append(pathPrefix).append(".");
}
sb.append(idProperty.getName());
if (!ascending){
sb.append(" desc");
}
return sb.toString();
public String getOrderBy(String pathPrefix, boolean ascending) {
StringBuilder sb = new StringBuilder();
if (pathPrefix != null) {
sb.append(pathPrefix).append(".");
}
sb.append(idProperty.getName());
if (!ascending) {
sb.append(" desc");
}
return sb.toString();
}
public void buildSelectExpressionChain(String prefix, List<String> selectChain) {
public void buildSelectExpressionChain(String prefix, List<String> selectChain) {
idProperty.buildSelectExpressionChain(prefix, selectChain);
}
idProperty.buildSelectExpressionChain(prefix, selectChain);
}
/**
* Returns 1.
*/
public int getPropertyCount() {
return 1;
}
@Override
public BeanProperty getBeanProperty() {
return idProperty;
}
/**
* Returns 1.
*/
public int getPropertyCount() {
return 1;
}
public String getIdProperty() {
public String getIdProperty() {
return idProperty.getName();
}
@@ -87,128 +90,124 @@ public final class IdBinderSimple implements IdBinder {
public String getDefaultOrderBy() {
return idProperty.getName();
}
public BeanProperty[] getProperties() {
return properties;
}
public String getBindIdInSql(String baseTableAlias) {
if (baseTableAlias == null){
return idProperty.getDbColumn();
} else {
return baseTableAlias+"."+idProperty.getDbColumn();
}
}
public String getBindIdInSql(String baseTableAlias) {
if (baseTableAlias == null) {
return idProperty.getDbColumn();
} else {
return baseTableAlias + "." + idProperty.getDbColumn();
}
}
public String getBindIdSql(String baseTableAlias) {
if (baseTableAlias == null){
return bindIdSql;
} else {
return baseTableAlias+"."+bindIdSql;
}
}
public String getBindIdSql(String baseTableAlias) {
if (baseTableAlias == null) {
return bindIdSql;
} else {
return baseTableAlias + "." + bindIdSql;
}
}
public Object[] getIdValues(Object bean){
return new Object[]{idProperty.getValue(bean)};
}
public Object[] getBindValues(Object idValue){
return new Object[]{idValue};
}
public Object[] getIdValues(EntityBean bean) {
return new Object[] { idProperty.getValue(bean) };
}
public String getIdInValueExprDelete(int size) {
return getIdInValueExpr(size);
public Object[] getBindValues(Object idValue) {
return new Object[] { idValue };
}
public String getIdInValueExprDelete(int size) {
return getIdInValueExpr(size);
}
public String getIdInValueExpr(int size) {
StringBuilder sb = new StringBuilder(2 * size + 10);
sb.append(" in");
sb.append(" (?");
for (int i = 1; i < size; i++) {
sb.append(",?");
}
sb.append(") ");
return sb.toString();
}
public void addIdInBindValue(SpiExpressionRequest request, Object value) {
value = convertSetId(value, null);
request.addBindValue(value);
}
public void bindId(DefaultSqlUpdate sqlUpdate, Object value) {
sqlUpdate.addParameter(value);
}
public void bindId(DataBind dataBind, Object value) throws SQLException {
if (!value.getClass().equals(expectedType)) {
value = scalarType.toBeanType(value);
}
idProperty.bind(dataBind, value);
}
public void writeData(DataOutput os, Object value) throws IOException {
idProperty.writeData(os, value);
}
public Object readData(DataInput is) throws IOException {
return idProperty.readData(is);
}
public void loadIgnore(DbReadContext ctx) {
idProperty.loadIgnore(ctx);
}
public Object readSet(DbReadContext ctx, EntityBean bean) throws SQLException {
Object id = idProperty.read(ctx);
if (id != null) {
idProperty.setValue(bean, id);
}
return id;
}
public Object read(DbReadContext ctx) throws SQLException {
return idProperty.read(ctx);
}
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
idProperty.appendSelect(ctx, subQuery);
}
public String getAssocOneIdExpr(String prefix, String operator) {
StringBuilder sb = new StringBuilder();
if (prefix != null) {
sb.append(prefix);
sb.append(".");
}
sb.append(idProperty.getName());
sb.append(operator);
return sb.toString();
}
public String getAssocIdInExpr(String prefix) {
StringBuilder sb = new StringBuilder();
if (prefix != null) {
sb.append(prefix);
sb.append(".");
}
sb.append(idProperty.getName());
return sb.toString();
}
public Object convertSetId(Object idValue, EntityBean bean) {
if (!idValue.getClass().equals(expectedType)) {
idValue = scalarType.toBeanType(idValue);
}
public String getIdInValueExpr(int size) {
StringBuilder sb = new StringBuilder(2*size+10);
sb.append(" in");
sb.append(" (?");
for (int i = 1; i < size; i++) {
sb.append(",?");
}
sb.append(") ");
return sb.toString();
if (bean != null) {
// support PropertyChangeSupport
idProperty.setValueIntercept(bean, idValue);
}
public void addIdInBindValue(SpiExpressionRequest request, Object value) {
value = convertSetId(value, null);
request.addBindValue(value);
}
public void bindId(DefaultSqlUpdate sqlUpdate, Object value) {
sqlUpdate.addParameter(value);
}
public void bindId(DataBind dataBind, Object value) throws SQLException {
if( !value.getClass().equals(expectedType) ){
value = scalarType.toBeanType(value);
}
idProperty.bind(dataBind, value);
}
public void writeData(DataOutput os, Object value) throws IOException {
idProperty.writeData(os, value);
}
public Object readData(DataInput is) throws IOException {
return idProperty.readData(is);
}
public void loadIgnore(DbReadContext ctx) {
idProperty.loadIgnore(ctx);
}
public Object readSet(DbReadContext ctx, Object bean) throws SQLException {
Object id = idProperty.read(ctx);
if (id != null){
idProperty.setValue(bean, id);
}
return id;
}
public Object read(DbReadContext ctx) throws SQLException {
return idProperty.read(ctx);
}
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
idProperty.appendSelect(ctx, subQuery);
}
public String getAssocOneIdExpr(String prefix, String operator){
StringBuilder sb = new StringBuilder();
if (prefix != null){
sb.append(prefix);
sb.append(".");
}
sb.append(idProperty.getName());
sb.append(operator);
return sb.toString();
}
public String getAssocIdInExpr(String prefix) {
StringBuilder sb = new StringBuilder();
if (prefix != null) {
sb.append(prefix);
sb.append(".");
}
sb.append(idProperty.getName());
return sb.toString();
}
public Object convertSetId(Object idValue, Object bean) {
if (!idValue.getClass().equals(expectedType)){
idValue = scalarType.toBeanType(idValue);
}
if (bean != null) {
// support PropertyChangeSupport
idProperty.setValueIntercept(bean, idValue);
}
return idValue;
}
return idValue;
}
}
@@ -2,6 +2,7 @@ package com.avaje.ebeaninternal.server.deploy.id;
import java.sql.SQLException;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
import com.avaje.ebeaninternal.server.deploy.IntersectionRow;
@@ -48,22 +49,17 @@ public interface ImportedId {
/**
* Append to the DML statement to the where clause.
*/
public void dmlWhere(GenerateDmlRequest request, Object bean);
/**
* Return true if the id value has changed.
*/
public boolean hasChanged(Object bean, Object oldValues);
public void dmlWhere(GenerateDmlRequest request, EntityBean bean);
/**
* Bind the value from the bean.
*/
public Object bind(BindableRequest request, Object bean, boolean bindNull) throws SQLException;
public Object bind(BindableRequest request, EntityBean bean) throws SQLException;
/**
* For inserting into ManyToMany intersection.
*/
public void buildImport(IntersectionRow row, Object other);
public void buildImport(IntersectionRow row, EntityBean other);
/**
* Used to derive a missing concatenated key from multiple imported keys.
@@ -4,6 +4,7 @@ import java.sql.SQLException;
import javax.persistence.PersistenceException;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanFkeyProperty;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssoc;
@@ -68,7 +69,7 @@ public class ImportedIdEmbedded implements ImportedId {
}
}
public void dmlWhere(GenerateDmlRequest request, Object bean){
public void dmlWhere(GenerateDmlRequest request, EntityBean bean){
Object embeddedId = null;
if (bean != null) {
@@ -82,10 +83,10 @@ public class ImportedIdEmbedded implements ImportedId {
}
}
} else {
EntityBean embedded = (EntityBean)embeddedId;
for (int i = 0; i < imported.length; i++) {
if (imported[i].owner.isDbUpdatable()) {
Object value = imported[i].foreignProperty.getValue(embeddedId);
Object value = imported[i].foreignProperty.getValue(embedded);
if (value == null){
request.appendColumnIsNull(imported[i].localDbColumn);
} else {
@@ -96,14 +97,7 @@ public class ImportedIdEmbedded implements ImportedId {
}
}
public boolean hasChanged(Object bean, Object oldValues) {
Object id = foreignAssocOne.getValue(bean);
Object oldId = foreignAssocOne.getValue(oldValues);
return !ValueUtil.areEqual(id, oldId);
}
public Object bind(BindableRequest request, Object bean, boolean bindNull) throws SQLException {
public Object bind(BindableRequest request, EntityBean bean) throws SQLException {
Object embeddedId = null;
@@ -114,15 +108,16 @@ public class ImportedIdEmbedded implements ImportedId {
if (embeddedId == null){
for (int i = 0; i < imported.length; i++) {
if (imported[i].owner.isUpdateable()) {
request.bind(null, imported[i].foreignProperty, imported[i].localDbColumn, true);
request.bind(null, imported[i].foreignProperty, imported[i].localDbColumn);
}
}
} else {
EntityBean embedded = (EntityBean)embeddedId;
for (int i = 0; i < imported.length; i++) {
if (imported[i].owner.isUpdateable()) {
Object scalarValue = imported[i].foreignProperty.getValue(embeddedId);
request.bind(scalarValue, imported[i].foreignProperty, imported[i].localDbColumn, true);
Object scalarValue = imported[i].foreignProperty.getValue(embedded);
request.bind(scalarValue, imported[i].foreignProperty, imported[i].localDbColumn);
}
}
}
@@ -130,9 +125,9 @@ public class ImportedIdEmbedded implements ImportedId {
return null;
}
public void buildImport(IntersectionRow row, Object other){
public void buildImport(IntersectionRow row, EntityBean other){
Object embeddedId = foreignAssocOne.getValue(other);
EntityBean embeddedId = (EntityBean)foreignAssocOne.getValue(other);
if (embeddedId == null){
String msg = "Foreign Key value null?";
throw new PersistenceException(msg);
@@ -2,13 +2,13 @@ package com.avaje.ebeaninternal.server.deploy.id;
import java.sql.SQLException;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssoc;
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
import com.avaje.ebeaninternal.server.deploy.IntersectionRow;
import com.avaje.ebeaninternal.server.persist.dml.GenerateDmlRequest;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableRequest;
import com.avaje.ebeaninternal.util.ValueUtil;
/**
* Imported concatenated id that is not embedded.
@@ -55,7 +55,7 @@ public class ImportedIdMultiple implements ImportedId {
}
}
public void dmlWhere(GenerateDmlRequest request, Object bean){
public void dmlWhere(GenerateDmlRequest request, EntityBean bean){
if (bean == null){
for (int i = 0; i < imported.length; i++) {
request.appendColumnIsNull(imported[i].localDbColumn);
@@ -72,32 +72,19 @@ public class ImportedIdMultiple implements ImportedId {
}
}
public boolean hasChanged(Object bean, Object oldValues) {
for (int i = 0; i < imported.length; i++) {
Object id = imported[i].foreignProperty.getValue(bean);
Object oldId = imported[i].foreignProperty.getValue(oldValues);
if (!ValueUtil.areEqual(id, oldId)) {
return true;
}
}
return false;
}
public Object bind(BindableRequest request, Object bean, boolean bindNull) throws SQLException {
public Object bind(BindableRequest request, EntityBean bean) throws SQLException {
for (int i = 0; i < imported.length; i++) {
if (imported[i].owner.isUpdateable()) {
Object scalarValue = imported[i].foreignProperty.getValue(bean);
request.bind(scalarValue, imported[i].foreignProperty, imported[i].localDbColumn, true);
request.bind(scalarValue, imported[i].foreignProperty, imported[i].localDbColumn);
}
}
// hmmm, not worrying about this just yet
return null;
}
public void buildImport(IntersectionRow row, Object other){
public void buildImport(IntersectionRow row, EntityBean other){
for (int i = 0; i < imported.length; i++) {
Object scalarValue = imported[i].foreignProperty.getValue(other);
@@ -7,6 +7,7 @@ import java.util.List;
import javax.persistence.PersistenceException;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.BeanFkeyProperty;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
@@ -15,7 +16,6 @@ import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
import com.avaje.ebeaninternal.server.deploy.IntersectionRow;
import com.avaje.ebeaninternal.server.persist.dml.GenerateDmlRequest;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableRequest;
import com.avaje.ebeaninternal.util.ValueUtil;
/**
* Single scalar imported id.
@@ -90,11 +90,11 @@ public final class ImportedIdSimple implements ImportedId, Comparable<ImportedId
return localDbColumn;
}
private Object getIdValue(Object bean) {
return foreignProperty.getValueWithInheritance(bean);
}
private Object getIdValue(EntityBean bean) {
return foreignProperty.getValue(bean);
}
public void buildImport(IntersectionRow row, Object other){
public void buildImport(IntersectionRow row, EntityBean other){
Object value = getIdValue(other);
if (value == null){
@@ -114,7 +114,7 @@ public final class ImportedIdSimple implements ImportedId, Comparable<ImportedId
request.appendColumn(localDbColumn);
}
public void dmlWhere(GenerateDmlRequest request, Object bean){
public void dmlWhere(GenerateDmlRequest request, EntityBean bean){
if (owner.isDbUpdatable()){
Object value = null;
@@ -129,25 +129,13 @@ public final class ImportedIdSimple implements ImportedId, Comparable<ImportedId
}
}
public boolean hasChanged(Object bean, Object oldValues) {
Object id = getIdValue(bean);
if (oldValues != null){
Object oldId = getIdValue(oldValues);
return !ValueUtil.areEqual(id, oldId);
}
return true;
}
public Object bind(BindableRequest request, Object bean, boolean bindNull) throws SQLException {
public Object bind(BindableRequest request, EntityBean bean) throws SQLException {
Object value = null;
if (bean != null){
value = getIdValue(bean);
}
request.bind(value, foreignProperty, localDbColumn, bindNull);
request.bind(value, foreignProperty, localDbColumn);
return value;
}
@@ -62,11 +62,6 @@ public class DeployBeanDescriptor<T> {
*/
private LinkedHashMap<String, DeployBeanProperty> propMap = new LinkedHashMap<String, DeployBeanProperty>();
/**
* The type of bean this describes.
*/
private final Class<T> beanType;
private EntityType entityType;
private final Map<String, DeployNamedQuery> namedQueries = new LinkedHashMap<String, DeployNamedQuery>();
@@ -104,7 +99,7 @@ public class DeployBeanDescriptor<T> {
/**
* The concurrency mode for beans of this type.
*/
private ConcurrencyMode concurrencyMode = ConcurrencyMode.ALL;
private ConcurrencyMode concurrencyMode;
private boolean updateChangesOnly;
@@ -131,11 +126,12 @@ public class DeployBeanDescriptor<T> {
* faster than reflection at this stage.
*/
private BeanReflect beanReflect;
private String[] properties;
/**
* The EntityBean type used to create new EntityBeans.
*/
private Class<?> factoryType;
private Class<T> beanType;
private List<BeanPersistController> persistControllers = new ArrayList<BeanPersistController>();
private List<BeanPersistListener<T>> persistListeners = new ArrayList<BeanPersistListener<T>>();
@@ -298,6 +294,14 @@ public class DeployBeanDescriptor<T> {
return namedUpdates;
}
public String[] getProperties() {
return properties;
}
public void setProperties(String[] props) {
this.properties = props;
}
public BeanReflect getBeanReflect() {
return beanReflect;
}
@@ -309,23 +313,6 @@ public class DeployBeanDescriptor<T> {
return beanType;
}
/**
* Return the class type this BeanDescriptor describes.
*/
public Class<?> getFactoryType() {
return factoryType;
}
/**
* Set the class used to create new EntityBean instances.
* <p>
* Normally this would be a subclass dynamically generated for this bean.
* </p>
*/
public void setFactoryType(Class<?> factoryType) {
this.factoryType = factoryType;
}
/**
* Set the BeanReflect used to create new instances of an EntityBean. This
* could use reflection or code generation to do this.
@@ -350,7 +337,7 @@ public class DeployBeanDescriptor<T> {
}
/**
* Return the reference options.
* Return the cache options.
*/
public CacheOptions getCacheOptions() {
return cacheOptions;
@@ -198,6 +198,8 @@ public class DeployBeanProperty {
*/
private Method writeMethod;
private int propertyIndex;
private BeanReflectGetter getter;
private BeanReflectSetter setter;
@@ -410,6 +412,14 @@ public class DeployBeanProperty {
this.scalarType = scalarType;
}
public int getPropertyIndex() {
return propertyIndex;
}
public void setPropertyIndex(int propertyIndex) {
this.propertyIndex = propertyIndex;
}
public BeanReflectGetter getGetter() {
return getter;
}
@@ -5,6 +5,9 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.bean.BeanCollection.ModifyListenMode;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptorMap;
@@ -20,347 +23,344 @@ import com.avaje.ebeaninternal.server.deploy.TableJoin;
*/
public class DeployBeanPropertyLists {
private BeanProperty derivedFirstVersionProp;
private static final Logger logger = LoggerFactory.getLogger(DeployBeanPropertyLists.class);
private final BeanDescriptor<?> desc;
private BeanProperty versionProperty;
private final LinkedHashMap<String, BeanProperty> propertyMap;
private final BeanDescriptor<?> desc;
private final ArrayList<BeanProperty> ids = new ArrayList<BeanProperty>();
private final LinkedHashMap<String, BeanProperty> propertyMap;
private final ArrayList<BeanProperty> version = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> ids = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> local = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> local = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> manys = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> nonManys = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> manys = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> nonManys = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> ones = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> ones = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> onesExported = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> onesExported = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> onesImported = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> onesImported = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> embedded = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> embedded = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> baseScalar = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> baseScalar = new ArrayList<BeanProperty>();
private final ArrayList<BeanPropertyCompound> baseCompound = new ArrayList<BeanPropertyCompound>();
private final ArrayList<BeanPropertyCompound> baseCompound = new ArrayList<BeanPropertyCompound>();
private final ArrayList<BeanProperty> transients = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> transients = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> nonTransients = new ArrayList<BeanProperty>();
private final ArrayList<BeanProperty> nonTransients = new ArrayList<BeanProperty>();
private final TableJoin[] tableJoins;
private final TableJoin[] tableJoins;
private final BeanPropertyAssocOne<?> unidirectional;
private final BeanPropertyAssocOne<?> unidirectional;
@SuppressWarnings({ "unchecked", "rawtypes" })
public DeployBeanPropertyLists(BeanDescriptorMap owner, BeanDescriptor<?> desc, DeployBeanDescriptor<?> deploy) {
this.desc = desc;
@SuppressWarnings({ "unchecked", "rawtypes" })
public DeployBeanPropertyLists(BeanDescriptorMap owner, BeanDescriptor<?> desc, DeployBeanDescriptor<?> deploy) {
this.desc = desc;
DeployBeanPropertyAssocOne<?> deployUnidirectional = deploy.getUnidirectional();
if (deployUnidirectional == null) {
unidirectional = null;
DeployBeanPropertyAssocOne<?> deployUnidirectional = deploy.getUnidirectional();
if (deployUnidirectional == null) {
unidirectional = null;
} else {
unidirectional = new BeanPropertyAssocOne(owner, desc, deployUnidirectional);
}
this.propertyMap = new LinkedHashMap<String, BeanProperty>();
Iterator<DeployBeanProperty> deployIt = deploy.propertiesAll();
while (deployIt.hasNext()) {
DeployBeanProperty deployProp = deployIt.next();
BeanProperty beanProp = createBeanProperty(owner, deployProp);
propertyMap.put(beanProp.getName(), beanProp);
}
Iterator<BeanProperty> it = propertyMap.values().iterator();
int order = 0;
while (it.hasNext()) {
BeanProperty prop = it.next();
prop.setDeployOrder(order++);
allocateToList(prop);
}
List<DeployTableJoin> deployTableJoins = deploy.getTableJoins();
tableJoins = new TableJoin[deployTableJoins.size()];
for (int i = 0; i < deployTableJoins.size(); i++) {
tableJoins[i] = new TableJoin(deployTableJoins.get(i), propertyMap);
}
}
/**
* Return the unidirectional.
*/
public BeanPropertyAssocOne<?> getUnidirectional() {
return unidirectional;
}
/**
* Allocate the property to a list.
*/
private void allocateToList(BeanProperty prop) {
if (prop.isTransient()) {
transients.add(prop);
return;
}
if (prop.isId()) {
ids.add(prop);
return;
} else {
nonTransients.add(prop);
}
if (desc.getInheritInfo() != null && prop.isLocal()) {
local.add(prop);
}
if (prop instanceof BeanPropertyAssocMany<?>) {
manys.add(prop);
} else {
nonManys.add(prop);
if (prop instanceof BeanPropertyAssocOne<?>) {
if (prop.isEmbedded()) {
embedded.add(prop);
} else {
unidirectional = new BeanPropertyAssocOne(owner, desc, deployUnidirectional);
ones.add(prop);
BeanPropertyAssocOne<?> assocOne = (BeanPropertyAssocOne<?>) prop;
if (assocOne.isOneToOneExported()) {
onesExported.add(prop);
} else {
onesImported.add(prop);
}
}
this.propertyMap = new LinkedHashMap<String, BeanProperty>();
Iterator<DeployBeanProperty> deployIt = deploy.propertiesAll();
while (deployIt.hasNext()) {
DeployBeanProperty deployProp = deployIt.next();
BeanProperty beanProp = createBeanProperty(owner, deployProp);
propertyMap.put(beanProp.getName(), beanProp);
} else {
// its a "base" property...
if (prop.isVersion()) {
if (versionProperty == null) {
versionProperty = prop;
} else {
logger.warn("Multiple @Version properties - property " + prop.getFullBeanName()
+ " not treated as a version property");
}
}
Iterator<BeanProperty> it = propertyMap.values().iterator();
int order = 0;
while (it.hasNext()) {
BeanProperty prop = it.next();
prop.setDeployOrder(order++);
allocateToList(prop);
}
List<DeployTableJoin> deployTableJoins = deploy.getTableJoins();
tableJoins = new TableJoin[deployTableJoins.size()];
for (int i = 0; i < deployTableJoins.size(); i++) {
tableJoins[i] = new TableJoin(deployTableJoins.get(i), propertyMap);
}
}
/**
* Return the unidirectional.
*/
public BeanPropertyAssocOne<?> getUnidirectional() {
return unidirectional;
}
/**
* Allocate the property to a list.
*/
private void allocateToList(BeanProperty prop) {
if (prop.isTransient()) {
transients.add(prop);
return;
}
if (prop.isId()) {
ids.add(prop);
return;
if (prop instanceof BeanPropertyCompound) {
baseCompound.add((BeanPropertyCompound) prop);
} else {
nonTransients.add(prop);
baseScalar.add(prop);
}
}
}
}
if (desc.getInheritInfo() != null && prop.isLocal()) {
local.add(prop);
public LinkedHashMap<String, BeanProperty> getPropertyMap() {
return propertyMap;
}
public TableJoin[] getTableJoin() {
return tableJoins;
}
/**
* Return the base scalar properties (excludes Id and secondary table
* properties).
*/
public BeanProperty[] getBaseScalar() {
return (BeanProperty[]) baseScalar.toArray(new BeanProperty[baseScalar.size()]);
}
public BeanPropertyCompound[] getBaseCompound() {
return (BeanPropertyCompound[]) baseCompound.toArray(new BeanPropertyCompound[baseCompound.size()]);
}
public BeanProperty getId() {
if (ids.size() > 1) {
String msg = "Ebean does not support multiple @Id properties. You need to convert to using an @EmbeddedId."
+" Please email the ebean google group if you need further clarification.";
throw new IllegalStateException(msg);
}
if (ids.isEmpty()) {
return null;
}
return ids.get(0);
}
public BeanProperty[] getNonTransients() {
return (BeanProperty[]) nonTransients.toArray(new BeanProperty[nonTransients.size()]);
}
public BeanProperty[] getTransients() {
return (BeanProperty[]) transients.toArray(new BeanProperty[transients.size()]);
}
public BeanProperty getVersionProperty() {
return versionProperty;
}
public BeanProperty[] getLocal() {
return (BeanProperty[]) local.toArray(new BeanProperty[local.size()]);
}
public BeanPropertyAssocOne<?>[] getEmbedded() {
return (BeanPropertyAssocOne[]) embedded.toArray(new BeanPropertyAssocOne[embedded.size()]);
}
public BeanPropertyAssocOne<?>[] getOneExported() {
return (BeanPropertyAssocOne[]) onesExported.toArray(new BeanPropertyAssocOne[onesExported.size()]);
}
public BeanPropertyAssocOne<?>[] getOneImported() {
return (BeanPropertyAssocOne[]) onesImported.toArray(new BeanPropertyAssocOne[onesImported.size()]);
}
public BeanPropertyAssocOne<?>[] getOnes() {
return (BeanPropertyAssocOne[]) ones.toArray(new BeanPropertyAssocOne[ones.size()]);
}
public BeanPropertyAssocOne<?>[] getOneExportedSave() {
return getOne(false, Mode.Save);
}
public BeanPropertyAssocOne<?>[] getOneExportedDelete() {
return getOne(false, Mode.Delete);
}
public BeanPropertyAssocOne<?>[] getOneImportedSave() {
return getOne(true, Mode.Save);
}
public BeanPropertyAssocOne<?>[] getOneImportedDelete() {
return getOne(true, Mode.Delete);
}
public BeanProperty[] getNonMany() {
return (BeanProperty[]) nonManys.toArray(new BeanProperty[nonManys.size()]);
}
public BeanPropertyAssocMany<?>[] getMany() {
return (BeanPropertyAssocMany[]) manys.toArray(new BeanPropertyAssocMany[manys.size()]);
}
public BeanPropertyAssocMany<?>[] getManySave() {
return getMany(Mode.Save);
}
public BeanPropertyAssocMany<?>[] getManyDelete() {
return getMany(Mode.Delete);
}
public BeanPropertyAssocMany<?>[] getManyToMany() {
return getMany2Many();
}
/**
* Mode used to determine which BeanPropertyAssoc to include.
*/
private enum Mode {
Save, Delete, Validate;
}
private BeanPropertyAssocOne<?>[] getOne(boolean imported, Mode mode) {
ArrayList<BeanPropertyAssocOne<?>> list = new ArrayList<BeanPropertyAssocOne<?>>();
for (int i = 0; i < ones.size(); i++) {
BeanPropertyAssocOne<?> prop = (BeanPropertyAssocOne<?>) ones.get(i);
if (imported != prop.isOneToOneExported()) {
switch (mode) {
case Save:
if (prop.getCascadeInfo().isSave()) {
list.add(prop);
}
break;
case Delete:
if (prop.getCascadeInfo().isDelete()) {
list.add(prop);
}
break;
case Validate:
if (prop.getCascadeInfo().isValidate()) {
list.add(prop);
}
break;
default:
break;
}
}
}
if (prop instanceof BeanPropertyAssocMany<?>) {
manys.add(prop);
return (BeanPropertyAssocOne[]) list.toArray(new BeanPropertyAssocOne[list.size()]);
}
} else {
nonManys.add(prop);
if (prop instanceof BeanPropertyAssocOne<?>) {
if (prop.isEmbedded()) {
embedded.add(prop);
} else {
ones.add(prop);
BeanPropertyAssocOne<?> assocOne = (BeanPropertyAssocOne<?>) prop;
if (assocOne.isOneToOneExported()) {
onesExported.add(prop);
} else {
onesImported.add(prop);
}
}
} else {
// its a "base" property...
if (prop.isVersion()) {
version.add(prop);
if (derivedFirstVersionProp == null) {
derivedFirstVersionProp = prop;
}
}
if (prop instanceof BeanPropertyCompound) {
baseCompound.add((BeanPropertyCompound) prop);
} else {
baseScalar.add(prop);
}
}
private BeanPropertyAssocMany<?>[] getMany2Many() {
ArrayList<BeanPropertyAssocMany<?>> list = new ArrayList<BeanPropertyAssocMany<?>>();
for (int i = 0; i < manys.size(); i++) {
BeanPropertyAssocMany<?> prop = (BeanPropertyAssocMany<?>) manys.get(i);
if (prop.isManyToMany()) {
list.add(prop);
}
}
return (BeanPropertyAssocMany[]) list.toArray(new BeanPropertyAssocMany[list.size()]);
}
private BeanPropertyAssocMany<?>[] getMany(Mode mode) {
ArrayList<BeanPropertyAssocMany<?>> list = new ArrayList<BeanPropertyAssocMany<?>>();
for (int i = 0; i < manys.size(); i++) {
BeanPropertyAssocMany<?> prop = (BeanPropertyAssocMany<?>) manys.get(i);
switch (mode) {
case Save:
if (prop.getCascadeInfo().isSave() || prop.isManyToMany()
|| ModifyListenMode.REMOVALS.equals(prop.getModifyListenMode())) {
// Note ManyToMany always included as we always 'save'
// the relationship via insert/delete of intersection table
// REMOVALS means including PrivateOwned relationships
list.add(prop);
}
break;
case Delete:
if (prop.getCascadeInfo().isDelete() || ModifyListenMode.REMOVALS.equals(prop.getModifyListenMode())) {
// REMOVALS means including PrivateOwned relationships
list.add(prop);
}
break;
case Validate:
if (prop.getCascadeInfo().isValidate()) {
list.add(prop);
}
break;
default:
break;
}
}
public BeanProperty getFirstVersion() {
return derivedFirstVersionProp;
}
return (BeanPropertyAssocMany[]) list.toArray(new BeanPropertyAssocMany[list.size()]);
}
public LinkedHashMap<String, BeanProperty> getPropertyMap() {
return propertyMap;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private BeanProperty createBeanProperty(BeanDescriptorMap owner, DeployBeanProperty deployProp) {
public TableJoin[] getTableJoin() {
return tableJoins;
}
/**
* Return the base scalar properties (excludes Id and secondary table
* properties).
*/
public BeanProperty[] getBaseScalar() {
return (BeanProperty[]) baseScalar.toArray(new BeanProperty[baseScalar.size()]);
}
public BeanPropertyCompound[] getBaseCompound() {
return (BeanPropertyCompound[]) baseCompound.toArray(new BeanPropertyCompound[baseCompound.size()]);
if (deployProp instanceof DeployBeanPropertyAssocOne) {
return new BeanPropertyAssocOne(owner, desc, (DeployBeanPropertyAssocOne) deployProp);
}
public BeanProperty getNaturalKey() {
String naturalKey = desc.getCacheOptions().getNaturalKey();
if (naturalKey != null){
return propertyMap.get(naturalKey);
}
return null;
}
public BeanProperty[] getId() {
return (BeanProperty[]) ids.toArray(new BeanProperty[ids.size()]);
}
public BeanProperty[] getNonTransients() {
return (BeanProperty[]) nonTransients.toArray(new BeanProperty[nonTransients.size()]);
}
public BeanProperty[] getTransients() {
return (BeanProperty[]) transients.toArray(new BeanProperty[transients.size()]);
}
public BeanProperty[] getVersion() {
return (BeanProperty[]) version.toArray(new BeanProperty[version.size()]);
}
public BeanProperty[] getLocal() {
return (BeanProperty[]) local.toArray(new BeanProperty[local.size()]);
}
public BeanPropertyAssocOne<?>[] getEmbedded() {
return (BeanPropertyAssocOne[]) embedded.toArray(new BeanPropertyAssocOne[embedded.size()]);
}
public BeanPropertyAssocOne<?>[] getOneExported() {
return (BeanPropertyAssocOne[]) onesExported.toArray(new BeanPropertyAssocOne[onesExported.size()]);
}
public BeanPropertyAssocOne<?>[] getOneImported() {
return (BeanPropertyAssocOne[]) onesImported.toArray(new BeanPropertyAssocOne[onesImported.size()]);
}
public BeanPropertyAssocOne<?>[] getOnes() {
return (BeanPropertyAssocOne[]) ones.toArray(new BeanPropertyAssocOne[ones.size()]);
}
public BeanPropertyAssocOne<?>[] getOneExportedSave() {
return getOne(false, Mode.Save);
}
public BeanPropertyAssocOne<?>[] getOneExportedDelete() {
return getOne(false, Mode.Delete);
}
public BeanPropertyAssocOne<?>[] getOneImportedSave() {
return getOne(true, Mode.Save);
}
public BeanPropertyAssocOne<?>[] getOneImportedDelete() {
return getOne(true, Mode.Delete);
}
public BeanProperty[] getNonMany() {
return (BeanProperty[]) nonManys.toArray(new BeanProperty[nonManys.size()]);
if (deployProp instanceof DeployBeanPropertySimpleCollection<?>) {
return new BeanPropertySimpleCollection(owner, desc, (DeployBeanPropertySimpleCollection) deployProp);
}
public BeanPropertyAssocMany<?>[] getMany() {
return (BeanPropertyAssocMany[]) manys.toArray(new BeanPropertyAssocMany[manys.size()]);
if (deployProp instanceof DeployBeanPropertyAssocMany) {
return new BeanPropertyAssocMany(owner, desc, (DeployBeanPropertyAssocMany) deployProp);
}
if (deployProp instanceof DeployBeanPropertyCompound) {
return new BeanPropertyCompound(owner, desc, (DeployBeanPropertyCompound) deployProp);
}
public BeanPropertyAssocMany<?>[] getManySave() {
return getMany(Mode.Save);
}
public BeanPropertyAssocMany<?>[] getManyDelete() {
return getMany(Mode.Delete);
}
public BeanPropertyAssocMany<?>[] getManyToMany() {
return getMany2Many();
}
/**
* Mode used to determine which BeanPropertyAssoc to include.
*/
private enum Mode {
Save, Delete, Validate;
}
private BeanPropertyAssocOne<?>[] getOne(boolean imported, Mode mode) {
ArrayList<BeanPropertyAssocOne<?>> list = new ArrayList<BeanPropertyAssocOne<?>>();
for (int i = 0; i < ones.size(); i++) {
BeanPropertyAssocOne<?> prop = (BeanPropertyAssocOne<?>) ones.get(i);
if (imported != prop.isOneToOneExported()) {
switch (mode) {
case Save:
if (prop.getCascadeInfo().isSave()) {
list.add(prop);
}
break;
case Delete:
if (prop.getCascadeInfo().isDelete()) {
list.add(prop);
}
break;
case Validate:
if (prop.getCascadeInfo().isValidate()) {
list.add(prop);
}
break;
default:
break;
}
}
}
return (BeanPropertyAssocOne[]) list.toArray(new BeanPropertyAssocOne[list.size()]);
}
private BeanPropertyAssocMany<?>[] getMany2Many() {
ArrayList<BeanPropertyAssocMany<?>> list = new ArrayList<BeanPropertyAssocMany<?>>();
for (int i = 0; i < manys.size(); i++) {
BeanPropertyAssocMany<?> prop = (BeanPropertyAssocMany<?>) manys.get(i);
if (prop.isManyToMany()) {
list.add(prop);
}
}
return (BeanPropertyAssocMany[]) list.toArray(new BeanPropertyAssocMany[list.size()]);
}
private BeanPropertyAssocMany<?>[] getMany(Mode mode) {
ArrayList<BeanPropertyAssocMany<?>> list = new ArrayList<BeanPropertyAssocMany<?>>();
for (int i = 0; i < manys.size(); i++) {
BeanPropertyAssocMany<?> prop = (BeanPropertyAssocMany<?>) manys.get(i);
switch (mode) {
case Save:
if (prop.getCascadeInfo().isSave() || prop.isManyToMany()
|| ModifyListenMode.REMOVALS.equals(prop.getModifyListenMode())) {
// Note ManyToMany always included as we always 'save'
// the relationship via insert/delete of intersection table
// REMOVALS means including PrivateOwned relationships
list.add(prop);
}
break;
case Delete:
if (prop.getCascadeInfo().isDelete()
|| ModifyListenMode.REMOVALS.equals(prop.getModifyListenMode())) {
// REMOVALS means including PrivateOwned relationships
list.add(prop);
}
break;
case Validate:
if (prop.getCascadeInfo().isValidate()) {
list.add(prop);
}
break;
default:
break;
}
}
return (BeanPropertyAssocMany[]) list.toArray(new BeanPropertyAssocMany[list.size()]);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private BeanProperty createBeanProperty(BeanDescriptorMap owner, DeployBeanProperty deployProp) {
if (deployProp instanceof DeployBeanPropertyAssocOne) {
return new BeanPropertyAssocOne(owner, desc, (DeployBeanPropertyAssocOne) deployProp);
}
if (deployProp instanceof DeployBeanPropertySimpleCollection<?>) {
return new BeanPropertySimpleCollection(owner, desc, (DeployBeanPropertySimpleCollection)deployProp);
}
if (deployProp instanceof DeployBeanPropertyAssocMany) {
return new BeanPropertyAssocMany(owner, desc, (DeployBeanPropertyAssocMany) deployProp);
}
if (deployProp instanceof DeployBeanPropertyCompound) {
return new BeanPropertyCompound(owner, desc, (DeployBeanPropertyCompound) deployProp);
}
return new BeanProperty(owner, desc, deployProp);
}
return new BeanProperty(owner, desc, deployProp);
}
}
@@ -8,6 +8,7 @@ import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import com.avaje.ebean.annotation.CacheStrategy;
import com.avaje.ebean.annotation.CacheTuning;
import com.avaje.ebean.annotation.EntityConcurrencyMode;
import com.avaje.ebean.annotation.NamedUpdate;
import com.avaje.ebean.annotation.NamedUpdates;
@@ -55,10 +56,8 @@ public class AnnotationClass extends AnnotationParser {
Entity entity = cls.getAnnotation(Entity.class);
if (entity != null) {
// checkDefaultConstructor();
if (entity.name().equals("")) {
descriptor.setName(cls.getSimpleName());
} else {
descriptor.setName(entity.name());
}
@@ -110,8 +109,9 @@ public class AnnotationClass extends AnnotationParser {
}
CacheStrategy cacheStrategy = cls.getAnnotation(CacheStrategy.class);
if (cacheStrategy != null) {
readCacheStrategy(cacheStrategy);
CacheTuning cacheTuning = cls.getAnnotation(CacheTuning.class);
if (cacheStrategy != null || cacheTuning != null) {
readCacheStrategy(cacheStrategy, cacheTuning);
}
EntityConcurrencyMode entityConcurrencyMode = cls.getAnnotation(EntityConcurrencyMode.class);
@@ -120,18 +120,24 @@ public class AnnotationClass extends AnnotationParser {
}
}
private void readCacheStrategy(CacheStrategy cacheStrategy) {
private void readCacheStrategy(CacheStrategy cacheStrategy, CacheTuning cacheTuning) {
CacheOptions cacheOptions = descriptor.getCacheOptions();
cacheOptions.setUseCache(cacheStrategy.useBeanCache());
cacheOptions.setReadOnly(cacheStrategy.readOnly());
cacheOptions.setWarmingQuery(cacheStrategy.warmingQuery());
if (cacheStrategy.naturalKey().length() > 0) {
String propName = cacheStrategy.naturalKey().trim();
DeployBeanProperty beanProperty = descriptor.getBeanProperty(propName);
if (beanProperty != null) {
beanProperty.setNaturalKey(true);
cacheOptions.setNaturalKey(propName);
if (cacheTuning != null) {
cacheOptions.setMaxSecsToLive(cacheTuning.maxSecsToLive());
cacheOptions.setMaxIdleSecs(cacheTuning.maxIdleSecs());
}
if (cacheStrategy != null) {
cacheOptions.setUseCache(cacheStrategy.useBeanCache());
cacheOptions.setReadOnly(cacheStrategy.readOnly());
cacheOptions.setWarmingQuery(cacheStrategy.warmingQuery());
if (cacheStrategy.naturalKey().length() > 0) {
String propName = cacheStrategy.naturalKey().trim();
DeployBeanProperty beanProperty = descriptor.getBeanProperty(propName);
if (beanProperty != null) {
beanProperty.setNaturalKey(true);
cacheOptions.setNaturalKey(propName);
}
}
}
}
@@ -2,6 +2,8 @@ package com.avaje.ebeaninternal.server.el;
import java.util.Comparator;
import com.avaje.ebean.bean.EntityBean;
/**
* Comparator based on a ElGetValue.
*/
@@ -21,15 +23,15 @@ public final class ElComparatorProperty<T> implements Comparator<T>, ElComparato
public int compare(T o1, T o2) {
Object val1 = elGetValue.elGetValue(o1);
Object val2 = elGetValue.elGetValue(o2);
Object val1 = elGetValue.elGetValue((EntityBean)o1);
Object val2 = elGetValue.elGetValue((EntityBean)o2);
return compareValues(val1, val2);
}
public int compareValue(Object value, T o2) {
Object val2 = elGetValue.elGetValue(o2);
Object val2 = elGetValue.elGetValue((EntityBean)o2);
return compareValues(value, val2);
}
@@ -4,6 +4,8 @@ import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import com.avaje.ebean.bean.EntityBean;
/**
* Contains the various ElMatcher implementations.
@@ -26,7 +28,7 @@ class ElMatchBuilder {
}
public boolean isMatch(T bean) {
String v = (String)elGetValue.elGetValue(bean);
String v = (String)elGetValue.elGetValue((EntityBean)bean);
return pattern.matcher(v).matches();
}
}
@@ -53,7 +55,7 @@ class ElMatchBuilder {
}
public boolean isMatch(T bean) {
String v = (String)elGetValue.elGetValue(bean);
String v = (String)elGetValue.elGetValue((EntityBean)bean);
return value.equalsIgnoreCase(v);
}
}
@@ -73,7 +75,7 @@ class ElMatchBuilder {
public boolean isMatch(T bean) {
String v = (String)elGetValue.elGetValue(bean);
String v = (String)elGetValue.elGetValue((EntityBean)bean);
return charMatch.startsWith(v);
}
}
@@ -93,7 +95,7 @@ class ElMatchBuilder {
public boolean isMatch(T bean) {
String v = (String)elGetValue.elGetValue(bean);
String v = (String)elGetValue.elGetValue((EntityBean)bean);
return charMatch.endsWith(v);
}
}
@@ -104,7 +106,7 @@ class ElMatchBuilder {
}
public boolean isMatch(T bean) {
String v = (String)elGetValue.elGetValue(bean);
String v = (String)elGetValue.elGetValue((EntityBean)bean);
return value.startsWith(v);
}
}
@@ -115,7 +117,7 @@ class ElMatchBuilder {
}
public boolean isMatch(T bean) {
String v = (String)elGetValue.elGetValue(bean);
String v = (String)elGetValue.elGetValue((EntityBean)bean);
return value.endsWith(v);
}
}
@@ -129,7 +131,7 @@ class ElMatchBuilder {
}
public boolean isMatch(T bean) {
return (null == elGetValue.elGetValue(bean));
return (null == elGetValue.elGetValue((EntityBean)bean));
}
}
@@ -142,7 +144,7 @@ class ElMatchBuilder {
}
public boolean isMatch(T bean) {
return (null != elGetValue.elGetValue(bean));
return (null != elGetValue.elGetValue((EntityBean)bean));
}
}
@@ -173,7 +175,7 @@ class ElMatchBuilder {
public boolean isMatch(T bean) {
Object value = elGetValue.elGetValue(bean);
Object value = elGetValue.elGetValue((EntityBean)bean);
if (value == null){
return false;
}
@@ -156,7 +156,7 @@ public class ElPropertyChain implements ElPropertyValue {
return lastElPropertyValue.isLocalEncrypted();
}
public Object[] getAssocOneIdValues(Object bean) {
public Object[] getAssocOneIdValues(EntityBean bean) {
// Don't navigate the object graph as bean
// is assumed to be the appropriate type
return lastElPropertyValue.getAssocOneIdValues(bean);
@@ -231,10 +231,10 @@ public class ElPropertyChain implements ElPropertyValue {
return lastElPropertyValue.elConvertType(value);
}
public Object elGetValue(Object bean) {
public Object elGetValue(EntityBean bean) {
for (int i = 0; i < chain.length; i++) {
bean = chain[i].elGetValue(bean);
bean = (EntityBean)chain[i].elGetValue(bean);
if (bean == null) {
return null;
}
@@ -243,24 +243,22 @@ public class ElPropertyChain implements ElPropertyValue {
return bean;
}
public Object elGetReference(Object bean) {
public Object elGetReference(EntityBean bean) {
Object prevBean = bean;
EntityBean prevBean = bean;
for (int i = 0; i < last; i++) {
// always return non null prevBean
prevBean = chain[i].elGetReference(prevBean);
prevBean = (EntityBean)chain[i].elGetReference(prevBean);
}
// try the last step in the chain
bean = chain[last].elGetValue(prevBean);
return bean;
return chain[last].elGetValue(prevBean);
}
public void elSetLoaded(Object bean) {
public void elSetLoaded(EntityBean bean) {
for (int i = 0; i < last; i++) {
bean = chain[i].elGetValue(bean);
bean = (EntityBean)chain[i].elGetValue(bean);
if (bean == null){
break;
}
@@ -270,31 +268,18 @@ public class ElPropertyChain implements ElPropertyValue {
}
}
public void elSetReference(Object bean) {
public void elSetValue(EntityBean bean, Object value, boolean populate) {
for (int i = 0; i < last; i++) {
bean = chain[i].elGetValue(bean);
if (bean == null){
break;
}
}
if (bean != null){
((EntityBean)bean)._ebean_getIntercept().setReference();
}
}
public void elSetValue(Object bean, Object value, boolean populate, boolean reference){
Object prevBean = bean;
EntityBean prevBean = bean;
if (populate){
for (int i = 0; i < last; i++) {
// always return non null prevBean
prevBean = chain[i].elGetReference(prevBean);
prevBean = (EntityBean)chain[i].elGetReference(prevBean);
}
} else {
for (int i = 0; i < last; i++) {
// always return non null prevBean
prevBean = chain[i].elGetValue(prevBean);
prevBean = (EntityBean)chain[i].elGetValue(prevBean);
if (prevBean == null){
break;
}
@@ -304,12 +289,10 @@ public class ElPropertyChain implements ElPropertyValue {
if (lastBeanProperty != null){
// last chain element maps to a real scalar property
lastBeanProperty.setValueIntercept(prevBean, value);
if (reference){
((EntityBean)prevBean)._ebean_getIntercept().setReference();
}
} else {
// a non-scalar property of a Compound value object
lastElPropertyValue.elSetValue(prevBean, value, populate, reference);
lastElPropertyValue.elSetValue(prevBean, value, populate);
}
}
}
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.el;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.text.StringFormatter;
import com.avaje.ebean.text.StringParser;
@@ -14,7 +15,7 @@ public interface ElPropertyValue extends ElPropertyDeploy {
/**
* Return the Id values for the given bean value.
*/
public Object[] getAssocOneIdValues(Object bean);
public Object[] getAssocOneIdValues(EntityBean bean);
/**
* Return the Id expression string.
@@ -89,13 +90,13 @@ public interface ElPropertyValue extends ElPropertyDeploy {
/**
* Return the value from a given entity bean.
*/
public Object elGetValue(Object bean);
public Object elGetValue(EntityBean bean);
/**
* Return the value ensuring objects prior to the top scalar property are
* automatically populated.
*/
public Object elGetReference(Object bean);
public Object elGetReference(EntityBean bean);
/**
* Set a value given a root level bean.
@@ -103,12 +104,7 @@ public interface ElPropertyValue extends ElPropertyDeploy {
* If populate then
* </p>
*/
public void elSetValue(Object bean, Object value, boolean populate, boolean reference);
/**
* Make the owning bean of this property a reference (as in not new/dirty).
*/
public void elSetReference(Object bean);
public void elSetValue(EntityBean bean, Object value, boolean populate);
/**
* Convert the value to the expected type.
@@ -5,6 +5,7 @@ import java.util.Iterator;
import com.avaje.ebean.ExampleExpression;
import com.avaje.ebean.LikeType;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.event.BeanQueryRequest;
import com.avaje.ebeaninternal.api.HashQueryPlanBuilder;
import com.avaje.ebeaninternal.api.ManyWhereJoins;
@@ -43,7 +44,7 @@ public class DefaultExampleExpression implements SpiExpression, ExampleExpressio
/**
* The example bean containing the properties.
*/
private final Object entity;
private final EntityBean entity;
/**
* Set to true to use case insensitive expressions.
@@ -66,6 +67,7 @@ public class DefaultExampleExpression implements SpiExpression, ExampleExpressio
*/
private ArrayList<SpiExpression> list;
/**
* Construct the query by example expression.
*
@@ -76,7 +78,7 @@ public class DefaultExampleExpression implements SpiExpression, ExampleExpressio
* @param likeType
* the type of Like wild card used
*/
public DefaultExampleExpression(Object entity, boolean caseInsensitive, LikeType likeType) {
public DefaultExampleExpression(EntityBean entity, boolean caseInsensitive, LikeType likeType) {
this.entity = entity;
this.caseInsensitive = caseInsensitive;
this.likeType = likeType;
@@ -11,6 +11,7 @@ import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Junction;
import com.avaje.ebean.LikeType;
import com.avaje.ebean.Query;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiExpressionFactory;
import com.avaje.ebeaninternal.api.SpiQuery;
@@ -21,6 +22,7 @@ public class DefaultExpressionFactory implements SpiExpressionFactory {
private static final Object[] EMPTY_ARRAY = new Object[] {};
public DefaultExpressionFactory() {
}
@@ -128,11 +130,18 @@ public class DefaultExpressionFactory implements SpiExpressionFactory {
return new NullExpression(propertyName, true);
}
private EntityBean checkEntityBean(Object bean) {
if (bean == null || (bean instanceof EntityBean == false)) {
throw new IllegalStateException("Expecting an EntityBean");
}
return (EntityBean)bean;
}
/**
* Case insensitive {@link #exampleLike(Object)}
*/
public ExampleExpression iexampleLike(Object example) {
return new DefaultExampleExpression(example, true, LikeType.RAW);
return new DefaultExampleExpression(checkEntityBean(example), true, LikeType.RAW);
}
/**
@@ -140,14 +149,14 @@ public class DefaultExpressionFactory implements SpiExpressionFactory {
* LikeType.RAW (you need to add you own wildcards % and _).
*/
public ExampleExpression exampleLike(Object example) {
return new DefaultExampleExpression(example, false, LikeType.RAW);
return new DefaultExampleExpression(checkEntityBean(example), false, LikeType.RAW);
}
/**
* Create the query by Example expression specifying more options.
*/
public ExampleExpression exampleLike(Object example, boolean caseInsensitive, LikeType likeType) {
return new DefaultExampleExpression(example, caseInsensitive, likeType);
return new DefaultExampleExpression(checkEntityBean(example), caseInsensitive, likeType);
}
/**
@@ -2,6 +2,7 @@ package com.avaje.ebeaninternal.server.expression;
import java.util.Collection;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.event.BeanQueryRequest;
import com.avaje.ebeaninternal.api.HashQueryPlanBuilder;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
@@ -36,7 +37,7 @@ class InExpression extends AbstractExpression {
} else {
// extract the id values from the bean
Object[] ids = prop.getAssocOneIdValues(values[i]);
Object[] ids = prop.getAssocOneIdValues((EntityBean)values[i]);
if (ids != null) {
for (int j = 0; j < ids.length; j++) {
request.addBindValue(ids[j]);
@@ -14,7 +14,6 @@ import com.avaje.ebean.Junction;
import com.avaje.ebean.OrderBy;
import com.avaje.ebean.PagingList;
import com.avaje.ebean.QueryIterator;
import com.avaje.ebean.QueryListener;
import com.avaje.ebean.QueryResultVisitor;
import com.avaje.ebean.event.BeanQueryRequest;
import com.avaje.ebeaninternal.api.HashQueryPlanBuilder;
@@ -375,19 +374,10 @@ abstract class JunctionExpression<T> implements Junction<T>, SpiExpression, Expr
return exprList.select(properties);
}
public com.avaje.ebean.Query<T> setBackgroundFetchAfter(int backgroundFetchAfter) {
return exprList.setBackgroundFetchAfter(backgroundFetchAfter);
}
public com.avaje.ebean.Query<T> setFirstRow(int firstRow) {
return exprList.setFirstRow(firstRow);
}
@Deprecated
public com.avaje.ebean.Query<T> setListener(QueryListener<T> queryListener) {
return exprList.setListener(queryListener);
}
public com.avaje.ebean.Query<T> setMapKey(String mapKey) {
return exprList.setMapKey(mapKey);
}
@@ -1,5 +1,6 @@
package com.avaje.ebeaninternal.server.expression;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.event.BeanQueryRequest;
import com.avaje.ebeaninternal.api.HashQueryPlanBuilder;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
@@ -48,7 +49,7 @@ public class SimpleExpression extends AbstractExpression {
ElPropertyValue prop = getElProp(request);
if (prop != null) {
if (prop.isAssocId()) {
Object[] ids = prop.getAssocOneIdValues(value);
Object[] ids = prop.getAssocOneIdValues((EntityBean)value);
if (ids != null) {
for (int i = 0; i < ids.length; i++) {
request.addBindValue(ids[i]);
@@ -17,6 +17,7 @@ import com.avaje.ebeaninternal.server.querydefn.OrmQueryProperties;
/**
* Default implementation of LoadBeanContext.
*
*/
public class DLoadBeanContext extends DLoadBaseContext implements LoadBeanContext{
@@ -155,7 +156,7 @@ public class DLoadBeanContext extends DLoadBaseContext implements LoadBeanContex
return;
}
if (context.hitCache && context.desc.loadFromCache(ebi)) {
if (context.hitCache && context.desc.cacheBeanLoad(ebi)) {
// successfully hit the L2 cache so don't invoke DB lazy loading
list.remove(ebi);
return;
@@ -166,7 +167,7 @@ public class DLoadBeanContext extends DLoadBaseContext implements LoadBeanContex
Iterator<EntityBeanIntercept> iterator = list.iterator();
while (iterator.hasNext()) {
EntityBeanIntercept bean = iterator.next();
if (context.desc.loadFromCache(bean)) {
if (context.desc.cacheBeanLoad(bean)) {
iterator.remove();
}
}
@@ -5,11 +5,12 @@ import java.util.List;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.BeanCollectionLoader;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.ObjectGraphNode;
import com.avaje.ebean.bean.PersistenceContext;
import com.avaje.ebeaninternal.api.LoadManyBuffer;
import com.avaje.ebeaninternal.api.LoadManyContext;
import com.avaje.ebeaninternal.api.LoadManyRequest;
import com.avaje.ebeaninternal.api.LoadManyBuffer;
import com.avaje.ebeaninternal.api.SpiQuery;
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
@@ -32,6 +33,7 @@ public class DLoadManyContext extends DLoadBaseContext implements LoadManyContex
this.property = property;
this.bufferList = new ArrayList<DLoadManyContext.LoadBuffer>();
this.currentBuffer = createBuffer(firstBatchSize);
}
private LoadBuffer createBuffer(int size) {
@@ -173,10 +175,10 @@ public class DLoadManyContext extends DLoadBaseContext implements LoadManyContex
synchronized (this) {
boolean useCache = context.hitCache && !onlyIds;
if (useCache) {
Object ownerBean = bc.getOwnerBean();
EntityBean ownerBean = bc.getOwnerBean();
BeanDescriptor<? extends Object> parentDesc = context.desc.getBeanDescriptor(ownerBean.getClass());
Object parentId = parentDesc.getId(ownerBean);
if (parentDesc.cacheLoadMany(context.property, bc, parentId, context.parent.isReadOnly())) {
if (parentDesc.cacheManyPropLoad(context.property, bc, parentId, context.parent.isReadOnly())) {
// we loaded the bean from cache
list.remove(bc);
return;
@@ -168,7 +168,7 @@ public final class BatchControl {
// special case where the same bean instance has been added
// to the batch more than once
if (logger.isDebugEnabled()) {
logger.debug("Bean instance already in this batch: " + request.getBean());
logger.debug("Bean instance already in this batch: " + request.getEntityBean());
}
return -1;
}
@@ -103,7 +103,7 @@ public class BatchedBeanHolder {
*/
public ArrayList<PersistRequest> getList(PersistRequestBean<?> request) {
Integer objHashCode = Integer.valueOf(System.identityHashCode(request.getBean()));
Integer objHashCode = Integer.valueOf(System.identityHashCode(request.getEntityBean()));
if (!beanHashCodes.add(objHashCode)) {
// special case where the same bean instance has already been
@@ -2,19 +2,20 @@ package com.avaje.ebeaninternal.server.persist;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.PersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.CallableSql;
import com.avaje.ebean.Query;
import com.avaje.ebean.SqlUpdate;
import com.avaje.ebean.Transaction;
import com.avaje.ebean.Update;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.BeanCollection.ModifyListenMode;
import com.avaje.ebean.bean.EntityBean;
@@ -31,6 +32,7 @@ import com.avaje.ebeaninternal.server.core.PersistRequestOrmUpdate;
import com.avaje.ebeaninternal.server.core.PersistRequestUpdateSql;
import com.avaje.ebeaninternal.server.core.Persister;
import com.avaje.ebeaninternal.server.core.PstmtBatch;
import com.avaje.ebeaninternal.server.deploy.BeanCollectionUtil;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptorManager;
import com.avaje.ebeaninternal.server.deploy.BeanManager;
@@ -40,9 +42,6 @@ import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
import com.avaje.ebeaninternal.server.deploy.IntersectionRow;
import com.avaje.ebeaninternal.server.deploy.ManyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Persister implementation using DML.
* <p>
@@ -72,6 +71,7 @@ public final class DefaultPersister implements Persister {
private final BeanDescriptorManager beanDescriptorManager;
public DefaultPersister(SpiEbeanServer server, Binder binder, BeanDescriptorManager descMgr, PstmtBatch pstmtBatch) {
this.server = server;
@@ -150,106 +150,40 @@ public final class DefaultPersister implements Persister {
server.delete(detailBean, t);
}
/**
* Force an Update using the given bean.
*/
public void forceUpdate(Object bean, Set<String> updateProps, Transaction t, boolean deleteMissingChildren, boolean updateNullProperties) {
/**
* Force an Update using the given bean.
*/
public void forceUpdate(EntityBean entityBean, Transaction t, boolean deleteMissingChildren) {
if (bean == null) {
throw new NullPointerException(Message.msg("bean.isnull"));
}
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);
try {
req.initTransIfRequired();
update(req);
req.commitTransIfRequired();
// finished a 'normal' update
return;
if (updateProps == null) {
// checking to see if this is just a 'normal' update
if (bean instanceof EntityBean) {
EntityBeanIntercept ebi = ((EntityBean) bean)._ebean_getIntercept();
if (ebi.isDirty() || ebi.isLoaded()) {
// a 'normal' update using 'dirty' properties from internal bean state.
// if not dirty we still update in case any cascading save occurs
PersistRequestBean<?> req = createRequest(bean, t, null);
try {
req.initTransIfRequired();
update(req);
req.commitTransIfRequired();
// finished a 'normal' update
return;
} catch (RuntimeException ex) {
req.rollbackTransIfRequired();
throw ex;
}
}
} catch (RuntimeException ex) {
req.rollbackTransIfRequired();
throw ex;
}
} else if (ebi.isReference()) {
// just return as no point in cascading (no modified beans/lists)
return;
}
// loadedProps set by Ebean JSON / XML Marshalling
updateProps = ebi.getLoadedProps();
}
}
BeanManager<?> mgr = getBeanManager(bean);
if (mgr == null) {
throw new PersistenceException(errNotRegistered(bean.getClass()));
}
forceUpdateStateless(bean, t, null, mgr, updateProps, deleteMissingChildren, updateNullProperties);
}
/**
* Force a 'stateless' update determining which properties to update.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private void forceUpdateStateless(Object bean, Transaction t, Object parentBean, BeanManager<?> mgr, Set<String> updateProps,
boolean deleteMissingChildren, boolean updateNullProperties) {
BeanDescriptor<?> descriptor = mgr.getBeanDescriptor();
// determine concurrency mode based on version property not null
ConcurrencyMode mode = descriptor.determineConcurrencyMode(bean);
if (updateProps == null) {
// determine based on null treatment (all properties updated or just the non-null ones)
updateProps = updateNullProperties ? null : descriptor.determineLoadedProperties(bean);
} else if (updateProps.isEmpty()) {
// in this case means we want to include all properties in the update
updateProps = null;
} else if (ConcurrencyMode.VERSION.equals(mode)) {
// check that the version property is included
String verName = descriptor.firstVersionProperty().getName();
if (!updateProps.contains(verName)) {
// defensively copy the updateProps and add the version property name
updateProps = new HashSet<String>(updateProps);
updateProps.add(verName);
}
}
PersistRequestBean<?> req = new PersistRequestBean(server, bean, parentBean, mgr, (SpiTransaction) t, persistExecute, updateProps, mode);
req.setStatelessUpdate(true, deleteMissingChildren, updateNullProperties);
try {
req.initTransIfRequired();
update(req);
req.commitTransIfRequired();
} catch (RuntimeException ex) {
req.rollbackTransIfRequired();
throw ex;
}
}
public void save(Object bean, Transaction t) {
public void save(EntityBean bean, Transaction t) {
saveRecurse(bean, t, null);
}
/**
* Explicitly specify to insert this bean.
*/
public void forceInsert(Object bean, Transaction t) {
public void forceInsert(EntityBean bean, Transaction t) {
PersistRequestBean<?> req = createRequest(bean, t, null);
PersistRequestBean<?> req = createRequest(bean, t, null, PersistRequest.Type.INSERT);
try {
req.initTransIfRequired();
insert(req);
@@ -270,7 +204,7 @@ public final class DefaultPersister implements Persister {
throw new IllegalArgumentException("This bean is of type ["+bean.getClass()+"] is not enhanced?");
}
PersistRequestBean<?> req = createRequest(bean, t, parentBean);
PersistRequestBean<?> req = createRequest(bean, t, parentBean, PersistRequest.Type.DETERMINE);
try {
req.initTransIfRequired();
saveEnhanced(req);
@@ -289,21 +223,22 @@ public final class DefaultPersister implements Persister {
EntityBeanIntercept intercept = request.getEntityBeanIntercept();
if (intercept.isReference()) {
if (request.isReference()) {
// its a reference...
if (request.isPersistCascade()) {
// save any associated List held beans
intercept.setLoaded();
saveAssocMany(false, request);
intercept.setReference();
intercept.setReference(-1);
}
request.checkUpdatedManysOnly();
} else {
if (intercept.isLoaded()) {
// Need to call setLoaded(false) to simulate insert
update(request);
if (request.isInsert()) {
insert(request);
} else {
insert(request);
update(request);
}
}
}
@@ -319,8 +254,6 @@ public final class DefaultPersister implements Persister {
}
try {
request.setType(PersistRequest.Type.INSERT);
if (request.isPersistCascade()) {
// save associated One beans recursively first
saveAssocOne(request);
@@ -350,8 +283,6 @@ public final class DefaultPersister implements Persister {
}
try {
// we have determined that it is an update
request.setType(PersistRequest.Type.UPDATE);
if (request.isPersistCascade()) {
// save associated One beans recursively first
saveAssocOne(request);
@@ -371,6 +302,9 @@ public final class DefaultPersister implements Persister {
// save all the beans in assocMany's after
saveAssocMany(false, request);
}
request.checkUpdatedManysOnly();
} finally {
request.unRegisterBean();
}
@@ -379,9 +313,9 @@ public final class DefaultPersister implements Persister {
/**
* Delete the bean with the explicit transaction.
*/
public void delete(Object bean, Transaction t) {
public void delete(EntityBean bean, Transaction t) {
PersistRequestBean<?> req = createRequest(bean, t, null);
PersistRequestBean<?> req = createRequest(bean, t, null, PersistRequest.Type.DELETE);
if (req.isRegisteredForDeleteBean()) {
// skip deleting bean. Used where cascade is on
// both sides of a relationship
@@ -390,7 +324,7 @@ public final class DefaultPersister implements Persister {
}
return;
}
req.setType(PersistRequest.Type.DELETE);
try {
req.initTransIfRequired();
delete(req);
@@ -404,7 +338,7 @@ public final class DefaultPersister implements Persister {
private void deleteList(List<?> beanList, Transaction t) {
for (int i = 0; i < beanList.size(); i++) {
Object bean = beanList.get(i);
EntityBean bean = (EntityBean)beanList.get(i);
delete(bean, t);
}
}
@@ -468,7 +402,7 @@ public final class DefaultPersister implements Persister {
if (t.isLogSummary()) {
t.logSummary("-- DeleteById of " + descriptor.getName() + " id[" + id + "] requires fetch of foreign key values");
}
Object bean = server.findUnique(q, t);
EntityBean bean = (EntityBean)server.findUnique(q, t);
if (bean == null) {
return 0;
} else {
@@ -484,7 +418,7 @@ public final class DefaultPersister implements Persister {
BeanPropertyAssocOne<?>[] expOnes = descriptor.propertiesOneExportedDelete();
for (int i = 0; i < expOnes.length; i++) {
BeanDescriptor<?> targetDesc = expOnes[i].getTargetDescriptor();
if (targetDesc.isDeleteRecurseSkippable() && !targetDesc.isUsingL2Cache()) {
if (targetDesc.isDeleteRecurseSkippable() && !targetDesc.isBeanCaching()) {
SqlUpdate sqlDelete = expOnes[i].deleteByParentId(id, idList);
executeSqlUpdate(sqlDelete, t);
} else {
@@ -497,7 +431,7 @@ public final class DefaultPersister implements Persister {
BeanPropertyAssocMany<?>[] manys = descriptor.propertiesManyDelete();
for (int i = 0; i < manys.length; i++) {
BeanDescriptor<?> targetDesc = manys[i].getTargetDescriptor();
if (targetDesc.isDeleteRecurseSkippable() && !targetDesc.isUsingL2Cache()) {
if (targetDesc.isDeleteRecurseSkippable() && !targetDesc.isBeanCaching()) {
// we can just delete children with a single statement
SqlUpdate sqlDelete = manys[i].deleteByParentId(id, idList);
executeSqlUpdate(sqlDelete, t);
@@ -610,7 +544,7 @@ public final class DefaultPersister implements Persister {
*/
private void saveAssocMany(boolean insertedParent, PersistRequestBean<?> request) {
Object parentBean = request.getBean();
EntityBean parentBean = request.getEntityBean();
BeanDescriptor<?> desc = request.getBeanDescriptor();
SpiTransaction t = request.getTransaction();
@@ -637,7 +571,13 @@ public final class DefaultPersister implements Persister {
// many's with cascade save
BeanPropertyAssocMany<?>[] manys = desc.propertiesManySave();
for (int i = 0; i < manys.length; i++) {
saveMany(new SaveManyPropRequest(insertedParent, manys[i], parentBean, request));
// check that property is loaded and not empty uninitialised collection
if (request.isLoadedProperty(manys[i]) && !manys[i].isEmptyBeanCollection(parentBean)) {
saveMany(new SaveManyPropRequest(insertedParent, manys[i], parentBean, request));
if (!insertedParent) {
request.addUpdatedManyProperty(manys[i]);
}
}
}
}
@@ -648,39 +588,36 @@ public final class DefaultPersister implements Persister {
private static class SaveManyPropRequest {
private final boolean insertedParent;
private final BeanPropertyAssocMany<?> many;
private final Object parentBean;
private final SpiTransaction t;
private final EntityBean parentBean;
private final SpiTransaction transaction;
private final boolean cascade;
private final boolean statelessUpdate;
private final boolean deleteMissingChildren;
private final boolean updateNullProperties;
private SaveManyPropRequest(boolean insertedParent, BeanPropertyAssocMany<?> many, Object parentBean, PersistRequestBean<?> request) {
private SaveManyPropRequest(boolean insertedParent, BeanPropertyAssocMany<?> many, EntityBean parentBean, PersistRequestBean<?> request) {
this.insertedParent = insertedParent;
this.many = many;
this.cascade = many.getCascadeInfo().isSave();
this.parentBean = parentBean;
this.t = request.getTransaction();
this.transaction = request.getTransaction();
this.statelessUpdate = request.isStatelessUpdate();
this.deleteMissingChildren = request.isDeleteMissingChildren();
this.updateNullProperties = request.isUpdateNullProperties();
}
private SaveManyPropRequest(BeanPropertyAssocMany<?> many, Object parentBean, SpiTransaction t) {
private SaveManyPropRequest(BeanPropertyAssocMany<?> many, EntityBean parentBean, SpiTransaction t) {
this.insertedParent = false;
this.many = many;
this.parentBean = parentBean;
this.t = t;
this.transaction = t;
this.cascade = true;
this.statelessUpdate = false;
this.deleteMissingChildren = false;
this.updateNullProperties = false;
}
public boolean isSaveIntersection() {
return t.isSaveAssocManyIntersection(many.getIntersectionTableJoin().getTable(), many.getBeanDescriptor().getName());
return transaction.isSaveAssocManyIntersection(many.getIntersectionTableJoin().getTable(), many.getBeanDescriptor().getName());
}
private Object getValue() {
return many.getValue(parentBean);
}
@@ -696,10 +633,6 @@ public final class DefaultPersister implements Persister {
private boolean isDeleteMissingChildren() {
return deleteMissingChildren;
}
private boolean isUpdateNullProperties() {
return updateNullProperties;
}
private boolean isInsertedParent() {
return insertedParent;
@@ -709,12 +642,12 @@ public final class DefaultPersister implements Persister {
return many;
}
private Object getParentBean() {
private EntityBean getParentBean() {
return parentBean;
}
private SpiTransaction getTransaction() {
return t;
return transaction;
}
private boolean isCascade() {
@@ -730,7 +663,7 @@ public final class DefaultPersister implements Persister {
boolean saveIntersectionFromThisDirection = saveMany.isSaveIntersection();
if (saveMany.isCascade()) {
// Need explicit Cascade to save the beans on other side
saveAssocManyDetails(saveMany, false, saveMany.isUpdateNullProperties());
saveAssocManyDetails(saveMany, false);
}
// for ManyToMany save the 'relationship' via inserts/deletes
// into/from the intersection table
@@ -740,7 +673,7 @@ public final class DefaultPersister implements Persister {
}
} else {
if (saveMany.isCascade()) {
saveAssocManyDetails(saveMany, saveMany.isDeleteMissingChildren(), saveMany.isUpdateNullProperties());
saveAssocManyDetails(saveMany, saveMany.isDeleteMissingChildren());
}
if (saveMany.isModifyListenMode()) {
removeAssocManyPrivateOwned(saveMany);
@@ -781,7 +714,7 @@ public final class DefaultPersister implements Persister {
/**
* Save the details from a OneToMany collection.
*/
private void saveAssocManyDetails(SaveManyPropRequest saveMany, boolean deleteMissingChildren, boolean updateNullProperties) {
private void saveAssocManyDetails(SaveManyPropRequest saveMany, boolean deleteMissingChildren) {
BeanPropertyAssocMany<?> prop = saveMany.getMany();
@@ -790,19 +723,19 @@ public final class DefaultPersister implements Persister {
// check that the list is not null and if it is a BeanCollection
// check that is has been populated (don't trigger lazy loading)
// For a Map this is a collection of Map.Entry objects and not beans
Collection<?> collection = getActualEntries(details);
Collection<?> collection = BeanCollectionUtil.getActualEntries(details);
if (collection == null) {
// nothing to do here
return;
}
BeanDescriptor<?> targetDescriptor = prop.getTargetDescriptor();
if (saveMany.isInsertedParent()) {
// performance optimisation for large collections
prop.getTargetDescriptor().preAllocateIds(collection.size());
targetDescriptor.preAllocateIds(collection.size());
}
BeanDescriptor<?> targetDescriptor = prop.getTargetDescriptor();
ArrayList<Object> detailIds = null;
if (deleteMissingChildren) {
// collect the Id's (to exclude from deleteManyDetails)
@@ -817,7 +750,7 @@ public final class DefaultPersister implements Persister {
// set it to the appropriate property on the
// detail bean before we save it
boolean isMap = ManyType.JAVA_MAP.equals(prop.getManyType());
Object parentBean = saveMany.getParentBean();
EntityBean parentBean = (EntityBean)saveMany.getParentBean();
Object mapKeyValue = null;
boolean saveSkippable = prop.isSaveRecurseSkippable();
@@ -831,59 +764,58 @@ public final class DefaultPersister implements Persister {
detailBean = entry.getValue();
}
if (prop.isManyToMany()) {
if (detailBean instanceof EntityBean) {
skipSavingThisBean = ((EntityBean) detailBean)._ebean_getIntercept().isReference();
}
if (detailBean instanceof EntityBean == false) {
skipSavingThisBean = true;
logger.debug("Skip non entity bean");
} else {
// set the 'parent/master' bean to the detailBean as long
// as we don't make it 'dirty' in doing so
if (detailBean instanceof EntityBean) {
EntityBeanIntercept ebi = ((EntityBean) detailBean)._ebean_getIntercept();
if (ebi.isNewOrDirty()) {
// set the parent bean to detailBean
prop.setJoinValuesToChild(parentBean, detailBean, mapKeyValue);
} else if (ebi.isReference()) {
// we can skip this one
skipSavingThisBean = true;
EntityBean detail = (EntityBean)detailBean;
EntityBeanIntercept ebi = detail._ebean_getIntercept();
if (prop.isManyToMany()) {
skipSavingThisBean = targetDescriptor.isReference(ebi);
} else {
if (targetDescriptor.isReference(ebi)) {
// we can skip this one
skipSavingThisBean = true;
} else {
// unmodified so skip depending on prop.isSaveRecurseSkippable();
skipSavingThisBean = saveSkippable;
}
} else {
// set the parent bean to detailBean
prop.setJoinValuesToChild(parentBean, detailBean, mapKeyValue);
}
}
} else if (ebi.isNewOrDirty()) {
skipSavingThisBean = false;
// set the parent bean to detailBean
prop.setJoinValuesToChild(parentBean, detail, mapKeyValue);
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 {
// unmodified so skip depending on prop.isSaveRecurseSkippable();
skipSavingThisBean = saveSkippable;
}
}
} else if (!saveMany.isStatelessUpdate()) {
// normal save recurse
saveRecurse(detailBean, t, parentBean);
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 (targetDescriptor.isStatelessUpdate(detailBean)) {
// update based on the value of Version/Id properties
// cascade update in stateless mode
forceUpdate(detailBean, null, t, deleteMissingChildren, updateNullProperties);
} else {
// cascade insert
forceInsert(detailBean, t);
}
}
} else if (!saveMany.isStatelessUpdate()) {
// normal save recurse
saveRecurse(detailBean, t, parentBean);
if (detailIds != null) {
// remember the Id (other details not in the collection) will be removed
Object id = targetDescriptor.getId(detailBean);
if (!DmlUtil.isNullOrZero(id)) {
detailIds.add(id);
}
} 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);
}
}
}
}
@@ -895,14 +827,14 @@ public final class DefaultPersister implements Persister {
}
public int deleteManyToManyAssociations(Object ownerBean, String propertyName, Transaction t) {
public int deleteManyToManyAssociations(EntityBean ownerBean, String propertyName, Transaction t) {
BeanDescriptor<?> descriptor = beanDescriptorManager.getBeanDescriptor(ownerBean.getClass());
BeanPropertyAssocMany<?> prop = (BeanPropertyAssocMany<?>) descriptor.getBeanProperty(propertyName);
return deleteAssocManyIntersection(ownerBean, prop, t);
}
public void saveManyToManyAssociations(Object ownerBean, String propertyName, Transaction t) {
public void saveManyToManyAssociations(EntityBean ownerBean, String propertyName, Transaction t) {
BeanDescriptor<?> descriptor = beanDescriptorManager.getBeanDescriptor(ownerBean.getClass());
BeanPropertyAssocMany<?> prop = (BeanPropertyAssocMany<?>) descriptor.getBeanProperty(propertyName);
@@ -910,7 +842,7 @@ public final class DefaultPersister implements Persister {
saveAssocManyIntersection(new SaveManyPropRequest(prop, ownerBean, (SpiTransaction) t), false);
}
public void saveAssociation(Object parentBean, String propertyName, Transaction t) {
public void saveAssociation(EntityBean parentBean, String propertyName, Transaction t) {
BeanDescriptor<?> descriptor = beanDescriptorManager.getBeanDescriptor(parentBean.getClass());
SpiTransaction trans = (SpiTransaction) t;
@@ -995,7 +927,8 @@ public final class DefaultPersister implements Persister {
t.depth(+1);
if (additions != null && !additions.isEmpty()) {
for (Object otherBean : additions) {
for (Object other : additions) {
EntityBean otherBean = (EntityBean)other;
// the object from the 'other' side of the ManyToMany
if (deletions != null && deletions.remove(otherBean)) {
String m = "Inserting and Deleting same object? " + otherBean;
@@ -1019,7 +952,8 @@ public final class DefaultPersister implements Persister {
}
}
if (deletions != null && !deletions.isEmpty()) {
for (Object otherDelete : deletions) {
for (Object other : deletions) {
EntityBean otherDelete = (EntityBean)other;
// the object from the 'other' side of the ManyToMany
// build a intersection row for 'delete'
IntersectionRow intRow = prop.buildManyToManyMapBean(saveManyPropRequest.getParentBean(), otherDelete);
@@ -1032,7 +966,7 @@ public final class DefaultPersister implements Persister {
t.depth(-1);
}
private int deleteAssocManyIntersection(Object bean, BeanPropertyAssocMany<?> many, Transaction t) {
private int deleteAssocManyIntersection(EntityBean bean, BeanPropertyAssocMany<?> many, Transaction t) {
// delete all intersection rows for this bean
IntersectionRow intRow = many.buildManyToManyDeleteChildren(bean);
@@ -1053,7 +987,7 @@ public final class DefaultPersister implements Persister {
t.depth(-1);
BeanDescriptor<?> desc = request.getBeanDescriptor();
Object parentBean = request.getBean();
EntityBean parentBean = request.getEntityBean();
BeanPropertyAssocOne<?>[] expOnes = desc.propertiesOneExportedDelete();
if (expOnes.length > 0) {
@@ -1096,7 +1030,8 @@ public final class DefaultPersister implements Persister {
if (modifyRemovals != null && !modifyRemovals.isEmpty()) {
// delete the orphans that have been removed from the collection
for (Object detailBean : modifyRemovals) {
for (Object detail : modifyRemovals) {
EntityBean detailBean = (EntityBean)detail;
if (manys[i].hasId(detailBean)) {
deleteRecurse(detailBean, t);
}
@@ -1121,13 +1056,13 @@ public final class DefaultPersister implements Persister {
* collection (and should not be deleted).
* </p>
*/
private void deleteManyDetails(SpiTransaction t, BeanDescriptor<?> desc, Object parentBean,
private void deleteManyDetails(SpiTransaction t, BeanDescriptor<?> desc, EntityBean parentBean,
BeanPropertyAssocMany<?> many, ArrayList<Object> excludeDetailIds) {
if (many.getCascadeInfo().isDelete()) {
// cascade delete the beans in the collection
BeanDescriptor<?> targetDesc = many.getTargetDescriptor();
if (targetDesc.isDeleteRecurseSkippable() && !targetDesc.isUsingL2Cache()) {
if (targetDesc.isDeleteRecurseSkippable() && !targetDesc.isBeanCaching()) {
// Just delete all the children with one statement
IntersectionRow intRow = many.buildManyDeleteChildren(parentBean, excludeDetailIds);
SqlUpdate sqlDelete = intRow.createDelete(server);
@@ -1159,9 +1094,9 @@ public final class DefaultPersister implements Persister {
// check for partial objects
if (request.isLoadedProperty(prop)) {
Object detailBean = prop.getValue(request.getBean());
Object detailBean = prop.getValue(request.getEntityBean());
if (detailBean != null) {
if (isReference(detailBean)) {
if (prop.isReference(detailBean)) {
// skip saving a reference
} else if (request.isParent(detailBean)) {
// skip saving the parent as already saved
@@ -1179,13 +1114,6 @@ public final class DefaultPersister implements Persister {
}
}
/**
* Return true if the bean is a reference.
*/
private boolean isReference(Object bean) {
return (bean instanceof EntityBean) && ((EntityBean) bean)._ebean_getIntercept().isReference();
}
/**
* Support for loading any Imported Associated One properties that are not
* loaded but required for Delete cascade.
@@ -1223,9 +1151,12 @@ public final class DefaultPersister implements Persister {
// handled by DeleteUnloadedForeignKeys that was built
// via getDeleteUnloadedForeignKeys();
} else {
Object detailBean = prop.getValue(request.getBean());
if (detailBean != null && prop.hasId(detailBean)) {
deleteRecurse(detailBean, request.getTransaction());
Object detailBean = prop.getValue(request.getEntityBean());
if (detailBean != null) {
EntityBean detail = (EntityBean)detailBean;
if (prop.hasId(detail)) {
deleteRecurse(detail, request.getTransaction());
}
}
}
}
@@ -1241,13 +1172,13 @@ public final class DefaultPersister implements Persister {
return;
}
BeanProperty idProp = desc.getSingleIdProperty();
BeanProperty idProp = desc.getIdProperty();
if (idProp == null || idProp.isEmbedded()) {
// not supporting IdGeneration for concatenated or Embedded
return;
}
Object bean = request.getBean();
EntityBean bean = request.getEntityBean();
Object uid = idProp.getValue(bean);
if (DmlUtil.isNullOrZero(uid)) {
@@ -1260,45 +1191,19 @@ public final class DefaultPersister implements Persister {
}
}
/**
* Return the details of the collection or map taking care to avoid
* unnecessary fetching of the data.
*/
private Collection<?> getActualEntries(Object o) {
if (o == null) {
return null;
}
if (o instanceof BeanCollection<?>) {
BeanCollection<?> bc = (BeanCollection<?>) o;
if (!bc.isPopulated()) {
return null;
}
// For maps this is a collection of Map.Entry, otherwise it
// returns a collection of beans
return bc.getActualEntries();
}
if (o instanceof Map<?, ?>) {
// yes, we want the entrySet (to set the keys)
return ((Map<?, ?>) o).entrySet();
} else if (o instanceof Collection<?>) {
return ((Collection<?>) o);
}
throw new PersistenceException("expecting a Map or Collection but got [" + o.getClass().getName() + "]");
}
/**
* Create the Persist Request Object that wraps all the objects used to
* perform an insert, update or delete.
*/
@SuppressWarnings("unchecked")
private <T> PersistRequestBean<T> createRequest(T bean, Transaction t, Object parentBean) {
private <T> PersistRequestBean<T> createRequest(T bean, Transaction t, Object parentBean, PersistRequest.Type type) {
BeanManager<T> mgr = getBeanManager(bean);
if (mgr == null) {
throw new PersistenceException(errNotRegistered(bean.getClass()));
}
return (PersistRequestBean<T>) createRequest(bean, t, parentBean, mgr);
return (PersistRequestBean<T>) createRequest(bean, t, parentBean, mgr, type);
}
private String errNotRegistered(Class<?> beanClass) {
@@ -1313,9 +1218,9 @@ public final class DefaultPersister implements Persister {
* perform an insert, update or delete.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private PersistRequestBean<?> createRequest(Object bean, Transaction t, Object parentBean, BeanManager<?> mgr) {
private PersistRequestBean<?> createRequest(Object bean, Transaction t, Object parentBean, BeanManager<?> mgr, PersistRequest.Type type) {
return new PersistRequestBean(server, bean, parentBean, mgr, (SpiTransaction) t, persistExecute);
return new PersistRequestBean(server, bean, parentBean, mgr, (SpiTransaction) t, persistExecute, type);
}
/**
@@ -3,6 +3,7 @@ package com.avaje.ebeaninternal.server.persist;
import java.util.ArrayList;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.api.SpiQuery;
import com.avaje.ebeaninternal.api.SpiTransaction;
@@ -29,7 +30,7 @@ public class DeleteUnloadedForeignKeys {
private final PersistRequestBean<?> request;
private Object beanWithForeignKeys;
private EntityBean beanWithForeignKeys;
public DeleteUnloadedForeignKeys(SpiEbeanServer server, PersistRequestBean<?> request) {
this.server = server;
@@ -70,7 +71,7 @@ public class DeleteUnloadedForeignKeys {
if (t.isLogSummary()) {
t.logSummary("-- Ebean fetching foreign key values for delete of " + descriptor.getName() + " id:" + id);
}
beanWithForeignKeys = server.findUnique(q, t);
beanWithForeignKeys = (EntityBean)server.findUnique(q, t);
}
/**
@@ -84,7 +85,7 @@ public class DeleteUnloadedForeignKeys {
Object detailBean = prop.getValue(beanWithForeignKeys);
// if bean exists with a unique id then delete it
if (detailBean != null && prop.hasId(detailBean)) {
if (detailBean != null && prop.hasId((EntityBean)detailBean)) {
server.delete(detailBean, request.getTransaction());
}
}
@@ -56,19 +56,9 @@ public class DeleteHandler extends DmlHandler {
// Deletes the bean from the PersistenceContext
persistRequest.postDelete();
}
@Override
public boolean isIncluded(BeanProperty prop) {
return prop.isDbUpdatable() && super.isIncluded(prop);
}
@Override
public boolean isIncludedWhere(BeanProperty prop) {
return prop.isDbUpdatable() && (loadedProps == null || loadedProps.contains(prop.getName()));
}
public void registerDerivedRelationship(DerivedRelationshipData assocBean) {
throw new RuntimeException("Never called on delete");
}
public void registerDerivedRelationship(DerivedRelationshipData assocBean) {
throw new RuntimeException("Never called on delete");
}
}
@@ -1,9 +1,9 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.Set;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
@@ -23,21 +23,17 @@ public final class DeleteMeta {
private final Bindable version;
private final Bindable all;
private final String tableName;
private final boolean emptyStringAsNull;
public DeleteMeta(boolean emptyStringAsNull, BeanDescriptor<?> desc, BindableId id, Bindable version, Bindable all) {
public DeleteMeta(boolean emptyStringAsNull, BeanDescriptor<?> desc, BindableId id, Bindable version) {
this.emptyStringAsNull = emptyStringAsNull;
this.tableName = desc.getBaseTable();
this.id = id;
this.version = version;
this.all = all;
sqlNone = genSql(ConcurrencyMode.NONE);
sqlVersion = genSql(ConcurrencyMode.VERSION);
this.sqlNone = genSql(ConcurrencyMode.NONE);
this.sqlVersion = genSql(ConcurrencyMode.VERSION);
}
public boolean isEmptyStringAsNull() {
@@ -56,18 +52,13 @@ public final class DeleteMeta {
*/
public void bind(PersistRequestBean<?> persist, DmlHandler bind) throws SQLException {
Object bean = persist.getBean();
EntityBean bean = persist.getEntityBean();
id.dmlBind(bind, false, bean);
id.dmlBind(bind, bean);
switch (persist.getConcurrencyMode()) {
case VERSION:
version.dmlBind(bind, false, bean);
break;
case ALL:
Object oldBean = persist.getOldValues();
all.dmlBindWhere(bind, true, oldBean);
version.dmlBind(bind, bean);
break;
default:
@@ -91,9 +82,6 @@ public final class DeleteMeta {
case VERSION:
return sqlVersion;
case ALL:
return genDynamicWhere(request.getLoadedProperties(), request.getOldValues());
default:
throw new RuntimeException("Invalid mode " + request.determineConcurrencyMode());
}
@@ -109,37 +97,15 @@ public final class DeleteMeta {
request.append(" where ");
request.setWhereIdMode();
id.dmlAppend(request, false);
id.dmlAppend(request);
if (ConcurrencyMode.VERSION.equals(conMode)) {
if (version == null) {
return null;
}
version.dmlAppend(request, false);
} else if (ConcurrencyMode.ALL.equals(conMode)) {
throw new RuntimeException("Never called for ConcurrencyMode.ALL");
version.dmlAppend(request);
}
return request.toString();
}
/**
* Generate the sql dynamically for where using IS NULL for binding null
* values.
*/
private String genDynamicWhere(Set<String> includedProps, Object oldBean) throws SQLException {
// always has a preceding id property(s) so the first
// option is always ' and ' and not blank.
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringAsNull, includedProps, oldBean);
request.append(sqlNone);
request.setWhereMode();
all.dmlWhere(request, true, oldBean);
return request.toString();
}
@@ -4,11 +4,13 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.OptimisticLockException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.core.PstmtBatch;
@@ -18,8 +20,6 @@ import com.avaje.ebeaninternal.server.persist.BatchedPstmtHolder;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableRequest;
import com.avaje.ebeaninternal.server.transaction.TransactionManager;
import com.avaje.ebeaninternal.server.type.DataBind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class for Handler implementations.
@@ -35,8 +35,6 @@ public abstract class DmlHandler implements PersistHandler, BindableRequest {
protected final StringBuilder bindLog;
protected final Set<String> loadedProps;
protected final SpiTransaction transaction;
protected final boolean emptyStringToNull;
@@ -52,12 +50,9 @@ public abstract class DmlHandler implements PersistHandler, BindableRequest {
protected ArrayList<UpdateGenValue> updateGenValues;
private Set<String> additionalProps;
protected DmlHandler(PersistRequestBean<?> persistRequest, boolean emptyStringToNull) {
this.persistRequest = persistRequest;
this.emptyStringToNull = emptyStringToNull;
this.loadedProps = persistRequest.getLoadedProperties();
this.transaction = persistRequest.getTransaction();
this.logLevelSql = transaction.isLogSql();
if (logLevelSql) {
@@ -148,20 +143,6 @@ public abstract class DmlHandler implements PersistHandler, BindableRequest {
}
}
public boolean isIncluded(BeanProperty prop) {
return (loadedProps == null || loadedProps.contains(prop.getName()));
}
public boolean isIncludedWhere(BeanProperty prop) {
if (prop.isDbEncrypted()) {
// update without a version property ...
// for encrypted properties only include if it was
// also an updated/modified property
return isIncluded(prop);
}
return prop.isDbUpdatable() && (loadedProps == null || loadedProps.contains(prop.getName()));
}
/**
* Bind a raw value. Used to bind the discriminator column.
*/
@@ -194,80 +175,36 @@ public abstract class DmlHandler implements PersistHandler, BindableRequest {
/**
* Bind the value to the preparedStatement.
*/
public Object bind(Object value, BeanProperty prop, String propName, boolean bindNull)
throws SQLException {
return bindInternal(logLevelSql, value, prop, propName, bindNull);
public Object bind(Object value, BeanProperty prop, String propName) throws SQLException {
return bindInternal(logLevelSql, value, prop, propName);
}
/**
* Bind the value to the preparedStatement without logging.
*/
public Object bindNoLog(Object value, BeanProperty prop, String propName, boolean bindNull)
throws SQLException {
return bindInternal(false, value, prop, propName, bindNull);
public Object bindNoLog(Object value, BeanProperty prop, String propName) throws SQLException {
return bindInternal(false, value, prop, propName);
}
private Object bindInternal(boolean log, Object value, BeanProperty prop, String propName,
boolean bindNull) throws SQLException {
private Object bindInternal(boolean log, Object value, BeanProperty prop, String propName) throws SQLException {
if (!bindNull) {
if (emptyStringToNull && (value instanceof String) && ((String) value).length() == 0) {
// support Oracle conversion of empty string to null
// value = prop.getDbNullValue(value);
value = null;
}
}
if (!bindNull && value == null) {
// where will have IS NULL clause so don't actually bind
if (log) {
bindLog.append("null, ");
}
} else {
if (log) {
if (prop.isLob()) {
bindLog.append("[LOB]");
} else {
String sv = String.valueOf(value);
if (sv.length() > 50) {
sv = sv.substring(0, 47) + "...";
}
bindLog.append(sv);
if (log) {
if (prop.isLob()) {
bindLog.append("[LOB]");
} else {
String sv = String.valueOf(value);
if (sv.length() > 50) {
sv = sv.substring(0, 47) + "...";
}
bindLog.append(",");
bindLog.append(sv);
}
// do the actual binding to PreparedStatement
prop.bind(dataBind, value);
bindLog.append(",");
}
// do the actual binding to PreparedStatement
prop.bind(dataBind, value);
return value;
}
/**
* For generated properties set on insert register as additional loaded
* properties if required.
*/
public final void registerAdditionalProperty(String propertyName) {
if (loadedProps != null && !loadedProps.contains(propertyName)) {
if (additionalProps == null) {
additionalProps = new HashSet<String>();
}
additionalProps.add(propertyName);
}
}
/**
* Set any additional (generated) properties to the set of loaded properties
* if required.
*/
protected void setAdditionalProperties() {
if (additionalProps != null) {
// additional generated properties set on insert
// added to the set of loaded properties
additionalProps.addAll(loadedProps);
persistRequest.setLoadedProps(additionalProps);
}
}
/**
* Register a generated value on a update. This can not be set to the bean
* until after the where clause has been bound for concurrency checking.
@@ -277,12 +214,11 @@ public abstract class DmlHandler implements PersistHandler, BindableRequest {
* generation.
* </p>
*/
public void registerUpdateGenValue(BeanProperty prop, Object bean, Object value) {
public void registerUpdateGenValue(BeanProperty prop, EntityBean bean, Object value) {
if (updateGenValues == null) {
updateGenValues = new ArrayList<UpdateGenValue>();
}
updateGenValues.add(new UpdateGenValue(prop, bean, value));
registerAdditionalProperty(prop.getName());
}
/**
@@ -303,6 +239,7 @@ public abstract class DmlHandler implements PersistHandler, BindableRequest {
*/
protected PreparedStatement getPstmt(SpiTransaction t, String sql, boolean genKeys)
throws SQLException {
Connection conn = t.getInternalConnection();
if (genKeys) {
// the Id generated is always the first column
@@ -353,11 +290,11 @@ public abstract class DmlHandler implements PersistHandler, BindableRequest {
private final BeanProperty property;
private final Object bean;
private final EntityBean bean;
private final Object value;
private UpdateGenValue(BeanProperty property, Object bean, Object value) {
private UpdateGenValue(BeanProperty property, EntityBean bean, Object value) {
this.property = property;
this.bean = bean;
this.value = value;
@@ -15,8 +15,4 @@ public enum DmlMode {
*/
UPDATE,
/**
* The Update or Delete WHERE.
*/
WHERE
}
@@ -1,7 +1,6 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.util.Set;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
@@ -15,10 +14,8 @@ public class GenerateDmlRequest {
private final StringBuilder sb = new StringBuilder(100);
private final Set<String> includeProps;
private final Set<String> includeWhereProps;
private final Object oldValues;
private final EntityBeanIntercept ebi;
private final boolean changesOnly;
private StringBuilder insertBindBuffer;
@@ -28,29 +25,21 @@ public class GenerateDmlRequest {
private int insertMode;
private int bindColumnCount;
/**
* Create with includeWhereProps same as includeProps.
*/
public GenerateDmlRequest(boolean emptyStringAsNull, Set<String> includeProps, Object oldValues) {
this(emptyStringAsNull, includeProps, includeProps, oldValues);
}
/**
* Create from a PersistRequestBean.
*/
public GenerateDmlRequest(boolean emptyStringAsNull, Set<String> includeProps, Set<String> includeWhereProps, Object oldValues) {
public GenerateDmlRequest(boolean emptyStringAsNull, EntityBeanIntercept ebi, boolean changesOnly) {//, Object oldValues) {
this.emptyStringAsNull = emptyStringAsNull;
this.includeProps = includeProps;
this.includeWhereProps = includeWhereProps;
this.oldValues = oldValues;
this.ebi = ebi;
this.changesOnly = changesOnly;
}
/**
* Create for generating standard all properties DML/SQL.
*/
public GenerateDmlRequest(boolean emptyStringAsNull) {
this(emptyStringAsNull, null, null, null);
this(emptyStringAsNull, null, false);
}
public GenerateDmlRequest append(String s) {
@@ -66,14 +55,21 @@ public class GenerateDmlRequest {
* Return true if this property should be included in the set clause.
*/
public boolean isIncluded(BeanProperty prop) {
return (includeProps == null || includeProps.contains(prop.getName()));
if (ebi == null) {
return true;
}
if (changesOnly) {
return ebi.isDirtyProperty(prop.getPropertyIndex());
} else {
return ebi.isLoadedProperty(prop.getPropertyIndex());
}
}
/**
* Return true if this property should be included in the where clause.
*/
public boolean isIncludedWhere(BeanProperty prop) {
return (includeWhereProps == null || includeWhereProps.contains(prop.getName()));
return ebi == null || ebi.isLoadedProperty(prop.getPropertyIndex());
}
public void appendColumnIsNull(String column) {
@@ -81,28 +77,29 @@ public class GenerateDmlRequest {
}
public void appendColumn(String column) {
String bind = (insertMode > 0) ? "?" : "=?";
appendColumn(column, bind);
//String bind = (insertMode > 0) ? "?" : "=?";
appendColumn(column, "?");
}
public void appendColumn(String column, String suffik) {
appendColumn(column, "", suffik);
public void appendColumn(String column, String bind) {
appendColumn(column, "", bind);
}
public void appendColumn(String column, String expr, String suffik) {
public void appendColumn(String column, String expr, String bind) {
++bindColumnCount;
sb.append(prefix);
sb.append(column);
sb.append(expr);
//sb.append(expr);
if (insertMode > 0) {
if (insertMode++ > 1) {
insertBindBuffer.append(",");
}
insertBindBuffer.append(suffik);
insertBindBuffer.append(bind);
} else {
sb.append(suffik);
sb.append("=");
sb.append(bind);
}
if (prefix2 != null) {
@@ -145,8 +142,4 @@ public class GenerateDmlRequest {
this.prefix2 = ", ";
}
public Object getOldValues() {
return oldValues;
}
}
@@ -5,14 +5,17 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.List;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import com.avaje.ebean.EbeanServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.Message;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
@@ -20,8 +23,6 @@ import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.persist.DmlUtil;
import com.avaje.ebeaninternal.server.type.DataBind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Insert bean handler.
@@ -59,18 +60,13 @@ public class InsertHandler extends DmlHandler {
this.concatinatedKey = meta.isConcatinatedKey();
}
@Override
public boolean isIncluded(BeanProperty prop) {
return prop.isDbInsertable() && (super.isIncluded(prop));
}
/**
* Generate and bind the insert statement.
*/
public void bind() throws SQLException {
BeanDescriptor<?> desc = persistRequest.getBeanDescriptor();
Object bean = persistRequest.getBean();
EntityBean bean = persistRequest.getEntityBean();
Object idValue = desc.getId(bean);
@@ -142,20 +138,28 @@ public class InsertHandler extends DmlHandler {
}
checkRowCount(rc);
setAdditionalProperties();
//setAdditionalProperties();
executeDerivedRelationships();
persistRequest.postInsert();
}
protected void executeDerivedRelationships() {
List<DerivedRelationshipData> derivedRelationships = persistRequest.getDerivedRelationships();
if (derivedRelationships != null) {
SpiEbeanServer ebeanServer = (SpiEbeanServer)persistRequest.getEbeanServer();
for (int i = 0; i < derivedRelationships.size(); i++) {
DerivedRelationshipData derivedRelationshipData = derivedRelationships.get(i);
EbeanServer ebeanServer = persistRequest.getEbeanServer();
HashSet<String> updateProps = new HashSet<String>();
updateProps.add(derivedRelationshipData.getLogicalName());
ebeanServer.update(derivedRelationshipData.getBean(), updateProps, transaction, false, true);
BeanDescriptor<?> beanDescriptor = ebeanServer.getBeanDescriptor(derivedRelationshipData.getBean().getClass());
BeanProperty prop = beanDescriptor.getBeanProperty(derivedRelationshipData.getLogicalName());
EntityBean entityBean = (EntityBean)derivedRelationshipData.getBean();
entityBean._ebean_getIntercept().markPropertyAsChanged(prop.getPropertyIndex());
ebeanServer.update(entityBean, transaction);
}
}
}
@@ -1,8 +1,8 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.Set;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
@@ -53,7 +53,7 @@ public final class InsertMeta {
this.all = all;
this.shadowFKey = shadowFKey;
this.sqlWithId = genSql(false, null);
this.sqlWithId = genSql(false);
// only available for single Id property
if (id.isConcatenated()) {
@@ -68,7 +68,7 @@ public final class InsertMeta {
// insert sql for db identity or sequence insert
this.concatinatedKey = false;
this.identityDbColumns = new String[]{id.getIdentityColumn()};
this.sqlNullId = genSql(true, null);
this.sqlNullId = genSql(true);
this.supportsGetGeneratedKeys = dbPlatform.getDbIdentity().isSupportsGetGeneratedKeys();
this.selectLastInsertedId = desc.getSelectLastInsertedId();
}
@@ -131,18 +131,18 @@ public final class InsertMeta {
/**
* Bind the request based on whether the id value(s) are null.
*/
public void bind(DmlHandler request, Object bean, boolean withId) throws SQLException {
public void bind(DmlHandler request, EntityBean bean, boolean withId) throws SQLException {
if (withId) {
id.dmlBind(request, false, bean);
id.dmlBind(request, bean);
}
if (shadowFKey != null){
shadowFKey.dmlBind(request, false, bean);
shadowFKey.dmlBind(request, bean);
}
if (discriminator != null){
discriminator.dmlBind(request, false, bean);
discriminator.dmlBind(request, bean);
}
all.dmlBind(request, false, bean);
all.dmlBind(request, bean);
}
/**
@@ -157,27 +157,27 @@ public final class InsertMeta {
}
}
private String genSql(boolean nullId, Set<String> loadedProps) {
private String genSql(boolean nullId) {
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringToNull, loadedProps, null);
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringToNull, null, true);
request.setInsertSetMode();
request.append("insert into ").append(tableName);
request.append(" (");
if (!nullId) {
id.dmlInsert(request, false);
id.dmlAppend(request);
}
if (shadowFKey != null){
shadowFKey.dmlInsert(request, false);
shadowFKey.dmlAppend(request);
}
if (discriminator != null){
discriminator.dmlInsert(request, false);
discriminator.dmlAppend(request);
}
all.dmlInsert(request, false);
all.dmlAppend(request);
request.append(") values (");
request.append(request.getInsertBindBuffer());
@@ -66,16 +66,9 @@ public class MetaFactory {
Bindable ver = versionFact.create(desc);
List<Bindable> allList = new ArrayList<Bindable>();
baseFact.create(allList, desc, DmlMode.WHERE, false);
embeddedFact.create(allList, desc, DmlMode.WHERE, false);
assocOneFact.create(allList, desc, DmlMode.WHERE);
BindableList setBindable = new BindableList(setList);
BindableList allBindable = new BindableList(allList);
return new UpdateMeta(emptyStringAsNull, desc, setBindable, id, ver, allBindable);
return new UpdateMeta(emptyStringAsNull, desc, setBindable, id, ver);
}
/**
@@ -87,15 +80,7 @@ public class MetaFactory {
Bindable ver = versionFact.create(desc);
List<Bindable> allList = new ArrayList<Bindable>();
baseFact.create(allList, desc, DmlMode.WHERE, false);
embeddedFact.create(allList, desc, DmlMode.WHERE, false);
assocOneFact.create(allList, desc, DmlMode.WHERE);
Bindable allBindable = new BindableList(allList);
return new DeleteMeta(emptyStringAsNull, desc, id, ver, allBindable);
return new DeleteMeta(emptyStringAsNull, desc, id, ver);
}
/**
@@ -10,7 +10,6 @@ import com.avaje.ebeaninternal.api.DerivedRelationshipData;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
@@ -18,10 +17,7 @@ import com.avaje.ebeaninternal.server.type.DataBind;
*/
public class UpdateHandler extends DmlHandler {
private final UpdateMeta meta;
private Set<String> updatedProperties;
private boolean emptySetClause;
@@ -41,8 +37,6 @@ public class UpdateHandler extends DmlHandler {
emptySetClause = true;
return;
}
updatedProperties = updatePlan.getProperties();
sql = updatePlan.getSql();
@@ -79,18 +73,11 @@ public class UpdateHandler extends DmlHandler {
if (!emptySetClause){
int rowCount = dataBind.executeUpdate();
checkRowCount(rowCount);
setAdditionalProperties();
}
}
@Override
public boolean isIncluded(BeanProperty prop) {
return prop.isDbUpdatable() && (updatedProperties == null || updatedProperties.contains(prop.getName()));
}
public void registerDerivedRelationship(DerivedRelationshipData derivedRelationship) {
persistRequest.getTransaction().registerDerivedRelationship(derivedRelationship);
}
public void registerDerivedRelationship(DerivedRelationshipData derivedRelationship) {
persistRequest.getTransaction().registerDerivedRelationship(derivedRelationship);
}
}
@@ -3,14 +3,14 @@ package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.persistence.PersistenceException;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableId;
import com.avaje.ebeaninternal.server.persist.dmlbind.BindableList;
@@ -28,7 +28,6 @@ public final class UpdateMeta {
private final BindableList set;
private final BindableId id;
private final Bindable version;
private final Bindable all;
private final String tableName;
@@ -37,20 +36,18 @@ public final class UpdateMeta {
private final boolean emptyStringAsNull;
public UpdateMeta(boolean emptyStringAsNull, BeanDescriptor<?> desc, BindableList set, BindableId id, Bindable version, Bindable all) {
public UpdateMeta(boolean emptyStringAsNull, BeanDescriptor<?> desc, BindableList set, BindableId id, Bindable version) {
this.emptyStringAsNull = emptyStringAsNull;
this.tableName = desc.getBaseTable();
this.set = set;
this.id = id;
this.version = version;
this.all = all;
this.sqlNone = genSql(ConcurrencyMode.NONE, null, null);
this.sqlVersion = genSql(ConcurrencyMode.VERSION, null, null);
this.sqlNone = genSql(ConcurrencyMode.NONE, null, set);
this.sqlVersion = genSql(ConcurrencyMode.VERSION, null, set);
this.modeNoneUpdatePlan = new UpdatePlan(ConcurrencyMode.NONE, sqlNone, set);
this.modeVersionUpdatePlan = new UpdatePlan(ConcurrencyMode.VERSION, sqlVersion, set);
}
/**
@@ -72,19 +69,15 @@ public final class UpdateMeta {
*/
public void bind(PersistRequestBean<?> persist, DmlHandler bind, SpiUpdatePlan updatePlan) throws SQLException {
Object bean = persist.getBean();
EntityBean bean = persist.getEntityBean();
updatePlan.bindSet(bind, bean);
id.dmlBind(bind, false, bean);
id.dmlBind(bind, bean);
switch (persist.getConcurrencyMode()) {
case VERSION:
version.dmlBind(bind, false, bean);
break;
case ALL:
Object oldBean = persist.getOldValues();
all.dmlBindWhere(bind, true, oldBean);
version.dmlBind(bind, bean);
break;
default:
@@ -110,14 +103,6 @@ public final class UpdateMeta {
case VERSION:
return modeVersionUpdatePlan;
case ALL:
Object oldValues = request.getOldValues();
if (oldValues == null) {
throw new PersistenceException("OldValues are null?");
}
String sql = genDynamicWhere(request.getUpdatedProperties(), request.getLoadedProperties(), oldValues);
return new UpdatePlan(ConcurrencyMode.ALL, sql, set);
default:
throw new RuntimeException("Invalid mode " + mode);
}
@@ -125,26 +110,23 @@ public final class UpdateMeta {
private SpiUpdatePlan getDynamicUpdatePlan(ConcurrencyMode mode, PersistRequestBean<?> persistRequest) {
Set<String> updatedProps = persistRequest.getUpdatedProperties();
if (ConcurrencyMode.ALL.equals(mode)) {
// due to is null in where clause we won't bother trying to
// cache plans for ConcurrencyMode.ALL
String sql = genSql(mode, persistRequest, null);
if (sql == null) {
// changed properties must have been updatable=false
return UpdatePlan.EMPTY_SET_CLAUSE;
} else {
return new UpdatePlan(null, mode, sql, set, updatedProps);
// we can use a cached UpdatePlan for the changed properties
EntityBeanIntercept ebi = persistRequest.getEntityBeanIntercept();
int hash = ebi.getDirtyPropertyHash();
BeanDescriptor<?> beanDescriptor = persistRequest.getBeanDescriptor();
BeanProperty versionProperty = beanDescriptor.getVersionProperty();
if (versionProperty != null) {
if (ebi.isLoadedProperty(versionProperty.getPropertyIndex())) {
hash = hash * 31 + 7;
}
}
// we can use a cached UpdatePlan for the changed properties
int hash = mode.hashCode();
hash = hash * 31 + (updatedProps == null ? 0 : updatedProps.hashCode());
Integer key = Integer.valueOf(hash);
BeanDescriptor<?> beanDescriptor = persistRequest.getBeanDescriptor();
SpiUpdatePlan updatePlan = beanDescriptor.getUpdatePlan(key);
if (updatePlan != null) {
return updatePlan;
@@ -154,18 +136,13 @@ public final class UpdateMeta {
// build a bindableList that only contains the changed properties
List<Bindable> list = new ArrayList<Bindable>();
if (updatedProps == null) {
// update all the properties
set.addAll(list);
} else {
set.addChanged(persistRequest, list);
}
set.addToUpdate(persistRequest, list);
BindableList bindableList = new BindableList(list);
// build the SQL for this update statement
String sql = genSql(mode, persistRequest, bindableList);
updatePlan = new UpdatePlan(key, mode, sql, bindableList, null);
updatePlan = new UpdatePlan(key, mode, sql, bindableList);
// add the UpdatePlan to the cache
beanDescriptor.putUpdatePlan(key, updatePlan);
@@ -188,12 +165,8 @@ public final class UpdateMeta {
request.append("update ").append(tableName).append(" set ");
request.setUpdateSetMode();
if (bindableList != null) {
bindableList.dmlAppend(request, false);
} else {
set.dmlAppend(request, true);
}
bindableList.dmlAppend(request);
if (request.getBindColumnCount() == 0) {
// update properties must have been updatable=false
// with the result that nothing is in the set clause
@@ -203,38 +176,15 @@ public final class UpdateMeta {
request.append(" where ");
request.setWhereIdMode();
id.dmlAppend(request, false);
id.dmlAppend(request);
if (ConcurrencyMode.VERSION.equals(conMode)) {
if (version == null) {
return null;
}
version.dmlAppend(request, false);
} else if (ConcurrencyMode.ALL.equals(conMode)) {
all.dmlWhere(request, true, request.getOldValues());
version.dmlAppend(request);
}
return request.toString();
}
/**
* Generate the sql dynamically for where using IS NULL for binding null
* values.
*/
private String genDynamicWhere(Set<String> loadedProps, Set<String> whereProps, Object oldBean) {
// always has a preceding id property(s) so the first
// option is always ' and ' and not blank.
GenerateDmlRequest request = new GenerateDmlRequest(emptyStringAsNull, loadedProps, whereProps, oldBean);
request.append(sqlNone);
request.setWhereMode();
all.dmlWhere(request, true, oldBean);
return request.toString();
}
@@ -1,9 +1,9 @@
package com.avaje.ebeaninternal.server.persist.dml;
import java.sql.SQLException;
import java.util.Set;
import com.avaje.ebean.annotation.ConcurrencyMode;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.SpiUpdatePlan;
import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
@@ -15,12 +15,12 @@ import com.avaje.ebeaninternal.server.persist.dmlbind.Bindable;
*/
public class UpdatePlan implements SpiUpdatePlan {
/**
* Special plan used when there is nothing in the set clause and the update
* should in fact be skipped. Occurs when the updated properties have
* updatable=false in their deployment.
*/
public static final UpdatePlan EMPTY_SET_CLAUSE = new UpdatePlan();
/**
* Special plan used when there is nothing in the set clause and the update
* should in fact be skipped. Occurs when the updated properties have
* updatable=false in their deployment.
*/
public static final UpdatePlan EMPTY_SET_CLAUSE = new UpdatePlan();
private final Integer key;
@@ -30,10 +30,6 @@ public class UpdatePlan implements SpiUpdatePlan {
private final Bindable set;
private final Set<String> properties;
private final boolean checkIncludes;
private final long timeCreated;
private final boolean emptySetClause;
@@ -45,22 +41,19 @@ public class UpdatePlan implements SpiUpdatePlan {
*/
public UpdatePlan(ConcurrencyMode mode, String sql, Bindable set) {
this(null, mode, sql, set, null);
this(null, mode, sql, set);
}
/**
* Create a cachable UpdatePlan with a given key.
*/
public UpdatePlan(Integer key, ConcurrencyMode mode, String sql,
Bindable set, Set<String> properties) {
public UpdatePlan(Integer key, ConcurrencyMode mode, String sql, Bindable set) {
this.emptySetClause = false;
this.emptySetClause = (sql == null);
this.key = key;
this.mode = mode;
this.sql = sql;
this.set = set;
this.properties = properties;
this.checkIncludes = properties != null;
this.timeCreated = System.currentTimeMillis();
}
@@ -73,8 +66,6 @@ public class UpdatePlan implements SpiUpdatePlan {
this.mode = ConcurrencyMode.NONE;
this.sql = null;
this.set = null;
this.properties = null;
this.checkIncludes = false;
this.timeCreated = 0;
}
@@ -86,9 +77,9 @@ public class UpdatePlan implements SpiUpdatePlan {
/**
* Run the prepared statement binding for the 'update set' properties.
*/
public void bindSet(DmlHandler bind, Object bean) throws SQLException {
public void bindSet(DmlHandler bind, EntityBean bean) throws SQLException {
set.dmlBind(bind, checkIncludes, bean);
set.dmlBind(bind, bean);
// not strictly 'thread safe' but object assignment is atomic
Long touched = Long.valueOf(System.currentTimeMillis());
@@ -139,15 +130,4 @@ public class UpdatePlan implements SpiUpdatePlan {
return set;
}
/**
* Return the set of changed properties.
* <p>
* This can return null when all properties in the set are being bound in
* the update statement.
* </p>
*/
public Set<String> getProperties() {
return properties;
}
}
@@ -3,6 +3,7 @@ package com.avaje.ebeaninternal.server.persist.dmlbind;
import java.sql.SQLException;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.persist.dml.GenerateDmlRequest;
@@ -25,32 +26,17 @@ public interface Bindable {
* For Updates including only changed properties add the Bindable to the
* list if it should be included in the 'update set'.
*/
public void addChanged(PersistRequestBean<?> request, List<Bindable> list);
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list);
/**
* append sql to the buffer with prefix and suffix options.
*/
public void dmlInsert(GenerateDmlRequest request, boolean checkIncludes);
/**
* append sql to the buffer with prefix and suffix options.
*/
public void dmlAppend(GenerateDmlRequest request, boolean checkIncludes);
/**
* For WHERE clauses append sql to the buffer with prefix and suffix
* options. These need to take into account binding of null values.
*/
public void dmlWhere(GenerateDmlRequest request, boolean checkIncludes, Object bean);
public void dmlAppend(GenerateDmlRequest request);
/**
* Bind given the request and bean. The bean could be the oldValues bean
* when binding a update or delete where clause with ALL concurrency mode.
*/
public void dmlBind(BindableRequest request, boolean checkIncludes, Object bean)
throws SQLException;
public void dmlBindWhere(BindableRequest request, boolean checkIncludes, Object bean)
throws SQLException;
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException;
}
@@ -3,6 +3,7 @@ package com.avaje.ebeaninternal.server.persist.dmlbind;
import java.sql.SQLException;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
@@ -14,75 +15,42 @@ import com.avaje.ebeaninternal.server.persist.dml.GenerateDmlRequest;
*/
public class BindableAssocOne implements Bindable {
private final BeanPropertyAssocOne<?> assocOne;
private final BeanPropertyAssocOne<?> assocOne;
private final ImportedId importedId;
private final ImportedId importedId;
public BindableAssocOne(BeanPropertyAssocOne<?> assocOne) {
this.assocOne = assocOne;
this.importedId = assocOne.getImportedId();
public BindableAssocOne(BeanPropertyAssocOne<?> assocOne) {
this.assocOne = assocOne;
this.importedId = assocOne.getImportedId();
}
public String toString() {
return "BindableAssocOne " + assocOne;
}
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
if (request.isAddToUpdate(assocOne)) {
list.add(this);
}
}
public String toString() {
return "BindableAssocOne " + assocOne;
}
public void addChanged(PersistRequestBean<?> request, List<Bindable> list) {
if (request.hasChanged(assocOne)) {
list.add(this);
}
}
public void dmlInsert(GenerateDmlRequest request, boolean checkIncludes) {
dmlAppend(request, checkIncludes);
}
public void dmlAppend(GenerateDmlRequest request, boolean checkIncludes) {
if (checkIncludes && !request.isIncluded(assocOne)) {
return;
}
importedId.dmlAppend(request);
}
/**
* Used for dynamic where clause generation.
*/
public void dmlWhere(GenerateDmlRequest request, boolean checkIncludes, Object bean) {
if (checkIncludes && !request.isIncludedWhere(assocOne)) {
return;
}
Object assocBean = assocOne.getValue(bean);
importedId.dmlWhere(request, assocBean);
}
public void dmlBind(BindableRequest request, boolean checkIncludes, Object bean) throws SQLException {
if (checkIncludes && !request.isIncluded(assocOne)) {
return;
}
dmlBind(request, bean, true);
}
public void dmlBindWhere(BindableRequest request, boolean checkIncludes, Object bean) throws SQLException {
if (checkIncludes && !request.isIncludedWhere(assocOne)) {
return;
}
dmlBind(request, bean, false);
}
private void dmlBind(BindableRequest request, Object bean, boolean bindNull)
throws SQLException {
Object assocBean = assocOne.getValue(bean);
Object boundValue = importedId.bind(request, assocBean, bindNull);
if (bindNull && boundValue == null && assocBean != null){
// this is the scenario for a derived foreign key
// which will require an additional update
// register for post insert of assocBean
// update of bean set ... importedId.getLogicalName();
// value of assocBean.getId
DerivedRelationshipData d = new DerivedRelationshipData(assocBean, assocOne.getName(), bean);
request.registerDerivedRelationship(d);
}
public void dmlAppend(GenerateDmlRequest request) {
importedId.dmlAppend(request);
}
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
EntityBean assocBean = (EntityBean)assocOne.getValue(bean);
Object boundValue = importedId.bind(request, assocBean);
if (boundValue == null && assocBean != null) {
// this is the scenario for a derived foreign key
// which will require an additional update
// register for post insert of assocBean
// update of bean set ... importedId.getLogicalName();
// value of assocBean.getId
DerivedRelationshipData d = new DerivedRelationshipData(assocBean, assocOne.getName(), bean);
request.registerDerivedRelationship(d);
}
}
}
@@ -4,6 +4,7 @@ import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyCompound;
import com.avaje.ebeaninternal.server.persist.dml.GenerateDmlRequest;
@@ -26,62 +27,27 @@ public class BindableCompound implements Bindable {
return "BindableCompound " + compound + " items:" + Arrays.toString(items);
}
public void dmlInsert(GenerateDmlRequest request, boolean checkIncludes) {
dmlAppend(request, checkIncludes);
}
public void dmlAppend(GenerateDmlRequest request, boolean checkIncludes) {
if (checkIncludes && !request.isIncluded(compound)) {
return;
}
public void dmlAppend(GenerateDmlRequest request) {
for (int i = 0; i < items.length; i++) {
items[i].dmlAppend(request, false);
items[i].dmlAppend(request);
}
}
/**
* Used for dynamic where clause generation.
*/
public void dmlWhere(GenerateDmlRequest request, boolean checkIncludes, Object origBean) {
if (checkIncludes && !request.isIncludedWhere(compound)) {
return;
}
Object valueObject = compound.getValue(origBean);
for (int i = 0; i < items.length; i++) {
items[i].dmlWhere(request, false, valueObject);
}
}
public void addChanged(PersistRequestBean<?> request, List<Bindable> list) {
if (request.hasChanged(compound)) {
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
if (request.isAddToUpdate(compound)) {
list.add(this);
}
}
public void dmlBind(BindableRequest bindRequest, boolean checkIncludes, Object bean) throws SQLException {
if (checkIncludes && !bindRequest.isIncluded(compound)) {
return;
}
public void dmlBind(BindableRequest bindRequest, EntityBean bean) throws SQLException {
Object valueObject = compound.getValue(bean);
for (int i = 0; i < items.length; i++) {
items[i].dmlBind(bindRequest, false, valueObject);
}
throw new RuntimeException("This is broken, need to break out the scalar values!!");
//Object valueObject = compound.getValue(bean);
//for (int i = 0; i < items.length; i++) {
// items[i].dmlBind(bindRequest, valueObject);
//}
}
public void dmlBindWhere(BindableRequest bindRequest, boolean checkIncludes, Object bean) throws SQLException {
if (checkIncludes && !bindRequest.isIncludedWhere(compound)) {
return;
}
Object valueObject = compound.getValue(bean);
for (int i = 0; i < items.length; i++) {
items[i].dmlBindWhere(bindRequest, false, valueObject);
}
}
}
@@ -5,6 +5,7 @@ import java.util.List;
import javax.persistence.PersistenceException;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
import com.avaje.ebeaninternal.server.deploy.InheritInfo;
import com.avaje.ebeaninternal.server.persist.dml.GenerateDmlRequest;
@@ -28,31 +29,15 @@ public class BindableDiscriminator implements Bindable {
return columnName + " = " + discValue;
}
public void addChanged(PersistRequestBean<?> request, List<Bindable> list) {
public void addToUpdate(PersistRequestBean<?> request, List<Bindable> list) {
throw new PersistenceException("Never called (only for inserts)");
}
public void dmlInsert(GenerateDmlRequest request, boolean checkIncludes) {
dmlAppend(request, checkIncludes);
}
/**
* Never used in where clause.
*/
public void dmlWhere(GenerateDmlRequest request, boolean checkIncludes, Object bean) {
// never used in where
}
public void dmlAppend(GenerateDmlRequest request, boolean checkIncludes) {
public void dmlAppend(GenerateDmlRequest request) {
request.appendColumn(columnName);
}
public void dmlBind(BindableRequest bindRequest, boolean checkIncludes, Object bean) throws SQLException {
bindRequest.bind(columnName, discValue, sqlType);
}
public void dmlBindWhere(BindableRequest bindRequest, boolean checkIncludes, Object bean) throws SQLException {
public void dmlBind(BindableRequest bindRequest, EntityBean bean) throws SQLException {
bindRequest.bind(columnName, discValue, sqlType);
}

Some files were not shown because too many files have changed in this diff Show More