initial add of EbeanORM server based on v2.8.1

This commit is contained in:
rbygrave committed 2012-09-14 00:40:39 +12:00
1 parent 2b74d0f9d9
commit 96ce4c0ddf
1188 files changed
+135034

No files matched your search

@@ -0,0 +1,141 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import javax.persistence.CascadeType;
/**
* Persist info for determining if save or delete should be performed.
* <p>
* This is set to associated Beans, Table joins and List.
* </p>
*/
public class BeanCascadeInfo {
/**
* should delete cascade.
*/
boolean delete;
/**
* Should save cascade.
*/
boolean save;
/**
* Should validate cascade.
*/
boolean validate;
/**
* Set the raw deployment attribute.
*/
public void setAttribute(String attr) {
if (attr == null){
return;
}
attr = attr.toLowerCase();
delete = (attr.indexOf("delete")>-1);
if (!delete){
// same as EJB3 remove
delete = (attr.indexOf("remove")>-1);
}
save = (attr.indexOf("save")>-1);
if (!save){
// same as EJB3 persist
save = (attr.indexOf("persist")>-1);
}
if (attr.indexOf("validate")>-1){
validate = true;
}
if (attr.indexOf("all")>-1){
delete = true;
save = true;
validate = true;
}
}
public void setTypes(CascadeType[] types) {
for (int i = 0; i < types.length; i++) {
setType(types[i]);
}
}
private void setType(CascadeType type) {
if (type.equals(CascadeType.ALL)){
save = true;
delete = true;
}
if (type.equals(CascadeType.REMOVE)){
delete = true;
}
if (type.equals(CascadeType.PERSIST)){
save = true;
}
if (type.equals(CascadeType.MERGE)){
save = true;
}
if (save || delete){
validate = true;
}
}
/**
* Return true if delete should cascade.
*/
public boolean isDelete() {
return delete;
}
/**
* Set to true if delete should cascade.
*/
public void setDelete(boolean isDelete) {
this.delete = isDelete;
}
/**
* Return true if save should cascade.
*/
public boolean isSave() {
return save;
}
/**
* Set to true if save should cascade.
*/
public void setSave(boolean isUpdate) {
this.save = isUpdate;
}
/**
* Return true if validate should be cascaded.
*/
public boolean isValidate() {
return validate;
}
/**
* Set validate to cascade or not.
*/
public void setValidate(boolean isValidate) {
this.validate = isValidate;
}
}
@@ -0,0 +1,73 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.Iterator;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.InvalidValue;
import com.avaje.ebean.Query;
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.ebeaninternal.server.text.json.WriteJsonContext;
/**
* Helper functions for performing tasks on Lists Sets or Maps.
*/
public interface BeanCollectionHelp<T> {
/**
* Set the EbeanServer that owns the configuration.
*/
public void setLoader(BeanCollectionLoader loader);
/**
* Return the mechanism to add beans to the underlying collection.
* <p>
* For Map's this needs to take the mapKey.
* </p>
*/
public BeanCollectionAdd getBeanCollectionAdd(Object bc, String mapKey);
/**
* Create an empty collection of the correct type.
*/
public Object createEmpty(boolean vanilla);
/**
* Create an iterator for reading the entries.
*/
public Iterator<?> getIterator(Object collection);
/**
* Add a bean to the List Set or Map.
*/
public void add(BeanCollection<?> collection, Object bean);
/**
* Create a lazy loading proxy for a List Set or Map.
*/
public BeanCollection<T> createReference(Object parentBean, String propertyName);
/**
* Validate the List Set or Map.
*/
public ArrayList<InvalidValue> validate(Object manyValue);
/**
* Refresh the List Set or Map.
*/
public void refresh(EbeanServer server, Query<?> query, Transaction t, Object parentBean);
/**
* Apply the new refreshed BeanCollection to the appropriate property of the parent bean.
*/
public void refresh(BeanCollection<?> bc, Object parentBean);
/**
* Write the collection out as json.
*/
public void jsonWrite(WriteJsonContext ctx, String name, Object collection, boolean explicitInclude);
}
@@ -0,0 +1,49 @@
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebeaninternal.api.SpiQuery;
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
/**
* Creates Helpers specific to the type of the property (List Set or Map).
*/
public class BeanCollectionHelpFactory {
/**
* Create the helper based on the many property.
*/
public static <T> BeanCollectionHelp<T> create(BeanPropertyAssocMany<T> manyProperty) {
ManyType manyType = manyProperty.getManyType();
switch (manyType.getUnderlying()) {
case LIST:
return new BeanListHelp<T>(manyProperty);
case SET:
return new BeanSetHelp<T>(manyProperty);
case MAP:
return new BeanMapHelp<T>(manyProperty);
default:
throw new RuntimeException("Invalid type "+manyType);
}
}
public static <T> BeanCollectionHelp<T> create(OrmQueryRequest<T> request) {
SpiQuery.Type manyType = request.getQuery().getType();
if (manyType.equals(SpiQuery.Type.LIST)){
return new BeanListHelp<T>();
} else if (manyType.equals(SpiQuery.Type.SET)) {
return new BeanSetHelp<T>();
} else {
BeanDescriptor<T> target = request.getBeanDescriptor();
String mapKey = request.getQuery().getMapKey();
return new BeanMapHelp<T>(target, mapKey);
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,56 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.cache.ServerCacheManager;
import com.avaje.ebean.config.EncryptKey;
import com.avaje.ebeaninternal.server.deploy.id.IdBinder;
/**
* Provides a method to find a BeanDescriptor.
* <p>
* Used during deployment of to resolve relationships between beans.
* </p>
*/
public interface BeanDescriptorMap {
/**
* Return the name of the server/database.
*/
public String getServerName();
/**
* Return the Cache Manager.
*/
public ServerCacheManager getCacheManager();
/**
* Return the BeanDescriptor for a given class.
*/
public <T> BeanDescriptor<T> getBeanDescriptor(Class<T> entityType);
/**
* Return the Encrypt key given the table and column name.
*/
public EncryptKey getEncryptKey(String tableName, String columnName);
public IdBinder createIdBinder(BeanProperty[] uids);
}
@@ -0,0 +1,50 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
public class BeanEmbeddedMeta {
final BeanProperty[] properties;
public BeanEmbeddedMeta(BeanProperty[] properties) {
this.properties = properties;
}
/**
* Return the properties with over ridden mapping information.
*/
public BeanProperty[] getProperties() {
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;
}
}
@@ -0,0 +1,72 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.util.Map;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanPropertyAssocOne;
/**
* Creates BeanProperties for Embedded beans that have deployment information
* such as the actual DB column name and table alias.
*/
public class BeanEmbeddedMetaFactory {
/**
* Create BeanProperties for embedded beans using the deployment specific DB column name and table alias.
*/
public static BeanEmbeddedMeta create(BeanDescriptorMap owner, DeployBeanPropertyAssocOne<?> prop,
BeanDescriptor<?> descriptor) {
// we can get a BeanDescriptor for an Embedded bean
// and know that it is NOT recursive, as Embedded beans are
// only allow to hold simple scalar types...
BeanDescriptor<?> targetDesc = owner.getBeanDescriptor(prop.getTargetType());
if (targetDesc == null){
String msg = "Could not find BeanDescriptor for "+prop.getTargetType()
+". Perhaps the EmbeddedId class is not registered?";
throw new PersistenceException(msg);
}
// deployment override information (column names)
Map<String, String> propColMap = prop.getDeployEmbedded().getPropertyColumnMap();
BeanProperty[] sourceProperties = targetDesc.propertiesBaseScalar();
BeanProperty[] embeddedProperties = new BeanProperty[sourceProperties.length];
for (int i = 0; i < sourceProperties.length; i++) {
String propertyName = sourceProperties[i].getName();
String dbColumn = propColMap.get(propertyName);
if (dbColumn == null) {
// dbColumn not overridden so take original
dbColumn = sourceProperties[i].getDbColumn();
}
BeanPropertyOverride overrides = new BeanPropertyOverride(dbColumn);
embeddedProperties[i] = new BeanProperty(sourceProperties[i], overrides);
}
return new BeanEmbeddedMeta(embeddedProperties);
}
}
@@ -0,0 +1,45 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.util.List;
import com.avaje.ebean.event.BeanFinder;
/**
* Factory for controlling the construction of BeanFinders.
*/
public interface BeanFinderManager {
/**
* Return the number of beans with a registered finder.
*/
public int getRegisterCount();
/**
* Create the appropriate BeanController.
*/
public int createBeanFinders(List<Class<?>> finderClassList);
/**
* Return the BeanController for a given entity type.
*/
public <T> BeanFinder<T> getBeanFinder(Class<T> entityType);
}
@@ -0,0 +1,185 @@
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.text.StringFormatter;
import com.avaje.ebean.text.StringParser;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
/**
* Used to evaluate imported foreign keys so as to avoid unnecessary joins.
*/
public final class BeanFkeyProperty implements ElPropertyValue {
private final String placeHolder;
private final String prefix;
private final String name;
private final String dbColumn;
private int deployOrder;
public BeanFkeyProperty(String prefix, String name, String dbColumn, int deployOrder) {
this.prefix = prefix;
this.name = name;
this.dbColumn = dbColumn;
this.deployOrder = deployOrder;
this.placeHolder = calcPlaceHolder(prefix, dbColumn);
}
public int getDeployOrder() {
return deployOrder;
}
private String calcPlaceHolder(String prefix, String dbColumn) {
if (prefix != null) {
return "${" + prefix + "}" + dbColumn;
} else {
return ROOT_ELPREFIX + dbColumn;
}
}
public BeanFkeyProperty create(String expression) {
int len = expression.length() - name.length() - 1;
String prefix = expression.substring(0, len);
return new BeanFkeyProperty(prefix, name, dbColumn, deployOrder);
}
/**
* Returns false for keys.
*/
public boolean isDbEncrypted() {
return false;
}
/**
* Returns false for keys.
*/
public boolean isLocalEncrypted() {
return false;
}
/**
* Only usable as ElPropertyDeploy.
*/
public boolean isDeployOnly() {
return true;
}
/**
* Returns false.
*/
public boolean containsMany() {
return false;
}
public boolean containsManySince(String sinceProperty) {
return containsMany();
}
public String getDbColumn() {
return dbColumn;
}
public String getName() {
return name;
}
public String getElName() {
return name;
}
/**
* Returns null as not an AssocOne.
*/
public Object[] getAssocOneIdValues(Object value) {
return null;
}
/**
* Returns null as not an AssocOne.
*/
public String getAssocOneIdExpr(String prefix, String operator) {
return null;
}
/**
* Returns null as not an AssocOne.
*/
public String getAssocIdInExpr(String prefix) {
return null;
}
/**
* Returns null as not an AssocOne.
*/
public String getAssocIdInValueExpr(int size) {
return null;
}
/**
* Returns false as not an AssocOne.
*/
public boolean isAssocId() {
return false;
}
public boolean isAssocProperty() {
return false;
}
public String getElPlaceholder(boolean encrypted) {
return placeHolder;
}
public String getElPrefix() {
return prefix;
}
public boolean isDateTimeCapable() {
return false;
}
public int getJdbcType() {
return 0;
}
public Object parseDateTime(long systemTimeMillis) {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public StringFormatter getStringFormatter() {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public StringParser getStringParser() {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public void elSetReference(Object bean) {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public Object elConvertType(Object value) {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public void elSetValue(Object bean, Object value, boolean populate, boolean reference) {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public Object elGetValue(Object bean) {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public Object elGetReference(Object bean) {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public BeanProperty getBeanProperty() {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
public String getDeployProperty() {
throw new RuntimeException("ElPropertyDeploy only - not implemented");
}
}
@@ -0,0 +1,75 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebeaninternal.server.core.InternString;
/**
* Represents a database foreign key which can map to an object relationship.
*/
public class BeanForeignKey {
private final String dbColumn;
private final int dbType;
/**
* Construct the BeanForeignKey.
*/
public BeanForeignKey(String dbColumn, int dbType) {
this.dbColumn = InternString.intern(dbColumn);
this.dbType = dbType;
}
/**
* Return the database column.
*/
public String getDbColumn() {
return dbColumn;
}
/**
* Return the JDBC datatype of the database column.
*/
public int getDbType() {
return dbType;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof BeanForeignKey) {
return obj.hashCode() == hashCode();
}
return false;
}
public int hashCode() {
int hc = getClass().hashCode();
hc = hc * 31 + (dbColumn != null ? dbColumn.hashCode() : 0);
return hc;
}
public String toString() {
return dbColumn;
}
}
@@ -0,0 +1,167 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.InvalidValue;
import com.avaje.ebean.Query;
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.common.BeanList;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
/**
* Helper object for dealing with Lists.
*/
public final class BeanListHelp<T> implements BeanCollectionHelp<T> {
private final BeanPropertyAssocMany<T> many;
private final BeanDescriptor<T> targetDescriptor;
private BeanCollectionLoader loader;
public BeanListHelp(BeanPropertyAssocMany<T> many) {
this.many = many;
this.targetDescriptor = many.getTargetDescriptor();
}
public BeanListHelp() {
this.many = null;
this.targetDescriptor = null;
}
public void setLoader(BeanCollectionLoader loader) {
this.loader = loader;
}
public void add(BeanCollection<?> collection, Object bean) {
collection.internalAdd(bean);
}
public BeanCollectionAdd getBeanCollectionAdd(Object bc, String mapKey) {
if (bc instanceof BeanList<?>) {
BeanList<?> bl = (BeanList<?>) bc;
if (bl.getActualList() == null) {
bl.setActualList(new ArrayList<Object>());
}
return bl;
} else if (bc instanceof List<?>) {
return new VanillaAdd((List<?>) bc);
} else {
throw new RuntimeException("Unhandled type " + bc);
}
}
@SuppressWarnings("unchecked")
static class VanillaAdd implements BeanCollectionAdd {
@SuppressWarnings("rawtypes")
private final List list;
private VanillaAdd(List<?> list) {
this.list = list;
}
public void addBean(Object bean) {
list.add(bean);
}
}
public Iterator<?> getIterator(Object collection) {
return ((List<?>) collection).iterator();
}
public Object createEmpty(boolean vanilla) {
return vanilla ? new ArrayList<T>() : new BeanList<T>();
}
public BeanCollection<T> createReference(Object parentBean, String propertyName) {
return new BeanList<T>(loader, parentBean, propertyName);
}
public ArrayList<InvalidValue> validate(Object manyValue) {
ArrayList<InvalidValue> errs = null;
List<?> l = (List<?>) manyValue;
for (int i = 0; i < l.size(); i++) {
Object detailBean = l.get(i);
InvalidValue invalid = targetDescriptor.validate(true, detailBean);
if (invalid != null) {
if (errs == null) {
errs = new ArrayList<InvalidValue>();
}
errs.add(invalid);
}
}
return errs;
}
public void refresh(EbeanServer server, Query<?> query, Transaction t, Object parentBean) {
BeanList<?> newBeanList = (BeanList<?>) server.findList(query, t);
refresh(newBeanList, parentBean);
}
public void refresh(BeanCollection<?> bc, Object parentBean) {
BeanList<?> newBeanList = (BeanList<?>) bc;
List<?> currentList = (List<?>) many.getValueUnderlying(parentBean);
newBeanList.setModifyListening(many.getModifyListenMode());
if (currentList == null) {
// the currentList is null? Not really expecting this...
many.setValue(parentBean, newBeanList);
} else if (currentList instanceof BeanList<?>) {
// normally this case, replace just the underlying list
BeanList<?> currentBeanList = (BeanList<?>) currentList;
currentBeanList.setActualList(newBeanList.getActualList());
currentBeanList.setModifyListening(many.getModifyListenMode());
} else {
// replace the entire list with the BeanList
many.setValue(parentBean, newBeanList);
}
}
public void jsonWrite(WriteJsonContext ctx, String name, Object collection, boolean explicitInclude) {
List<?> list;
if (collection instanceof BeanCollection<?>) {
BeanList<?> beanList = (BeanList<?>) collection;
if (!beanList.isPopulated()) {
if (explicitInclude) {
// invoke lazy loading as collection
// is explicitly included in the output
beanList.size();
} else {
return;
}
}
list = beanList.getActualList();
} else {
list = (List<?>) collection;
}
ctx.beginAssocMany(name);
for (int j = 0; j < list.size(); j++) {
if (j > 0) {
ctx.appendComma();
}
Object detailBean = list.get(j);
targetDescriptor.jsonWrite(ctx, detailBean);
}
ctx.endAssocMany();
}
}
@@ -0,0 +1,59 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebeaninternal.server.persist.BeanPersister;
/**
* Holds the BeanDescriptor and its associated BeanPersister.
*/
public class BeanManager<T> {
private final BeanPersister persister;
private final BeanDescriptor<T> descriptor;
public BeanManager(BeanDescriptor<T> descriptor, BeanPersister persister) {
this.descriptor = descriptor;
this.persister = persister;
}
/**
* Return the associated BeanPersister.
*/
public BeanPersister getBeanPersister() {
return persister;
}
/**
* Return the BeanDescriptor.
*/
public BeanDescriptor<T> getBeanDescriptor() {
return descriptor;
}
/**
* Return true if this bean type is an LDAP entity type.
*/
public boolean isLdapEntityType() {
return descriptor.isLdapEntityType();
}
}
@@ -0,0 +1,46 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebeaninternal.server.persist.BeanPersister;
import com.avaje.ebeaninternal.server.persist.BeanPersisterFactory;
import com.avaje.ebeaninternal.server.persist.dml.DmlBeanPersisterFactory;
/**
* Creates BeanManagers.
*/
public class BeanManagerFactory {
final BeanPersisterFactory peristerFactory;
public BeanManagerFactory(ServerConfig config, DatabasePlatform dbPlatform) {
peristerFactory = new DmlBeanPersisterFactory(dbPlatform);
}
public <T> BeanManager<T> create(BeanDescriptor<T> desc) {
BeanPersister persister = peristerFactory.create(desc);
return new BeanManager<T>(desc, persister);
}
}
@@ -0,0 +1,205 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.InvalidValue;
import com.avaje.ebean.Query;
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.common.BeanMap;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
/**
* Helper specifically for dealing with Maps.
*/
public final class BeanMapHelp<T> implements BeanCollectionHelp<T> {
private final BeanPropertyAssocMany<T> many;
private final BeanDescriptor<T> targetDescriptor;
private final BeanProperty beanProperty;
private BeanCollectionLoader loader;
//private final String mapKey;
/**
* When created for a given query that will return a map.
*/
public BeanMapHelp(BeanDescriptor<T> targetDescriptor, String mapKey) {
this(null, targetDescriptor, mapKey);
}
public BeanMapHelp(BeanPropertyAssocMany<T> many){
this(many, many.getTargetDescriptor(), many.getMapKey());
}
/**
* When help is attached to a specific many property.
*/
private BeanMapHelp(BeanPropertyAssocMany<T> many, BeanDescriptor<T> targetDescriptor, String mapKey){
this.many = many;
this.targetDescriptor = targetDescriptor;
//this.mapKey = mapKey;
this.beanProperty = targetDescriptor.getBeanProperty(mapKey);
}
/**
* Return an iterator of the values.
*/
public Iterator<?> getIterator(Object collection) {
return ((Map<?,?>) collection).values().iterator();
}
public void setLoader(BeanCollectionLoader loader){
this.loader = loader;
}
@SuppressWarnings("unchecked")
public BeanCollectionAdd getBeanCollectionAdd(Object bc, String mapKey) {
if(mapKey == null){
mapKey = many.getMapKey();
}
BeanProperty beanProp = targetDescriptor.getBeanProperty(mapKey);
if (bc instanceof BeanMap<?,?>){
BeanMap<Object, Object> bm = (BeanMap<Object, Object>)bc;
Map<Object, Object> actualMap = bm.getActualMap();
if (actualMap == null){
actualMap = new LinkedHashMap<Object, Object>();
bm.setActualMap(actualMap);
}
return new Adder(beanProp, actualMap);
} else if (bc instanceof Map<?,?>) {
return new Adder(beanProp, (Map<Object, Object>)bc);
} else {
throw new RuntimeException("Unhandled type "+bc);
}
}
static class Adder implements BeanCollectionAdd {
private final BeanProperty beanProperty;
private final Map<Object, Object> map;
Adder(BeanProperty beanProperty, Map<Object, Object> map) {
this.beanProperty = beanProperty;
this.map = map;
}
public void addBean(Object bean) {
Object keyValue = beanProperty.getValue(bean);
map.put(keyValue, bean);
}
}
@SuppressWarnings("rawtypes")
public Object createEmpty(boolean vanilla) {
return vanilla ? new LinkedHashMap() : new BeanMap();
}
@SuppressWarnings("unchecked")
public void add(BeanCollection<?> collection, Object bean) {
Object keyValue = beanProperty.getValueIntercept(bean);
Map<Object, Object> map = (Map<Object, Object>) collection;
map.put(keyValue, bean);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public BeanCollection<T> createReference(Object parentBean, String propertyName) {
return new BeanMap(loader, parentBean, propertyName);
}
public ArrayList<InvalidValue> validate(Object manyValue) {
ArrayList<InvalidValue> errs = null;
Map<?, ?> m = (Map<?, ?>) manyValue;
Iterator<?> it = m.values().iterator();
while (it.hasNext()) {
Object detailBean = (Object) it.next();
InvalidValue invalid = targetDescriptor.validate(true, detailBean);
if (invalid != null) {
if (errs == null) {
errs = new ArrayList<InvalidValue>();
}
errs.add(invalid);
}
}
return errs;
}
public void refresh(EbeanServer server, Query<?> query, Transaction t, Object parentBean) {
BeanMap<?, ?> newBeanMap = (BeanMap<?, ?>) server.findMap(query, t);
refresh(newBeanMap, parentBean);
}
public void refresh(BeanCollection<?> bc, Object parentBean) {
BeanMap<?, ?> newBeanMap = (BeanMap<?, ?>) bc;
Map<?, ?> current = (Map<?, ?>) many.getValueUnderlying(parentBean);
newBeanMap.setModifyListening(many.getModifyListenMode());
if (current == null) {
// the currentMap is null? Not really expecting this...
many.setValue(parentBean, newBeanMap);
} else if (current instanceof BeanMap<?,?>) {
// normally this case, replace just the underlying list
BeanMap<?, ?> currentBeanMap = (BeanMap<?, ?>) current;
currentBeanMap.setActualMap(newBeanMap.getActualMap());
currentBeanMap.setModifyListening(many.getModifyListenMode());
} else {
// replace the entire set
many.setValue(parentBean, newBeanMap);
}
}
public void jsonWrite(WriteJsonContext ctx, String name, Object collection, boolean explicitInclude) {
Map<?,?> map;
if (collection instanceof BeanCollection<?>){
BeanMap<?,?> bc = (BeanMap<?,?>)collection;
if (!bc.isPopulated()){
if (explicitInclude){
// invoke lazy loading as collection
// is explicitly included in the output
bc.size();
} else {
return;
}
}
map = bc.getActualMap();
} else {
map = (Map<?,?>)collection;
}
int count = 0;
ctx.beginAssocMany(name);
Iterator<?> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<?, ?> entry = (Entry<?, ?>)it.next();
if (count++ > 0){
ctx.appendComma();
}
//FIXME: json write map key ...
Object detailBean = entry.getValue();
targetDescriptor.jsonWrite(ctx, detailBean);
}
ctx.endAssocMany();
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,402 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
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.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;
/**
* Abstract base for properties mapped to an associated bean, list, set or map.
*/
public abstract class BeanPropertyAssoc<T> extends BeanProperty {
private static final Logger logger = Logger.getLogger(BeanPropertyAssoc.class.getName());
/**
* The descriptor of the target. This MUST be initialised after construction
* so as to avoid a dependency loop between BeanDescriptors.
*/
BeanDescriptor<T> targetDescriptor;
IdBinder targetIdBinder;
InheritInfo targetInheritInfo;
String targetIdProperty;
/**
* Persist settings.
*/
final BeanCascadeInfo cascadeInfo;
/**
* Join between the beans.
*/
final TableJoin tableJoin;
/**
* The type of the joined bean.
*/
final Class<T> targetType;
/**
* The join table information.
*/
final BeanTable beanTable;
final String mappedBy;
/**
* Whether the associated join type should be an outer join.
*/
final boolean isOuterJoin;
String extraWhere;
boolean saveRecurseSkippable;
boolean deleteRecurseSkippable;
/**
* Construct the property.
*/
public BeanPropertyAssoc(BeanDescriptorMap owner, BeanDescriptor<?> descriptor, DeployBeanPropertyAssoc<T> deploy) {
super(owner, descriptor, deploy);
this.extraWhere = InternString.intern(deploy.getExtraWhere());
this.isOuterJoin = deploy.isOuterJoin();
this.beanTable = deploy.getBeanTable();
this.mappedBy = InternString.intern(deploy.getMappedBy());
this.tableJoin = new TableJoin(deploy.getTableJoin(), null);
this.targetType = deploy.getTargetType();
this.cascadeInfo = deploy.getCascadeInfo();
}
/**
* Initialise post construction.
*/
@Override
public void initialise() {
// this *MUST* execute after the BeanDescriptor is
// put into the map to stop infinite recursion
if (!isTransient){
targetDescriptor = descriptor.getBeanDescriptor(targetType);
targetIdBinder = targetDescriptor.getIdBinder();
targetInheritInfo = targetDescriptor.getInheritInfo();
saveRecurseSkippable = targetDescriptor.isSaveRecurseSkippable();
deleteRecurseSkippable = targetDescriptor.isDeleteRecurseSkippable();
cascadeValidate = cascadeInfo.isValidate();
if (!targetIdBinder.isComplexId()){
targetIdProperty = targetIdBinder.getIdProperty();
}
}
}
/**
* Create a ElPropertyValue for a *ToOne or *ToMany.
*/
protected ElPropertyValue createElPropertyValue(String propName, String remainder, ElPropertyChainBuilder chain, boolean propertyDeploy) {
// associated or embedded bean
BeanDescriptor<?> embDesc = getTargetDescriptor();
if (chain == null) {
chain = new ElPropertyChainBuilder(isEmbedded(), propName);
}
chain.add(this);
if (containsMany()) {
chain.setContainsMany(true);
}
return embDesc.buildElGetValue(remainder, chain, propertyDeploy);
}
/**
* Add table join with table alias based on prefix.
*/
public boolean addJoin(boolean forceOuterJoin, String prefix, DbSqlContext ctx) {
return tableJoin.addJoin(forceOuterJoin, prefix, ctx);
}
/**
* Add table join with explicit table alias.
*/
public boolean addJoin(boolean forceOuterJoin, String a1, String a2, DbSqlContext ctx) {
return tableJoin.addJoin(forceOuterJoin, a1, a2, ctx);
}
/**
* Add table join with explicit table alias.
*/
public void addInnerJoin(String a1, String a2, DbSqlContext ctx) {
tableJoin.addInnerJoin(a1, a2, ctx);
}
/**
* Return false.
*/
public boolean isScalar() {
return false;
}
/**
* Return the mappedBy property.
* This will be null on the owning side.
*/
public String getMappedBy() {
return mappedBy;
}
/**
* Return the Id property of the target entity type.
* <p>
* This will return null for multiple Id properties.
* </p>
*/
public String getTargetIdProperty() {
return targetIdProperty;
}
/**
* Return the BeanDescriptor of the target.
*/
public BeanDescriptor<T> getTargetDescriptor() {
return targetDescriptor;
}
public boolean isSaveRecurseSkippable(Object bean) {
if (!saveRecurseSkippable){
// we have to saveRecurse even if the bean is not dirty
// as this bean has cascade save on some of its properties
return false;
}
if (bean instanceof EntityBean){
return !((EntityBean)bean)._ebean_getIntercept().isNewOrDirty();
} else {
// we don't know so we say no
return false;
}
}
/**
* Return true if save can be skipped for unmodified bean(s) of this
* property.
* <p>
* That is, if a bean of this property is unmodified we don't need to
* saveRecurse because none of its associated beans have cascade save set to
* true.
* </p>
*/
public boolean isSaveRecurseSkippable() {
return saveRecurseSkippable;
}
/**
* Similar to isSaveRecurseSkippable but in terms of delete.
*/
public boolean isDeleteRecurseSkippable() {
return deleteRecurseSkippable;
}
/**
* Return true if the unique id properties are all not null for this bean.
*/
public boolean hasId(Object bean) {
BeanDescriptor<?> targetDesc = getTargetDescriptor();
BeanProperty[] uids = targetDesc.propertiesId();
for (int i = 0; i < uids.length; i++) {
Object value = uids[i].getValue(bean);
if (value == null) {
return false;
}
}
// all the unique properties are non-null
return true;
}
/**
* Return the type of the target.
* <p>
* This is the class of the associated bean, or beans contained in a list,
* set or map.
* </p>
*/
public Class<?> getTargetType() {
return targetType;
}
/**
* Return an extra clause to add to the query for loading or joining
* to this bean type.
*/
public String getExtraWhere() {
return extraWhere;
}
/**
* Return if this association should use an Outer join.
*/
public boolean isOuterJoin() {
return isOuterJoin;
}
/**
* Return true if this association is updateable.
*/
public boolean isUpdateable() {
if (tableJoin.columns().length > 0) {
return tableJoin.columns()[0].isUpdateable();
}
return true;
}
/**
* Return true if this association is insertable.
*/
public boolean isInsertable() {
if (tableJoin.columns().length > 0) {
return tableJoin.columns()[0].isInsertable();
}
return true;
}
/**
* return the join to use for the bean.
*/
public TableJoin getTableJoin() {
return tableJoin;
}
/**
* Return the BeanTable for this association.
* <p>
* This has the table name which is used to determine the relationship for
* this association.
* </p>
*/
public BeanTable getBeanTable() {
return beanTable;
}
/**
* Get the persist info.
*/
public BeanCascadeInfo getCascadeInfo() {
return cascadeInfo;
}
/**
* Build the list of imported property. Matches BeanProperty from the target
* descriptor back to local database columns in the TableJoin.
*/
protected ImportedId createImportedId(BeanPropertyAssoc<?> owner, BeanDescriptor<?> target, TableJoin join) {
BeanProperty[] props = target.propertiesId();
BeanProperty[] others = target.propertiesBaseScalar();
if (descriptor.isSqlSelectBased()){
String dbColumn = owner.getDbColumn();
return new ImportedIdSimple(owner, dbColumn, props[0], 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.log(Level.SEVERE, msg);
return null;
} else {
return createImportedScalar(owner, cols[0], props, others);
}
} 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);
}
} else {
// Concatenated key that is not embedded
ImportedIdSimple[] scalars = createImportedList(owner, cols, props, others);
return new ImportedIdMultiple(owner, scalars);
}
}
private ImportedIdSimple[] createImportedList(BeanPropertyAssoc<?> owner, TableJoinColumn[] cols, BeanProperty[] props, BeanProperty[] others) {
ArrayList<ImportedIdSimple> list = new ArrayList<ImportedIdSimple>();
for (int i = 0; i < cols.length; i++) {
list.add(createImportedScalar(owner, cols[i], props, others));
}
return ImportedIdSimple.sort(list);
}
private ImportedIdSimple createImportedScalar(BeanPropertyAssoc<?> owner, TableJoinColumn col, BeanProperty[] props, BeanProperty[] others) {
String matchColumn = col.getForeignDbColumn();
String localColumn = col.getLocalDbColumn();
for (int j = 0; j < props.length; j++) {
if (props[j].getDbColumn().equalsIgnoreCase(matchColumn)) {
return new ImportedIdSimple(owner, localColumn, props[j], j);
}
}
for (int j = 0; j < others.length; j++) {
if (others[j].getDbColumn().equalsIgnoreCase(matchColumn)) {
return new ImportedIdSimple(owner, localColumn, others[j], j+props.length);
}
}
String msg = "Error with the Join on ["+getFullBeanName()
+"]. Could not find the local match for ["+matchColumn+"] "//in table["+searchTable+"]?"
+" Perhaps an error in a @JoinColumn";
throw new PersistenceException(msg);
}
}
@@ -0,0 +1,845 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.PersistenceException;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.Expression;
import com.avaje.ebean.InvalidValue;
import com.avaje.ebean.Query;
import com.avaje.ebean.SqlUpdate;
import com.avaje.ebean.Transaction;
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.ebeaninternal.api.SpiQuery;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.deploy.id.ImportedId;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanPropertyAssocMany;
import com.avaje.ebeaninternal.server.el.ElPropertyChainBuilder;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
import com.avaje.ebeaninternal.server.query.SqlBeanLoad;
import com.avaje.ebeaninternal.server.text.json.ReadJsonContext;
import com.avaje.ebeaninternal.server.text.json.ReadJsonContext.ReadBeanState;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
/**
* Property mapped to a List Set or Map.
*/
public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
/**
* Join for manyToMany intersection table.
*/
final TableJoin intersectionJoin;
/**
* For ManyToMany this is the Inverse join used to build reference queries.
*/
final TableJoin inverseJoin;
/**
* Flag to indicate that this is a unidirectional relationship.
*/
final boolean unidirectional;
/**
* Flag to indicate manyToMany relationship.
*/
final boolean manyToMany;
final String fetchOrderBy;
final String mapKey;
/**
* The type of the many, set, list or map.
*/
final ManyType manyType;
final String serverName;
final ModifyListenMode modifyListenMode;
BeanProperty mapKeyProperty;
/**
* Derived list of exported property and matching foreignKey
*/
ExportedProperty[] exportedProperties;
/**
* Property on the 'child' bean that links back to the 'master'.
*/
BeanPropertyAssocOne<?> childMasterProperty;
boolean embeddedExportedProperties;
BeanCollectionHelp<T> help;
ImportedId importedId;
String deleteByParentIdSql;
String deleteByParentIdInSql;
final CollectionTypeConverter typeConverter;
/**
* Create this property.
*/
public BeanPropertyAssocMany(BeanDescriptorMap owner, BeanDescriptor<?> descriptor, DeployBeanPropertyAssocMany<T> deploy) {
super(owner, descriptor, deploy);
this.unidirectional = deploy.isUnidirectional();
this.manyToMany = deploy.isManyToMany();
this.serverName = descriptor.getServerName();
this.manyType = deploy.getManyType();
this.typeConverter = manyType.getTypeConverter();
this.mapKey = deploy.getMapKey();
this.fetchOrderBy = deploy.getFetchOrderBy();
this.intersectionJoin = deploy.createIntersectionTableJoin();
this.inverseJoin = deploy.createInverseTableJoin();
this.modifyListenMode = deploy.getModifyListenMode();
}
public void initialise() {
super.initialise();
if (!isTransient){
this.help = BeanCollectionHelpFactory.create(this);
if (manyToMany){
// only manyToMany's have imported properties
importedId = createImportedId(this, targetDescriptor, tableJoin);
} else {
// find the property in the many that matches
// back to the master (Order in the OrderDetail bean)
childMasterProperty = initChildMasterProperty();
if (childMasterProperty != null){
childMasterProperty.setRelationshipProperty(this);
}
}
if (mapKey != null){
mapKeyProperty = initMapKeyProperty();
}
exportedProperties = createExported();
if (exportedProperties.length > 0){
embeddedExportedProperties = exportedProperties[0].isEmbedded();
}
String delStmt;
if (manyToMany){
delStmt = "delete from "+inverseJoin.getTable()+" where ";
} else {
delStmt = "delete from "+targetDescriptor.getBaseTable()+" where ";
}
deleteByParentIdSql = delStmt + deriveWhereParentIdSql(false);
deleteByParentIdInSql = delStmt + deriveWhereParentIdSql(true);
}
}
/**
* Get the underlying List Set or Map.
* For unwrapping scala collection types etc.
*/
public Object getValueUnderlying(Object bean) {
Object value = getValue(bean);
if (typeConverter != null){
value = typeConverter.toUnderlying(value);
}
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) {
if (typeConverter != null){
value = typeConverter.toWrapped(value);
}
super.setValue(bean, value);
}
@Override
public void setValueIntercept(Object bean, Object value) {
if (typeConverter != null){
value = typeConverter.toWrapped(value);
}
super.setValueIntercept(bean, value);
}
public ElPropertyValue buildElPropertyValue(String propName, String remainder, ElPropertyChainBuilder chain, boolean propertyDeploy) {
return createElPropertyValue(propName, remainder, chain, propertyDeploy);
}
public SqlUpdate deleteByParentId(Object parentId, List<Object> parentIdist) {
if (parentId != null){
return deleteByParentId(parentId);
} else {
return deleteByParentIdList(parentIdist);
}
}
private SqlUpdate deleteByParentId(Object parentId) {
DefaultSqlUpdate sqlDelete = new DefaultSqlUpdate(deleteByParentIdSql);
bindWhereParendId(sqlDelete, parentId);
return sqlDelete;
}
/**
* Find the Id's of detail beans given a parent Id or list of parent Id's.
*/
public List<Object> findIdsByParentId(Object parentId, List<Object> parentIdist, Transaction t, ArrayList<Object> excludeDetailIds) {
if (parentId != null){
return findIdsByParentId(parentId, t, excludeDetailIds);
} else {
return findIdsByParentIdList(parentIdist, t, excludeDetailIds);
}
}
private List<Object> findIdsByParentId(Object parentId, Transaction t, ArrayList<Object> excludeDetailIds) {
String rawWhere = deriveWhereParentIdSql(false);
EbeanServer server = getBeanDescriptor().getEbeanServer();
Query<?> q = server.find(getPropertyType())
.where().raw(rawWhere).query();
bindWhereParendId(1, q, parentId);
if (excludeDetailIds != null && !excludeDetailIds.isEmpty()) {
Expression idIn = q.getExpressionFactory().idIn(excludeDetailIds);
q.where().not(idIn);
}
return server.findIds(q, t);
}
private List<Object> findIdsByParentIdList(List<Object> parentIdist, Transaction t, ArrayList<Object> excludeDetailIds) {
String rawWhere = deriveWhereParentIdSql(true);
String inClause = targetIdBinder.getIdInValueExpr(parentIdist.size());
String expr = rawWhere+inClause;
EbeanServer server = getBeanDescriptor().getEbeanServer();
Query<?> q = server.find(getPropertyType())
.where().raw(expr).query();
int pos = 1;
for (int i = 0; i < parentIdist.size(); i++) {
pos = bindWhereParendId(pos, q, parentIdist.get(i));
}
if (excludeDetailIds != null && !excludeDetailIds.isEmpty()) {
Expression idIn = q.getExpressionFactory().idIn(excludeDetailIds);
q.where().not(idIn);
}
return server.findIds(q, t);
}
private SqlUpdate deleteByParentIdList(List<Object> parentIdist) {
StringBuilder sb = new StringBuilder(100);
sb.append(deleteByParentIdInSql);
String inClause = targetIdBinder.getIdInValueExpr(parentIdist.size());
sb.append(inClause);
DefaultSqlUpdate delete = new DefaultSqlUpdate(sb.toString());
for (int i = 0; i < parentIdist.size(); i++) {
bindWhereParendId(delete, parentIdist.get(i));
}
return delete;
}
/**
* Set the lazy load server to help create reference collections (that lazy
* load on demand).
*/
public void setLoader(BeanCollectionLoader loader){
if (help != null){
help.setLoader(loader);
}
}
/**
* Return the mode for listening to modifications to collections for this
* association.
*/
public ModifyListenMode getModifyListenMode() {
return modifyListenMode;
}
/**
* Ignore changes for Many properties.
*/
public boolean hasChanged(Object bean, Object oldValues) {
return false;
}
@Override
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
}
@Override
public void loadIgnore(DbReadContext ctx) {
// nothing to ignore for Many
}
@Override
public void load(SqlBeanLoad sqlBeanLoad) throws SQLException {
sqlBeanLoad.loadAssocMany(this);
}
@Override
public Object readSet(DbReadContext ctx, Object bean, Class<?> type) throws SQLException {
return null;
}
@Override
public Object read(DbReadContext ctx) throws SQLException {
return null;
}
@Override
public boolean isValueLoaded(Object value) {
if (value instanceof BeanCollection<?>){
return ((BeanCollection<?>)value).isPopulated();
}
return true;
}
public void add(BeanCollection<?> collection, Object bean) {
help.add(collection, bean);
}
@Override
public InvalidValue validateCascade(Object manyValue) {
ArrayList<InvalidValue> errs = help.validate(manyValue);
if (errs == null){
return null;
} else {
return new InvalidValue("recurse.many", targetDescriptor.getFullName(), manyValue, InvalidValue.toArray(errs));
}
}
/**
* Refresh the appropriate list set or map.
*/
public void refresh(EbeanServer server, Query<?> query, Transaction t, Object parentBean) {
help.refresh(server, query, t, parentBean);
}
/**
* Apply the refreshed BeanCollection to the property of the parentBean.
*/
public void refresh(BeanCollection<?> bc, Object parentBean) {
help.refresh(bc, parentBean);
}
/**
* Return the Id values from the given bean.
*/
@Override
public Object[] getAssocOneIdValues(Object bean) {
return targetDescriptor.getIdBinder().getIdValues(bean);
}
/**
* Return the Id expression to add to where clause etc.
*/
public String getAssocOneIdExpr(String prefix, String operator) {
return targetDescriptor.getIdBinder().getAssocOneIdExpr(prefix, operator);
}
/**
* Return the logical id value expression taking into account embedded id's.
*/
@Override
public String getAssocIdInValueExpr(int size){
return targetDescriptor.getIdBinder().getIdInValueExpr(size);
}
/**
* Return the logical id in expression taking into account embedded id's.
*/
@Override
public String getAssocIdInExpr(String prefix){
return targetDescriptor.getIdBinder().getAssocIdInExpr(prefix);
}
@Override
public boolean isAssocId() {
return true;
}
@Override
public boolean isAssocProperty() {
return true;
}
/**
* Returns true.
*/
@Override
public boolean containsMany(){
return true;
}
/**
* Return the many type.
*/
public ManyType getManyType() {
return manyType;
}
/**
* Return true if this is many to many.
*/
public boolean isManyToMany() {
return manyToMany;
}
/**
* ManyToMany only, join from local table to intersection table.
*/
public TableJoin getIntersectionTableJoin() {
return intersectionJoin;
}
/**
* 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) {
if (mapKeyProperty != null){
mapKeyProperty.setValue(child, mapKeyValue);
}
if (!manyToMany){
if (childMasterProperty != null){
// bidirectional in the sense that the 'master' property
// exists on the 'detail' bean
childMasterProperty.setValue(child, parent);
} else {
// unidirectional in the sense that the 'master' property
// does NOT exist on the 'detail' bean
}
}
}
/**
* Return the order by clause used to order the fetching of the data for
* this list, set or map.
*/
public String getFetchOrderBy() {
return fetchOrderBy;
}
/**
* Return the default mapKey when returning a Map.
*/
public String getMapKey() {
return mapKey;
}
public BeanCollection<?> createReferenceIfNull(Object parentBean) {
Object v = getValue(parentBean);
if (v instanceof BeanCollection<?>){
BeanCollection<?> bc = (BeanCollection<?>)v;
return bc.isReference() ? bc : null;
} else {
return createReference(parentBean);
}
}
public BeanCollection<?> createReference(Object parentBean) {
BeanCollection<?> ref = help.createReference(parentBean, name);
setValue(parentBean, ref);
return ref;
}
public Object createEmpty(boolean vanilla) {
return help.createEmpty(vanilla);
}
public BeanCollectionAdd getBeanCollectionAdd(Object bc, String mapKey) {
return help.getBeanCollectionAdd(bc, mapKey);
}
public Object getParentId(Object parentBean) {
return descriptor.getId(parentBean);
}
private void bindWhereParendId(DefaultSqlUpdate sqlUpd, Object parentId){
if (exportedProperties.length == 1){
sqlUpd.addParameter(parentId);
return;
}
for (int i = 0; i < exportedProperties.length; i++) {
Object embVal = exportedProperties[i].getValue(parentId);
sqlUpd.addParameter(embVal);
}
}
private int bindWhereParendId(int pos, Query<?> q, Object parentId) {
if (exportedProperties.length == 1) {
q.setParameter(pos++, parentId);
} else {
for (int i = 0; i < exportedProperties.length; i++) {
Object embVal = exportedProperties[i].getValue(parentId);
q.setParameter(pos++, embVal);
}
}
return pos;
}
private String deriveWhereParentIdSql(boolean inClause) {
StringBuilder sb = new StringBuilder();
if (inClause){
sb.append("(");
}
for (int i = 0; i < exportedProperties.length; i++) {
String fkColumn = exportedProperties[i].getForeignDbColumn();
if (i > 0){
String s = inClause ? "," : " and ";
sb.append(s);
}
sb.append(fkColumn);
if (!inClause){
sb.append("=? ");
}
}
if (inClause){
sb.append(")");
}
return sb.toString();
}
public void setPredicates(SpiQuery<?> query, Object parentBean) {
if (manyToMany){
// for ManyToMany lazy loading we need to include a
// join to the intersection table. The predicate column
// is not on the 'destination many table'.
query.setIncludeTableJoin(inverseJoin);
}
if (embeddedExportedProperties) {
// use the EmbeddedId object instead of the parentBean
BeanProperty[] uids = descriptor.propertiesId();
parentBean = uids[0].getValue(parentBean);
}
for (int i = 0; i < exportedProperties.length; i++) {
Object val = exportedProperties[i].getValue(parentBean);
String fkColumn = exportedProperties[i].getForeignDbColumn();
if (!manyToMany){
fkColumn = targetDescriptor.getBaseTableAlias()+"."+fkColumn;
} else {
// use hard coded alias for intersection table
fkColumn = "int_."+fkColumn;
}
query.where().eq(fkColumn, val);
}
if (extraWhere != null){
// replace the table alias place holder
String ta = targetDescriptor.getBaseTableAlias();
String where = StringHelper.replaceString(extraWhere, "${ta}", ta);
query.where().raw(where);
}
if (fetchOrderBy != null){
query.order(fetchOrderBy);
}
}
/**
* Create the array of ExportedProperty used to build reference objects.
*/
private ExportedProperty[] createExported() {
BeanProperty[] uids = descriptor.propertiesId();
ArrayList<ExportedProperty> list = new ArrayList<ExportedProperty>();
if (uids.length == 1 && uids[0].isEmbedded()) {
BeanPropertyAssocOne<?> one = (BeanPropertyAssocOne<?>) uids[0];
BeanDescriptor<?> targetDesc = one.getTargetDescriptor();
BeanProperty[] emIds = targetDesc.propertiesBaseScalar();
try {
for (int i = 0; i < emIds.length; i++) {
ExportedProperty expProp = findMatch(true, emIds[i]);
list.add(expProp);
}
} catch (PersistenceException e){
// not found as individual scalar properties
e.printStackTrace();
}
} else {
for (int i = 0; i < uids.length; i++) {
ExportedProperty expProp = findMatch(false, uids[i]);
list.add(expProp);
}
}
return (ExportedProperty[]) list.toArray(new ExportedProperty[list.size()]);
}
/**
* Find the matching foreignDbColumn for a given local property.
*/
private ExportedProperty findMatch(boolean embedded,BeanProperty prop) {
String matchColumn = prop.getDbColumn();
String searchTable;
TableJoinColumn[] columns;
if (manyToMany){
// look for column going to intersection
columns = intersectionJoin.columns();
searchTable = intersectionJoin.getTable();
} else {
columns = tableJoin.columns();
searchTable = tableJoin.getTable();
}
for (int i = 0; i < columns.length; i++) {
String matchTo = columns[i].getLocalDbColumn();
if (matchColumn.equalsIgnoreCase(matchTo)) {
String foreignCol = columns[i].getForeignDbColumn();
return new ExportedProperty(embedded, foreignCol, prop);
}
}
String msg = "Error with the Join on ["+getFullBeanName()
+"]. Could not find the matching foreign key for ["+matchColumn+"] in table["+searchTable+"]?"
+" Perhaps using a @JoinColumn with the name/referencedColumnName attributes swapped?";
throw new PersistenceException(msg);
}
/**
* Return the child property that links back to the master bean.
* <p>
* Note that childMasterProperty will be null if a field is used instead of
* a ManyToOne bean association.
* </p>
*/
private BeanPropertyAssocOne<?> initChildMasterProperty() {
if (unidirectional){
return null;
}
// search for the property, to see if it exists
Class<?> beanType = descriptor.getBeanType();
BeanDescriptor<?> targetDesc = getTargetDescriptor();
BeanPropertyAssocOne<?>[] ones = targetDesc.propertiesOne();
for (int i = 0; i < ones.length; i++) {
BeanPropertyAssocOne<?> prop = ones[i];
if (mappedBy != null){
// match using mappedBy as property name
if (mappedBy.equalsIgnoreCase(prop.getName())) {
return prop;
}
} else {
// assume only one property that matches parent object type
if (prop.getTargetType().equals(beanType)) {
// found it, stop search
return prop;
}
}
}
String msg = "Can not find Master [" + beanType + "] in Child[" + targetDesc + "]";
throw new RuntimeException(msg);
}
/**
* Search for and return the mapKey property.
*/
private BeanProperty initMapKeyProperty() {
// search for the property
BeanDescriptor<?> targetDesc = getTargetDescriptor();
Iterator<BeanProperty> it = targetDesc.propertiesAll();
while (it.hasNext()){
BeanProperty prop = it.next();
if (mapKey.equalsIgnoreCase(prop.getName())) {
return prop;
}
}
String from = descriptor.getFullName();
String to = targetDesc.getFullName();
String msg = from+": Could not find mapKey property ["+mapKey+"] on ["+to+"]";
throw new PersistenceException(msg);
}
public IntersectionRow buildManyDeleteChildren(Object parentBean, ArrayList<Object> excludeDetailIds) {
IntersectionRow row = new IntersectionRow(tableJoin.getTable());
if (excludeDetailIds != null && !excludeDetailIds.isEmpty()) {
row.setExcludeIds(excludeDetailIds, getTargetDescriptor());
}
buildExport(row, parentBean);
return row;
}
public IntersectionRow buildManyToManyDeleteChildren(Object parentBean) {
IntersectionRow row = new IntersectionRow(intersectionJoin.getTable());
buildExport(row, parentBean);
return row;
}
public IntersectionRow buildManyToManyMapBean(Object parent, Object other) {
IntersectionRow row = new IntersectionRow(intersectionJoin.getTable());
buildExport(row, parent);
buildImport(row, other);
return row;
}
private void buildExport(IntersectionRow row, Object parentBean) {
if (embeddedExportedProperties) {
BeanProperty[] uids = descriptor.propertiesId();
parentBean = uids[0].getValue(parentBean);
}
for (int i = 0; i < exportedProperties.length; i++) {
Object val = exportedProperties[i].getValue(parentBean);
String fkColumn = exportedProperties[i].getForeignDbColumn();
row.put(fkColumn, val);
}
}
/**
* Set the predicates for lazy loading of the association.
* Handles predicates for both OneToMany and ManyToMany.
*/
private void buildImport(IntersectionRow row, Object otherBean) {
importedId.buildImport(row, otherBean);
}
/**
* Return true if the otherBean has an Id value.
*/
public boolean hasImportedId(Object otherBean) {
return null != targetDescriptor.getId(otherBean);
}
public void jsonWrite(WriteJsonContext ctx, Object bean) {
Boolean include = ctx.includeMany(name);
if (Boolean.FALSE.equals(include)){
return;
}
Object value = getValueIntercept(bean);
if (value != null){
ctx.pushParentBeanMany(bean);
help.jsonWrite(ctx, name, value, include != null);
ctx.popParentBeanMany();
}
}
public void jsonRead(ReadJsonContext ctx, Object bean){
if (!ctx.readArrayBegin()) {
// the array is null
return;
}
Object collection = help.createEmpty(false);
BeanCollectionAdd add = getBeanCollectionAdd(collection, null);
do {
ReadBeanState detailBeanState = targetDescriptor.jsonRead(ctx, name);
if (detailBeanState == null){
// probably empty array
break;
}
Object detailBean = detailBeanState.getBean();
add.addBean(detailBean);
if (bean != null && childMasterProperty != null){
// bind detail bean back to master via mappedBy property
childMasterProperty.setValue(detailBean, bean);
detailBeanState.setLoaded(childMasterProperty.getName());
}
detailBeanState.setLoadedState();
if (!ctx.readArrayNext()){
break;
}
} while(true);
setValue(bean, collection);
}
}
@@ -0,0 +1,930 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.persistence.PersistenceException;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.InvalidValue;
import com.avaje.ebean.Query;
import com.avaje.ebean.SqlUpdate;
import com.avaje.ebean.Transaction;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebean.bean.PersistenceContext;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.deploy.id.IdBinder;
import com.avaje.ebeaninternal.server.deploy.id.ImportedId;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanPropertyAssocOne;
import com.avaje.ebeaninternal.server.el.ElPropertyChainBuilder;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
import com.avaje.ebeaninternal.server.query.SplitName;
import com.avaje.ebeaninternal.server.query.SqlBeanLoad;
import com.avaje.ebeaninternal.server.text.json.ReadJsonContext;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
/**
* Property mapped to a joined bean.
*/
public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
private final boolean oneToOne;
private final boolean oneToOneExported;
private final boolean embeddedVersion;
private final boolean importedPrimaryKey;
private final LocalHelp localHelp;
private final BeanProperty[] embeddedProps;
private final HashMap<String,BeanProperty> embeddedPropsMap;
/**
* The information for Imported foreign Keys.
*/
private ImportedId importedId;
private ExportedProperty[] exportedProperties;
private String deleteByParentIdSql;
private String deleteByParentIdInSql;
BeanPropertyAssocMany<?> relationshipProperty;
/**
* Create based on deploy information of an EmbeddedId.
*/
public BeanPropertyAssocOne(BeanDescriptorMap owner, DeployBeanPropertyAssocOne<T> deploy) {
this(owner, null, deploy);
}
/**
* Create the property.
*/
public BeanPropertyAssocOne(BeanDescriptorMap owner, BeanDescriptor<?> descriptor,
DeployBeanPropertyAssocOne<T> deploy) {
super(owner, descriptor, deploy);
importedPrimaryKey = deploy.isImportedPrimaryKey();
oneToOne = deploy.isOneToOne();
oneToOneExported = deploy.isOneToOneExported();
if (embedded) {
// 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]);
}
} else {
embeddedProps = null;
embeddedPropsMap = null;
embeddedVersion = false;
}
localHelp = createHelp(embedded, oneToOneExported);
}
@Override
public void initialise() {
super.initialise();
if (!isTransient) {
if (embedded) {
// no imported or exported information
} else if (!oneToOneExported) {
importedId = createImportedId(this, targetDescriptor, tableJoin);
} else {
exportedProperties = createExported();
String delStmt = "delete from "+targetDescriptor.getBaseTable()+" where ";
deleteByParentIdSql = delStmt + deriveWhereParentIdSql(false);
deleteByParentIdInSql = delStmt + deriveWhereParentIdSql(true);
}
}
}
public void setRelationshipProperty(BeanPropertyAssocMany<?> relationshipProperty){
this.relationshipProperty = relationshipProperty;
}
public BeanPropertyAssocMany<?> getRelationshipProperty() {
return relationshipProperty;
}
public void cacheClear() {
if (targetDescriptor.isBeanCaching() && relationshipProperty != null) {
targetDescriptor.cacheClearCachedManyIds(relationshipProperty.getName());
}
}
public void cacheDelete(boolean clearOnNull, Object bean) {
if (targetDescriptor.isBeanCaching() && relationshipProperty != null) {
Object assocBean = getValue(bean);
if (assocBean != null) {
Object parentId = targetDescriptor.getId(assocBean);
if (parentId != null) {
targetDescriptor.cacheRemoveCachedManyIds(parentId, relationshipProperty.getName());
return;
}
}
if (clearOnNull) {
targetDescriptor.cacheClearCachedManyIds(relationshipProperty.getName());
}
}
}
public ElPropertyValue buildElPropertyValue(String propName, String remainder, ElPropertyChainBuilder chain, boolean propertyDeploy) {
if (embedded){
BeanProperty embProp = embeddedPropsMap.get(remainder);
if (embProp == null){
String msg = "Embedded Property "+remainder+" not found in "+getFullBeanName();
throw new PersistenceException(msg);
}
if (chain == null) {
chain = new ElPropertyChainBuilder(true, propName);
}
chain.add(this);
return chain.add(embProp).build();
}
return createElPropertyValue(propName, remainder, chain, propertyDeploy);
}
@Override
public String getElPlaceholder(boolean encrypted) {
return encrypted ? elPlaceHolderEncrypted : elPlaceHolder;
}
public SqlUpdate deleteByParentId(Object parentId, List<Object> parentIdist) {
if (parentId != null){
return deleteByParentId(parentId);
} else {
return deleteByParentIdList(parentIdist);
}
}
private SqlUpdate deleteByParentIdList(List<Object> parentIdist) {
StringBuilder sb = new StringBuilder(100);
sb.append(deleteByParentIdInSql);
String inClause = targetIdBinder.getIdInValueExpr(parentIdist.size());
sb.append(inClause);
DefaultSqlUpdate delete = new DefaultSqlUpdate(sb.toString());
for (int i = 0; i < parentIdist.size(); i++) {
targetIdBinder.bindId(delete, parentIdist.get(i));
}
return delete;
}
private SqlUpdate deleteByParentId(Object parentId) {
DefaultSqlUpdate delete = new DefaultSqlUpdate(deleteByParentIdSql);
if (exportedProperties.length == 1){
delete.addParameter(parentId);
} else {
targetDescriptor.getIdBinder().bindId(delete, parentId);
}
return delete;
}
public List<Object> findIdsByParentId(Object parentId, List<Object> parentIdist, Transaction t) {
if (parentId != null){
return findIdsByParentId(parentId, t);
} else {
return findIdsByParentIdList(parentIdist, t);
}
}
private List<Object> findIdsByParentId(Object parentId, Transaction t) {
String rawWhere = deriveWhereParentIdSql(false);
EbeanServer server = getBeanDescriptor().getEbeanServer();
Query<?> q = server.find(getPropertyType())
.where().raw(rawWhere).query();
bindWhereParendId(q, parentId);
return server.findIds(q, t);
}
private List<Object> findIdsByParentIdList(List<Object> parentIdist, Transaction t) {
String rawWhere = deriveWhereParentIdSql(true);
String inClause = targetIdBinder.getIdInValueExpr(parentIdist.size());
String expr = rawWhere+inClause;
EbeanServer server = getBeanDescriptor().getEbeanServer();
Query<?> q = (Query<?>)server.find(getPropertyType())
.where().raw(expr);
for (int i = 0; i < parentIdist.size(); i++) {
bindWhereParendId(q, parentIdist.get(i));
}
return server.findIds(q, t);
}
private void bindWhereParendId(Query<?> q, Object parentId) {
if (exportedProperties.length == 1) {
q.setParameter(1, parentId);
} else {
int pos = 1;
for (int i = 0; i < exportedProperties.length; i++) {
Object embVal = exportedProperties[i].getValue(parentId);
q.setParameter(pos++, embVal);
}
}
}
public void addFkey() {
if (importedId != null) {
importedId.addFkeys(name);
}
}
@Override
public boolean isValueLoaded(Object value) {
if (value instanceof EntityBean) {
return ((EntityBean) value)._ebean_getIntercept().isLoaded();
}
return true;
}
@Override
public InvalidValue validateCascade(Object value) {
BeanDescriptor<?> target = getTargetDescriptor();
return target.validate(true, value);
}
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.
*/
public BeanProperty[] getProperties() {
return embeddedProps;
}
public void buildSelectExpressionChain(String prefix, List<String> selectChain) {
prefix = SplitName.add(prefix, name);
if (!embedded){
targetIdBinder.buildSelectExpressionChain(prefix, selectChain);
} else {
for (int i = 0; i < embeddedProps.length; i++) {
embeddedProps[i].buildSelectExpressionChain(prefix, selectChain);
}
}
}
/**
* Return true if this a OneToOne property. Otherwise assumed ManyToOne.
*/
public boolean isOneToOne() {
return oneToOne;
}
/**
* Return true if this is the exported side of a OneToOne.
*/
public boolean isOneToOneExported() {
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.
*/
public boolean isImportedPrimaryKey() {
return importedPrimaryKey;
}
/**
* Same as getPropertyType(). Return the type of the bean this property
* represents.
*/
public Class<?> getTargetType() {
return getPropertyType();
}
public Object getCacheDataValue(Object bean){
if (embedded) {
throw new RuntimeException();
} else {
Object ap = getValue(bean);
if (ap == null){
return null;
} else {
return targetDescriptor.getId(ap);
}
}
}
public void setCacheDataValue(Object bean, Object cacheData, Object oldValues, boolean readOnly){
if (cacheData != null) {
if (embedded){
throw new RuntimeException();
} else {
boolean vanillaMode = false;
T ref = targetDescriptor.createReference(vanillaMode, Boolean.FALSE, cacheData, null);
setValue(bean, ref);
if (oldValues != null){
setValue(oldValues, ref);
}
if (readOnly && !vanillaMode){
((EntityBean)ref)._ebean_intercept().setReadOnly(true);
}
}
}
}
/**
* Return the Id values from the given bean.
*/
@Override
public Object[] getAssocOneIdValues(Object bean) {
return targetDescriptor.getIdBinder().getIdValues(bean);
}
/**
* Return the Id expression to add to where clause etc.
*/
public String getAssocOneIdExpr(String prefix, String operator) {
return targetDescriptor.getIdBinder().getAssocOneIdExpr(prefix, operator);
}
/**
* Return the logical id value expression taking into account embedded id's.
*/
@Override
public String getAssocIdInValueExpr(int size){
return targetDescriptor.getIdBinder().getIdInValueExpr(size);
}
/**
* Return the logical id in expression taking into account embedded id's.
*/
@Override
public String getAssocIdInExpr(String prefix){
return targetDescriptor.getIdBinder().getAssocIdInExpr(prefix);
}
@Override
public boolean isAssocId() {
return !embedded;
}
@Override
public boolean isAssocProperty() {
return !embedded;
}
/**
* Create a vanilla bean of the target type to be used as an embeddedId
* value.
*/
public Object createEmbeddedId() {
return getTargetDescriptor().createVanillaBean();
}
/**
* Return an empty reference object.
*/
public Object createEmptyReference() {
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) {
Object value = getValueIntercept(bean);
if (value == null) {
value = targetDescriptor.createEntityBean();
setValueIntercept(bean, value);
}
return value;
}
public ImportedId getImportedId() {
return importedId;
}
private String deriveWhereParentIdSql(boolean inClause) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < exportedProperties.length; i++) {
String fkColumn = exportedProperties[i].getForeignDbColumn();
if (i > 0){
String s = inClause ? "," : " and ";
sb.append(s);
}
sb.append(fkColumn);
if (!inClause){
sb.append("=? ");
}
}
return sb.toString();
}
/**
* Create the array of ExportedProperty used to build reference objects.
*/
private ExportedProperty[] createExported() {
BeanProperty[] uids = descriptor.propertiesId();
ArrayList<ExportedProperty> list = new ArrayList<ExportedProperty>();
if (uids.length == 1 && uids[0].isEmbedded()) {
BeanPropertyAssocOne<?> one = (BeanPropertyAssocOne<?>) uids[0];
BeanDescriptor<?> targetDesc = one.getTargetDescriptor();
BeanProperty[] emIds = targetDesc.propertiesBaseScalar();
try {
for (int i = 0; i < emIds.length; i++) {
ExportedProperty expProp = findMatch(true, emIds[i]);
list.add(expProp);
}
} catch (PersistenceException e){
// not found as individual scalar properties
e.printStackTrace();
}
} else {
for (int i = 0; i < uids.length; i++) {
ExportedProperty expProp = findMatch(false, uids[i]);
list.add(expProp);
}
}
return (ExportedProperty[]) list.toArray(new ExportedProperty[list.size()]);
}
/**
* Find the matching foreignDbColumn for a given local property.
*/
private ExportedProperty findMatch(boolean embeddedProp,BeanProperty prop) {
String matchColumn = prop.getDbColumn();
String searchTable = tableJoin.getTable();
TableJoinColumn[] columns = tableJoin.columns();
for (int i = 0; i < columns.length; i++) {
String matchTo = columns[i].getLocalDbColumn();
if (matchColumn.equalsIgnoreCase(matchTo)) {
String foreignCol = columns[i].getForeignDbColumn();
return new ExportedProperty(embeddedProp, foreignCol, prop);
}
}
String msg = "Error with the Join on ["+getFullBeanName()
+"]. Could not find the matching foreign key for ["+matchColumn+"] in table["+searchTable+"]?"
+" Perhaps using a @JoinColumn with the name/referencedColumnName attributes swapped?";
throw new PersistenceException(msg);
}
@Override
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
if (!isTransient) {
localHelp.appendSelect(ctx, subQuery);
}
}
@Override
public void appendFrom(DbSqlContext ctx, boolean forceOuterJoin) {
if (!isTransient) {
localHelp.appendFrom(ctx, forceOuterJoin);
}
}
@Override
public Object readSet(DbReadContext ctx, Object bean, Class<?> type) throws SQLException {
boolean assignable = (type == null || owningType.isAssignableFrom(type));
return localHelp.readSet(ctx, bean, assignable);
}
/**
* Read the data from the resultSet effectively ignoring it and returning null.
*/
@Override
public Object read(DbReadContext ctx) throws SQLException {
// just read the resultSet incrementing the column index
// pass in null for the bean so any data read is ignored
return localHelp.read(ctx);
}
@Override
public void loadIgnore(DbReadContext ctx) {
localHelp.loadIgnore(ctx);
}
@Override
public void load(SqlBeanLoad sqlBeanLoad) throws SQLException {
Object dbVal = sqlBeanLoad.load(this);
if (embedded && sqlBeanLoad.isLazyLoad()){
if (dbVal instanceof EntityBean){
((EntityBean)dbVal)._ebean_getIntercept().setLoaded();
}
}
}
private LocalHelp createHelp(boolean embedded, boolean oneToOneExported) {
if (embedded) {
return new Embedded();
} else if (oneToOneExported) {
return new ReferenceExported();
} else {
return new Reference(this);
}
}
/**
* Local interface to handle Embedded, Reference and Reference Exported
* cases.
*/
private abstract class LocalHelp {
abstract void loadIgnore(DbReadContext ctx);
abstract Object read(DbReadContext ctx) throws SQLException;
abstract Object readSet(DbReadContext ctx, Object bean, boolean assignAble) throws SQLException;
abstract void appendSelect(DbSqlContext ctx, boolean subQuery);
abstract void appendFrom(DbSqlContext ctx, boolean forceOuterJoin);
}
private final class Embedded extends LocalHelp {
void loadIgnore(DbReadContext ctx) {
for (int i = 0; i < embeddedProps.length; i++) {
embeddedProps[i].loadIgnore(ctx);
}
}
@Override
Object readSet(DbReadContext ctx, Object bean, boolean assignable) throws SQLException {
Object dbVal = read(ctx);
if (bean != null && assignable) {
// set back to the parent bean
setValue(bean, dbVal);
ctx.propagateState(dbVal);
return dbVal;
} else {
return null;
}
}
Object read(DbReadContext ctx) throws SQLException {
EntityBean embeddedBean = targetDescriptor.createEntityBean();
boolean notNull = false;
for (int i = 0; i < embeddedProps.length; i++) {
Object value = embeddedProps[i].readSet(ctx, embeddedBean, null);
if (value != null) {
notNull = true;
}
}
if (notNull) {
ctx.propagateState(embeddedBean);
return embeddedBean;
} else {
return null;
}
}
@Override
void appendFrom(DbSqlContext ctx, boolean forceOuterJoin) {
}
@Override
void appendSelect(DbSqlContext ctx, boolean subQuery) {
for (int i = 0; i < embeddedProps.length; i++) {
embeddedProps[i].appendSelect(ctx, subQuery);
}
}
}
/**
* For imported reference - this is the common case.
*/
private final class Reference extends LocalHelp {
//private final BeanPropertyAssocOne<?> beanProp;
Reference(BeanPropertyAssocOne<?> beanProp) {
// this.beanProp = beanProp;
}
void loadIgnore(DbReadContext ctx) {
targetIdBinder.loadIgnore(ctx);
if (targetInheritInfo != null) {
ctx.getDataReader().incrementPos(1);
}
}
Object readSet(DbReadContext ctx, Object bean, boolean assignable) throws SQLException {
Object val = read(ctx);
if (bean != null && assignable) {
setValue(bean, val);
ctx.propagateState(val);
}
return val;
}
/**
* Read and set a Reference bean.
*/
@Override
Object read(DbReadContext ctx) throws SQLException {
BeanDescriptor<?> rowDescriptor = null;
Class<?> rowType = targetType;
if (targetInheritInfo != null) {
// read discriminator to determine the type
InheritInfo rowInheritInfo = targetInheritInfo.readType(ctx);
if (rowInheritInfo != null) {
rowType = rowInheritInfo.getType();
rowDescriptor = rowInheritInfo.getBeanDescriptor();
}
}
// read the foreign key column(s)
Object id = targetIdBinder.read(ctx);
if (id == null) {
return null;
}
// check transaction context to see if it already exists
Object existing = ctx.getPersistenceContext().get(rowType, id);
if (existing != null) {
return existing;
}
// parent always null for this case (but here to document)
Object parent = null;
boolean vanillaMode = ctx.isVanillaMode();
//ReferenceOptions options = ctx.getReferenceOptionsFor(beanProp);
Boolean readOnly = ctx.isReadOnly();
Object ref;
if (targetInheritInfo != null) {
// for inheritance hierarchy create the correct type for this row...
ref = rowDescriptor.createReference(vanillaMode, readOnly, id, parent);
} else {
ref = targetDescriptor.createReference(vanillaMode, readOnly, id, parent);
}
Object existingBean = ctx.getPersistenceContext().putIfAbsent(id, ref);
if (existingBean != null) {
// advanced case when we use multiple concurrent threads to
// build a single object graph, and another thread has since
// loaded a matching bean so we will use that instead.
ref = existingBean;
} else if (!vanillaMode){
EntityBeanIntercept ebi = ((EntityBean) ref)._ebean_getIntercept();
if (Boolean.TRUE.equals(ctx.isReadOnly())){
ebi.setReadOnly(true);
}
ctx.register(name, ebi);
}
return ref;
}
@Override
void appendFrom(DbSqlContext ctx, boolean forceOuterJoin) {
if (targetInheritInfo != null) {
// add join to support the discriminator column
String relativePrefix = ctx.getRelativePrefix(name);
tableJoin.addJoin(forceOuterJoin, relativePrefix, ctx);
}
}
/**
* Append columns for foreign key columns.
*/
@Override
void appendSelect(DbSqlContext ctx, boolean subQuery) {
if (!subQuery && targetInheritInfo != null) {
// add discriminator column
String relativePrefix = ctx.getRelativePrefix(getName());
String tableAlias = ctx.getTableAlias(relativePrefix);
ctx.appendColumn(tableAlias, targetInheritInfo.getDiscriminatorColumn());
}
importedId.sqlAppend(ctx);
}
}
/**
* For OneToOne exported reference - not so common.
*/
private final class ReferenceExported extends LocalHelp {
@Override
void loadIgnore(DbReadContext ctx) {
targetDescriptor.getIdBinder().loadIgnore(ctx);
}
/**
* Read and set a Reference bean.
*/
@Override
Object readSet(DbReadContext ctx, Object bean, boolean assignable) throws SQLException {
Object dbVal = read(ctx);
if (bean != null && assignable) {
setValue(bean, dbVal);
ctx.propagateState(dbVal);
}
return dbVal;
}
@Override
Object read(DbReadContext ctx) throws SQLException {
// TODO: Support for Inheritance hierarchy on exported OneToOne ?
IdBinder idBinder = targetDescriptor.getIdBinder();
Object id = idBinder.read(ctx);
if (id == null) {
return null;
}
PersistenceContext persistCtx = ctx.getPersistenceContext();
Object existing = persistCtx.get(targetType, id);
if (existing != null) {
return existing;
}
boolean vanillaMode = ctx.isVanillaMode();
Object parent = null;
Object ref = targetDescriptor.createReference(vanillaMode, ctx.isReadOnly(), id, parent);
if (!vanillaMode){
EntityBeanIntercept ebi = ((EntityBean) ref)._ebean_getIntercept();
if (Boolean.TRUE.equals(ctx.isReadOnly())) {
ebi.setReadOnly(true);
}
persistCtx.put(id, ref);
ctx.register(name, ebi);
}
return ref;
}
/**
* Append columns for foreign key columns.
*/
@Override
void appendSelect(DbSqlContext ctx, boolean subQuery) {
// set appropriate tableAlias for
// the exported id columns
String relativePrefix = ctx.getRelativePrefix(getName());
ctx.pushTableAlias(relativePrefix);
IdBinder idBinder = targetDescriptor.getIdBinder();
idBinder.appendSelect(ctx, subQuery);
ctx.popTableAlias();
}
@Override
void appendFrom(DbSqlContext ctx, boolean forceOuterJoin) {
String relativePrefix = ctx.getRelativePrefix(getName());
tableJoin.addJoin(forceOuterJoin, relativePrefix, ctx);
}
}
@Override
public void jsonWrite(WriteJsonContext ctx, Object bean) {
Object value = getValueIntercept(bean);
if (value == null){
ctx.beginAssocOneIsNull(name);
} else {
if (ctx.isParentBean(value)){
// bi-directional and already rendered parent
} else {
ctx.pushParentBean(bean);
ctx.beginAssocOne(name);
BeanDescriptor<?> refDesc = descriptor.getBeanDescriptor(value.getClass());
refDesc.jsonWrite(ctx, value);
ctx.endAssocOne();
ctx.popParentBean();
}
}
}
@Override
public void jsonRead(ReadJsonContext ctx, Object bean){
T assocBean = targetDescriptor.jsonReadBean(ctx, name);
setValue(bean, assocBean);
}
}
@@ -0,0 +1,229 @@
/**
* Copyright (C) 2009 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.config.ScalarTypeConverter;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanPropertyCompound;
import com.avaje.ebeaninternal.server.el.ElPropertyChainBuilder;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
import com.avaje.ebeaninternal.server.query.SqlBeanLoad;
import com.avaje.ebeaninternal.server.text.json.ReadJsonContext;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
import com.avaje.ebeaninternal.server.type.CtCompoundProperty;
import com.avaje.ebeaninternal.server.type.CtCompoundPropertyElAdapter;
import com.avaje.ebeaninternal.server.type.CtCompoundType;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
/**
* Property mapped to an Immutable Compound Value Object.
* <p>
* An Immutable Compound Value Object is similar to an Embedded bean but it
* doesn't require enhancement and MUST be treated as an Immutable type.
* </p>
*/
public class BeanPropertyCompound extends BeanProperty {
private final CtCompoundType<?> compoundType;
/**
* Type Converter for scala.Option and similar type wrapping.
*/
@SuppressWarnings("rawtypes")
private final ScalarTypeConverter typeConverter;
private final BeanProperty[] scalarProperties;
private final LinkedHashMap<String, BeanProperty> propertyMap = new LinkedHashMap<String, BeanProperty>();
private final LinkedHashMap<String, CtCompoundPropertyElAdapter> nonScalarMap = new LinkedHashMap<String, CtCompoundPropertyElAdapter>();
private final BeanPropertyCompoundRoot root;
/**
* Create the property.
*/
public BeanPropertyCompound(BeanDescriptorMap owner, BeanDescriptor<?> descriptor, DeployBeanPropertyCompound deploy) {
super(owner, descriptor, deploy);
this.compoundType = deploy.getCompoundType();
this.typeConverter = deploy.getTypeConverter();
this.root = deploy.getFlatProperties(owner, descriptor);
this.scalarProperties = root.getScalarProperties();
for (int i = 0; i < scalarProperties.length; i++) {
propertyMap.put(scalarProperties[i].getName(), scalarProperties[i]);
}
List<CtCompoundProperty> nonScalarPropsList = root.getNonScalarProperties();
for (int i = 0; i < nonScalarPropsList.size(); i++) {
CtCompoundProperty ctProp = nonScalarPropsList.get(i);
CtCompoundPropertyElAdapter adapter = new CtCompoundPropertyElAdapter(ctProp);
nonScalarMap.put(ctProp.getRelativeName(), adapter);
}
}
@Override
public void initialise() {
// do nothing for normal BeanProperty
if (!isTransient && compoundType == null) {
String msg = "No cvoInternalType assigned to " + descriptor.getFullName() + "." + getName();
throw new RuntimeException(msg);
}
}
@Override
public void setDeployOrder(int deployOrder) {
this.deployOrder = deployOrder;
for (CtCompoundPropertyElAdapter adapter : nonScalarMap.values()) {
adapter.setDeployOrder(deployOrder);
}
}
/**
* Get the underlying compound type.
*/
@SuppressWarnings("unchecked")
public Object getValueUnderlying(Object bean) {
Object value = getValue(bean);
if (typeConverter != null){
value = typeConverter.unwrapValue(value);
}
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) {
chain = new ElPropertyChainBuilder(true, propName);
}
// first add this property
chain.add(this);
// handle all the rest of the chain handled by the
// BeanProperty (all depth for nested compound type)
BeanProperty p = propertyMap.get(remainder);
if (p != null) {
return chain.add(p).build();
}
CtCompoundPropertyElAdapter elAdapter = nonScalarMap.get(remainder);
if (elAdapter == null) {
throw new RuntimeException("property [" + remainder + "] not found in " + getFullBeanName());
}
return chain.add(elAdapter).build();
}
@Override
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
if (!isTransient) {
for (int i = 0; i < scalarProperties.length; i++) {
scalarProperties[i].appendSelect(ctx, subQuery);
}
}
}
public BeanProperty[] getScalarProperties() {
return scalarProperties;
}
@Override
public Object readSet(DbReadContext ctx, Object bean, Class<?> type) throws SQLException {
boolean assignable = (type == null || owningType.isAssignableFrom(type));
Object v = compoundType.read(ctx.getDataReader());
if (assignable) {
setValue(bean, v);
}
return v;
}
/**
* Read the data from the resultSet effectively ignoring it and returning
* null.
*/
@SuppressWarnings("unchecked")
@Override
public Object read(DbReadContext ctx) throws SQLException {
Object v = compoundType.read(ctx.getDataReader());
if (typeConverter != null){
v = typeConverter.wrapValue(v);
}
return v;
}
@Override
public void loadIgnore(DbReadContext ctx) {
compoundType.loadIgnore(ctx.getDataReader());
}
@Override
public void load(SqlBeanLoad sqlBeanLoad) throws SQLException {
sqlBeanLoad.load(this);
}
@Override
public Object elGetReference(Object bean) {
return bean;
}
public void jsonWrite(WriteJsonContext ctx, Object bean) {
Object valueObject = getValueIntercept(bean);
compoundType.jsonWrite(ctx, valueObject, name);
}
public void jsonRead(ReadJsonContext ctx, Object bean){
Object objValue = compoundType.jsonRead(ctx);
setValue(bean, objValue);
}
}
@@ -0,0 +1,129 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import com.avaje.ebeaninternal.server.reflect.BeanReflectSetter;
import com.avaje.ebeaninternal.server.type.CtCompoundProperty;
/**
* Represents the root BeanProperty for properties of a compound type.
* <p>
* Holds all the scalar and non-scalar properties of the compound type. The
* scalar properties match to DB columns and the non-scalar ones are here solely
* to support EL expression language for nested compound types.
* </p>
*
* @author rbygrave
*/
public class BeanPropertyCompoundRoot {
private final BeanReflectSetter setter;
/**
* The method used to write the property.
*/
private final Method writeMethod;
private final String name;
private final String fullBeanName;
private final LinkedHashMap<String, BeanPropertyCompoundScalar> propMap;
private final ArrayList<BeanPropertyCompoundScalar> propList;
private List<CtCompoundProperty> nonScalarProperties;
public BeanPropertyCompoundRoot(DeployBeanProperty deploy) {
this.fullBeanName = deploy.getFullBeanName();
this.name = deploy.getName();
this.setter = deploy.getSetter();
this.writeMethod = deploy.getWriteMethod();
this.propList = new ArrayList<BeanPropertyCompoundScalar>();
this.propMap = new LinkedHashMap<String, BeanPropertyCompoundScalar>();
}
public BeanProperty[] getScalarProperties() {
return propList.toArray(new BeanProperty[propList.size()]);
}
public void register(BeanPropertyCompoundScalar prop) {
propList.add(prop);
propMap.put(prop.getName(), prop);
}
public BeanPropertyCompoundScalar getCompoundScalarProperty(String propName) {
return propMap.get(propName);
}
public List<CtCompoundProperty> getNonScalarProperties() {
return nonScalarProperties;
}
public void setNonScalarProperties(List<CtCompoundProperty> nonScalarProperties) {
this.nonScalarProperties = nonScalarProperties;
}
/**
* Set the value of the property without interception or
* PropertyChangeSupport.
*/
public void setRootValue(Object 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);
}
} catch (Exception ex) {
String beanType = bean == null ? "null" : bean.getClass().getName();
String msg = "set " + name + " with arg[" + value + "] on ["+fullBeanName+"] with type[" + beanType + "] threw error";
throw new RuntimeException(msg, ex);
}
}
/**
* Set the value of the property.
*/
public void setRootValueIntercept(Object 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);
}
} catch (Exception ex) {
String beanType = bean == null ? "null" : bean.getClass().getName();
String msg = "setIntercept " + name + " arg[" + value + "] on ["+fullBeanName+"] with type[" + beanType + "] threw error";
throw new RuntimeException(msg, ex);
}
}
}
@@ -0,0 +1,120 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.config.ScalarTypeConverter;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import com.avaje.ebeaninternal.server.type.CtCompoundProperty;
/**
* A BeanProperty owned by a Compound value object that maps to
* a real scalar type.
*
* @author rbygrave
*/
public class BeanPropertyCompoundScalar extends BeanProperty {
private final BeanPropertyCompoundRoot rootProperty;
private final CtCompoundProperty ctProperty;
@SuppressWarnings("rawtypes")
private final ScalarTypeConverter typeConverter;
public BeanPropertyCompoundScalar(BeanPropertyCompoundRoot rootProperty, DeployBeanProperty scalarDeploy,
CtCompoundProperty ctProperty, ScalarTypeConverter<?, ?> typeConverter) {
super(scalarDeploy);
this.rootProperty = rootProperty;
this.ctProperty = ctProperty;
this.typeConverter = typeConverter;
}
@SuppressWarnings("unchecked")
@Override
public Object getValue(Object valueObject) {
if (typeConverter != null){
valueObject = typeConverter.unwrapValue(valueObject);
}
return ctProperty.getValue(valueObject);
}
@Override
public void setValue(Object bean, Object value) {
setValueInCompound(bean, value, false);
}
@SuppressWarnings("unchecked")
public void setValueInCompound(Object bean, Object value, boolean intercept) {
Object compoundValue = ctProperty.setValue(bean, value);
if (compoundValue != null){
if (typeConverter != null){
compoundValue = typeConverter.wrapValue(compoundValue);
}
// we are at the top level and we have a compound value
// that we can set using the root property
if (intercept){
rootProperty.setRootValueIntercept(bean, compoundValue);
} else {
rootProperty.setRootValue(bean, compoundValue);
}
}
}
/**
* No interception on embedded scalar values inside a CVO.
*/
@Override
public void setValueIntercept(Object bean, Object value) {
setValueInCompound(bean, value, true);
}
/**
* No interception on embedded scalar values inside a CVO.
*/
@Override
public Object getValueIntercept(Object bean) {
return getValue(bean);
}
@Override
public Object elGetReference(Object bean) {
return getValue(bean);
}
@Override
public Object elGetValue(Object 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);
}
}
@@ -0,0 +1,64 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
/**
* Used hold meta data when a bean property is overridden.
* <p>
* Typically this is for Embedded Beans.
* </p>
*/
public class BeanPropertyOverride {
private final String dbColumn;
private final String sqlFormulaSelect;
private final String sqlFormulaJoin;
public BeanPropertyOverride(String dbColumn) {
this(dbColumn, null, null);
}
public BeanPropertyOverride(String dbColumn, String sqlFormulaSelect, String sqlFormulaJoin) {
this.dbColumn = InternString.intern(dbColumn);
this.sqlFormulaSelect = InternString.intern(sqlFormulaSelect);
this.sqlFormulaJoin = InternString.intern(sqlFormulaJoin);
}
public String getDbColumn() {
return dbColumn;
}
public String getSqlFormulaSelect() {
return sqlFormulaSelect;
}
public String getSqlFormulaJoin() {
return sqlFormulaJoin;
}
public String replace(String src, String srcDbColumn){
return StringHelper.replaceString(src, srcDbColumn, dbColumn);
}
}
@@ -0,0 +1,99 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.util.Iterator;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import com.avaje.ebean.bean.BeanCollectionAdd;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanPropertySimpleCollection;
import com.avaje.ebeaninternal.server.ldap.LdapPersistenceException;
import com.avaje.ebeaninternal.server.type.ScalarType;
public class BeanPropertySimpleCollection<T> extends BeanPropertyAssocMany<T> {
private final ScalarType<T> collectionScalarType;
public BeanPropertySimpleCollection(BeanDescriptorMap owner, BeanDescriptor<?> descriptor, DeployBeanPropertySimpleCollection<T> deploy) {
super(owner, descriptor, deploy);
this.collectionScalarType = deploy.getCollectionScalarType();
}
public void initialise() {
super.initialise();
}
@Override
public Attribute createAttribute(Object bean) {
Object v = getValue(bean);
if (v == null){
return null;
}
if (ldapAttributeAdapter != null){
return ldapAttributeAdapter.createAttribute(v);
}
BasicAttribute attrs = new BasicAttribute(getDbColumn());
Iterator<?> it = help.getIterator(v);
if (it != null){
while (it.hasNext()) {
Object beanValue = it.next();
Object attrValue = collectionScalarType.toJdbcType(beanValue);
attrs.add(attrValue);
}
}
return attrs;
}
@Override
public void setAttributeValue(Object bean, Attribute attr) {
try {
if (attr != null){
Object beanValue;
if (ldapAttributeAdapter != null){
beanValue = ldapAttributeAdapter.readAttribute(attr);
} else {
boolean vanilla = true;
beanValue = help.createEmpty(vanilla);
BeanCollectionAdd collAdd = help.getBeanCollectionAdd(beanValue, mapKey);
NamingEnumeration<?> en = attr.getAll();
while (en.hasMoreElements()) {
Object attrValue = (Object) en.nextElement();
Object collValue = collectionScalarType.toBeanType(attrValue);
collAdd.addBean(collValue);
}
}
setValue(bean, beanValue);
}
} catch (NamingException e) {
throw new LdapPersistenceException(e);
}
}
}
@@ -0,0 +1,61 @@
/**
* Copyright (C) 2009 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.util.List;
import java.util.logging.Logger;
import com.avaje.ebean.event.BeanQueryAdapter;
import com.avaje.ebeaninternal.server.core.BootupClasses;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanDescriptor;
/**
* Default implementation for creating BeanControllers.
*/
public class BeanQueryAdapterManager {
private static final Logger logger = Logger.getLogger(BeanQueryAdapterManager.class.getName());
private final List<BeanQueryAdapter> list;
public BeanQueryAdapterManager(BootupClasses bootupClasses){
list = bootupClasses.getBeanQueryAdapters();
}
public int getRegisterCount() {
return list.size();
}
/**
* Return the BeanPersistController for a given entity type.
*/
public void addQueryAdapter(DeployBeanDescriptor<?> deployDesc){
for (int i = 0; i < list.size(); i++) {
BeanQueryAdapter c = list.get(i);
if (c.isRegisterFor(deployDesc.getBeanType())){
logger.fine("BeanQueryAdapter on[" + deployDesc.getFullName() + "] " + c.getClass().getName());
deployDesc.addQueryAdapter(c);
}
}
}
}
@@ -0,0 +1,174 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.InvalidValue;
import com.avaje.ebean.Query;
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.common.BeanSet;
import com.avaje.ebeaninternal.server.text.json.WriteJsonContext;
/**
* Helper specifically for dealing with Sets.
*/
public final class BeanSetHelp<T> implements BeanCollectionHelp<T> {
private final BeanPropertyAssocMany<T> many;
private final BeanDescriptor<T> targetDescriptor;
private BeanCollectionLoader loader;
/**
* When attached to a specific many property.
*/
public BeanSetHelp(BeanPropertyAssocMany<T> many){
this.many = many;
this.targetDescriptor = many.getTargetDescriptor();
}
/**
* For a query that returns a set.
*/
public BeanSetHelp(){
this.many = null;
this.targetDescriptor = null;
}
public void setLoader(BeanCollectionLoader loader){
this.loader = loader;
}
public Iterator<?> getIterator(Object collection) {
return ((Set<?>) collection).iterator();
}
public BeanCollectionAdd getBeanCollectionAdd(Object bc,String mapKey) {
if (bc instanceof BeanSet<?>){
BeanSet<?> beanSet = (BeanSet<?>)bc;
if (beanSet.getActualSet() == null){
beanSet.setActualSet(new LinkedHashSet<Object>());
}
return beanSet;
} else if (bc instanceof Set<?>) {
return new VanillaAdd((Set<?>)bc);
} else {
throw new RuntimeException("Unhandled type "+bc);
}
}
@SuppressWarnings("unchecked")
static class VanillaAdd implements BeanCollectionAdd {
@SuppressWarnings("rawtypes")
private final Set set;
private VanillaAdd(Set<?> set) {
this.set = set;
}
public void addBean(Object bean) {
set.add(bean);
}
}
public void add(BeanCollection<?> collection, Object bean) {
collection.internalAdd(bean);
}
public Object createEmpty(boolean vanilla) {
return vanilla ? new LinkedHashSet<T>() : new BeanSet<T>();
}
public BeanCollection<T> createReference(Object parentBean, String propertyName) {
return new BeanSet<T>(loader, parentBean, propertyName);
}
public ArrayList<InvalidValue> validate(Object manyValue) {
ArrayList<InvalidValue> errs = null;
Set<?> set = (Set<?>)manyValue;
Iterator<?> i = set.iterator();
while (i.hasNext()) {
Object detailBean = i.next();
InvalidValue invalid = targetDescriptor.validate(true, detailBean);
if (invalid != null){
if (errs == null){
errs = new ArrayList<InvalidValue>();
}
errs.add(invalid);
}
}
return errs;
}
public void refresh(EbeanServer server, Query<?> query, Transaction t, Object parentBean) {
BeanSet<?> newBeanSet = (BeanSet<?>)server.findSet(query, t);
refresh(newBeanSet, parentBean);
}
public void refresh(BeanCollection<?> bc, Object parentBean) {
BeanSet<?> newBeanSet = (BeanSet<?>)bc;
Set<?> current = (Set<?>)many.getValueUnderlying(parentBean);
newBeanSet.setModifyListening(many.getModifyListenMode());
if (current == null){
// the currentList is null? Not really expecting this...
many.setValue(parentBean,newBeanSet);
} else if (current instanceof BeanSet<?>) {
// normally this case, replace just the underlying list
BeanSet<?> currentBeanSet = (BeanSet<?>)current;
currentBeanSet.setActualSet(newBeanSet.getActualSet());
currentBeanSet.setModifyListening(many.getModifyListenMode());
} else {
// replace the entire set
many.setValue(parentBean, newBeanSet);
}
}
public void jsonWrite(WriteJsonContext ctx, String name, Object collection, boolean explicitInclude) {
Set<?> set;
if (collection instanceof BeanCollection<?>){
BeanSet<?> bc = (BeanSet<?>)collection;
if (!bc.isPopulated()){
if (explicitInclude){
// invoke lazy loading as collection
// is explicitly included in the output
bc.size();
} else {
return;
}
}
set = bc.getActualSet();
} else {
set = (Set<?>)collection;
}
int count = 0;
ctx.beginAssocMany(name);
Iterator<?> it = set.iterator();
while (it.hasNext()) {
Object detailBean = it.next();
if (count++ > 0){
ctx.appendComma();
}
targetDescriptor.jsonWrite(ctx, detailBean);
}
ctx.endAssocMany();
}
}
@@ -0,0 +1,88 @@
package com.avaje.ebeaninternal.server.deploy;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
public class BeanSqlSelect {
public static final String HAVING_PREDICATES = "${HAVING_PREDICATES}";
public static final String WHERE_PREDICATES = "${WHERE_PREDICATES}";
public static final String AND_PREDICATES = "${AND_PREDICATES}";
public static final String ORDER_BY = "${ORDER_BY}";
public enum PredicatesType {
HAVING, WHERE, AND, NONE
}
final String sql;
final PredicatesType predicatesType;
final boolean hasOrderBy;
public BeanSqlSelect(String sql, PredicatesType predicatesType, boolean hasOrderBy) {
this.sql = sql;
this.predicatesType = predicatesType;
this.hasOrderBy = hasOrderBy;
}
public String getSql() {
return sql;
}
public PredicatesType getPredicatesType() {
return predicatesType;
}
public boolean hasOrderBy() {
return hasOrderBy;
}
public String addPredicates(String query, String predicates) {
if (predicates == null) {
switch (predicatesType) {
case HAVING:
return StringHelper.replaceString(query, HAVING_PREDICATES, "");
case WHERE:
return StringHelper.replaceString(query, WHERE_PREDICATES, "");
case AND:
return StringHelper.replaceString(query, AND_PREDICATES, "");
case NONE:
return query;
default:
throw new PersistenceException("predicatesType " + predicatesType + " not handled");
}
} else {
switch (predicatesType) {
case HAVING:
return StringHelper
.replaceString(query, HAVING_PREDICATES, " HAVING " + predicates);
case WHERE:
return StringHelper.replaceString(query, WHERE_PREDICATES, " WHERE " + predicates);
case AND:
return StringHelper.replaceString(query, AND_PREDICATES, " AND " + predicates);
case NONE:
return query;
default:
throw new PersistenceException("predicatesType " + predicatesType + " not handled");
}
}
}
public String addOrderBy(String query, String orderBy) {
if (!hasOrderBy) {
return query;
}
if (orderBy == null) {
return StringHelper.replaceString(query, ORDER_BY, "");
} else {
return StringHelper.replaceString(query, ORDER_BY, " ORDER BY " + orderBy);
}
}
}
@@ -0,0 +1,59 @@
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebeaninternal.server.deploy.BeanSqlSelect.PredicatesType;
public class BeanSqlSelectFactory {
public static BeanSqlSelect create(String sql){
sql = trim(sql);
PredicatesType predicatesType = determinePredicatesType(sql);
boolean hasOrderBy = determineHasOrderBy(sql);
return new BeanSqlSelect(sql, predicatesType, hasOrderBy);
}
private static boolean determineHasOrderBy(String sql){
return sql.indexOf(BeanSqlSelect.ORDER_BY) > 0;
}
private static PredicatesType determinePredicatesType(String sql){
if (sql.indexOf(BeanSqlSelect.HAVING_PREDICATES) > 0){
return PredicatesType.HAVING;
}
if (sql.indexOf(BeanSqlSelect.WHERE_PREDICATES) > 0){
return PredicatesType.WHERE;
}
if (sql.indexOf(BeanSqlSelect.AND_PREDICATES) > 0){
return PredicatesType.AND;
}
return PredicatesType.NONE;
}
private static String trim(String sql) {
boolean removeWhitespace = false;
int length = sql.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
char c = sql.charAt(i);
if (removeWhitespace){
if (!Character.isWhitespace(c)){
sb.append(c);
removeWhitespace = false;
}
} else {
if (c == '\r' || c == '\n'){
sb.append('\n');
removeWhitespace = true;
} else {
sb.append(c);
}
}
}
return sb.toString();
}
}
@@ -0,0 +1,142 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanTable;
import com.avaje.ebeaninternal.server.deploy.meta.DeployTableJoin;
import com.avaje.ebeaninternal.server.deploy.meta.DeployTableJoinColumn;
/**
* Used for associated beans in place of a BeanDescriptor. This is done to avoid
* recursion issues due to the potentially bi-directional and circular
* relationships between beans.
* <p>
* It holds the main deployment information and not all the detail that is held
* in a BeanDescriptor.
* </p>
*/
public class BeanTable {
private static final Logger logger = Logger.getLogger(BeanTable.class.getName());
private final Class<?> beanType;
/**
* The base table.
*/
private final String baseTable;
private final BeanProperty[] idProperties;
/**
* Create the BeanTable.
*/
public BeanTable(DeployBeanTable mutable, BeanDescriptorMap owner) {
this.beanType = mutable.getBeanType();
this.baseTable = InternString.intern(mutable.getBaseTable());
this.idProperties = mutable.createIdProperties(owner);
}
public String toString(){
return baseTable;
}
/**
* Return the base table for this BeanTable.
* This is used to determine the join information
* for associations.
*/
public String getBaseTable() {
return baseTable;
}
/**
* Gets the unqualified base table.
*
* @return the unqualified base table
*/
public String getUnqualifiedBaseTable(){
final String[] chunks = baseTable.split("\\.");
return chunks.length == 2 ? chunks[1] :chunks[0];
}
/**
* Return the Id properties.
*/
public BeanProperty[] getIdProperties() {
return idProperties;
}
/**
* Return the class for this beanTable.
*/
public Class<?> getBeanType() {
return beanType;
}
public void createJoinColumn(String foreignKeyPrefix, DeployTableJoin join, boolean reverse) {
boolean complexKey = false;
BeanProperty[] props = idProperties;
if (idProperties.length == 1){
if (idProperties[0] instanceof BeanPropertyAssocOne<?>) {
BeanPropertyAssocOne<?> assocOne = (BeanPropertyAssocOne<?>)idProperties[0];
props = assocOne.getProperties();
complexKey = true;
}
}
for (int i = 0; i < props.length; i++) {
String lc = props[i].getDbColumn();
String fk = lc;
if (foreignKeyPrefix != null){
fk = foreignKeyPrefix+"_"+fk;
}
if (complexKey){
// check to see if we want prefixes by default with complex keys
boolean usePrefixOnComplex = GlobalProperties.getBoolean("ebean.prefixComplexKeys", false);
if (!usePrefixOnComplex){
// just to copy the column name rather than prefix with the foreignKeyPrefix.
// I think that with complex keys this is the more common approach.
String msg = "On table["+baseTable+"] foreign key column ["+lc+"]";
logger.log(Level.FINE, msg);
fk = lc;
}
}
DeployTableJoinColumn joinCol = new DeployTableJoinColumn(lc, fk);
if (reverse){
joinCol = joinCol.reverse();
}
join.addJoinColumn(joinCol);
}
}
}
@@ -0,0 +1,155 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import com.avaje.ebean.event.BeanPersistController;
import com.avaje.ebean.event.BeanPersistRequest;
public class ChainedBeanPersistController implements BeanPersistController {
private static final Sorter SORTER = new Sorter();
private final List<BeanPersistController> list;
private final BeanPersistController[] chain;
/**
* Construct adding 2 BeanPersistController's.
*/
public ChainedBeanPersistController(BeanPersistController c1, BeanPersistController c2) {
this(addList(c1, c2));
}
/**
* Helper method used to create a list from 2 BeanPersistController's.
*/
private static List<BeanPersistController> addList(BeanPersistController c1, BeanPersistController c2) {
ArrayList<BeanPersistController> addList = new ArrayList<BeanPersistController>(2);
addList.add(c1);
addList.add(c2);
return addList;
}
/**
* Construct given the list of BeanPersistController's.
* @param list
*/
public ChainedBeanPersistController(List<BeanPersistController> list) {
this.list = list;
BeanPersistController[] c = list.toArray(new BeanPersistController[list.size()]);
Arrays.sort(c, SORTER);
this.chain = c;
}
/**
* Register a new BeanPersistController and return the resulting chain.
*/
public ChainedBeanPersistController register(BeanPersistController c) {
if (list.contains(c)){
return this;
} else {
ArrayList<BeanPersistController> newList = new ArrayList<BeanPersistController>();
newList.addAll(list);
newList.add(c);
return new ChainedBeanPersistController(newList);
}
}
/**
* De-register a BeanPersistController and return the resulting chain.
*/
public ChainedBeanPersistController deregister(BeanPersistController c) {
if (!list.contains(c)){
return this;
} else {
ArrayList<BeanPersistController> newList = new ArrayList<BeanPersistController>();
newList.addAll(list);
newList.remove(c);
return new ChainedBeanPersistController(newList);
}
}
/**
* Always returns 0 (not used for this object).
*/
public int getExecutionOrder() {
return 0;
}
/**
* Always returns false (not used for this object).
*/
public boolean isRegisterFor(Class<?> cls) {
return false;
}
public void postDelete(BeanPersistRequest<?> request) {
for (int i = 0; i < chain.length; i++) {
chain[i].postDelete(request);
}
}
public void postInsert(BeanPersistRequest<?> request) {
for (int i = 0; i < chain.length; i++) {
chain[i].postInsert(request);
}
}
public void postLoad(Object bean, Set<String> includedProperties) {
for (int i = 0; i < chain.length; i++) {
chain[i].postLoad(bean, includedProperties);
}
}
public void postUpdate(BeanPersistRequest<?> request) {
for (int i = 0; i < chain.length; i++) {
chain[i].postUpdate(request);
}
}
public boolean preDelete(BeanPersistRequest<?> request) {
for (int i = 0; i < chain.length; i++) {
if (!chain[i].preDelete(request)) {
return false;
}
}
return true;
}
public boolean preInsert(BeanPersistRequest<?> request) {
for (int i = 0; i < chain.length; i++) {
if (!chain[i].preInsert(request)) {
return false;
}
}
return true;
}
public boolean preUpdate(BeanPersistRequest<?> request) {
for (int i = 0; i < chain.length; i++) {
if (!chain[i].preUpdate(request)) {
return false;
}
}
return true;
}
/**
* Helper to order the BeanPersistController's in a chain.
*/
private static class Sorter implements Comparator<BeanPersistController> {
public int compare(BeanPersistController o1, BeanPersistController o2) {
int i1 = o1.getExecutionOrder() ;
int i2 = o2.getExecutionOrder() ;
return (i1<i2 ? -1 : (i1==i2 ? 0 : 1));
}
}
}
@@ -0,0 +1,122 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.avaje.ebean.event.BeanPersistListener;
/**
* Handles multiple BeanPersistListener's for a given entity type.
*/
public class ChainedBeanPersistListener<T> implements BeanPersistListener<T> {
private final List<BeanPersistListener<T>> list;
private final BeanPersistListener<T>[] chain;
/**
* Construct adding 2 BeanPersistController's.
*/
public ChainedBeanPersistListener(BeanPersistListener<T> c1, BeanPersistListener<T> c2) {
this(addList(c1, c2));
}
/**
* Helper method used to create a list from 2 BeanPersistListener.
*/
private static <T> List<BeanPersistListener<T>> addList(BeanPersistListener<T> c1, BeanPersistListener<T> c2) {
ArrayList<BeanPersistListener<T>> addList = new ArrayList<BeanPersistListener<T>>(2);
addList.add(c1);
addList.add(c2);
return addList;
}
/**
* Construct given the list of BeanPersistController's.
* @param list
*/
@SuppressWarnings("unchecked")
public ChainedBeanPersistListener(List<BeanPersistListener<T>> list) {
this.list = list;
this.chain = list.toArray(new BeanPersistListener[list.size()]);
}
/**
* Register a new BeanPersistController and return the resulting chain.
*/
public ChainedBeanPersistListener<T> register(BeanPersistListener<T> c) {
if (list.contains(c)){
return this;
} else {
List<BeanPersistListener<T>> newList = new ArrayList<BeanPersistListener<T>>();
newList.addAll(list);
newList.add(c);
return new ChainedBeanPersistListener<T>(newList);
}
}
/**
* De-register a BeanPersistController and return the resulting chain.
*/
public ChainedBeanPersistListener<T> deregister(BeanPersistListener<T> c) {
if (!list.contains(c)){
return this;
} else {
ArrayList<BeanPersistListener<T>> newList = new ArrayList<BeanPersistListener<T>>();
newList.addAll(list);
newList.remove(c);
return new ChainedBeanPersistListener<T>(newList);
}
}
public boolean deleted(T bean) {
boolean notifyCluster = false;
for (int i = 0; i < chain.length; i++) {
if (chain[i].deleted(bean)) {
notifyCluster = true;
}
}
return notifyCluster;
}
public boolean inserted(T bean) {
boolean notifyCluster = false;
for (int i = 0; i < chain.length; i++) {
if (chain[i].inserted(bean)) {
notifyCluster = true;
}
}
return notifyCluster;
}
public void remoteDelete(Object id) {
for (int i = 0; i < chain.length; i++) {
chain[i].remoteDelete(id);
}
}
public void remoteInsert(Object id) {
for (int i = 0; i < chain.length; i++) {
chain[i].remoteInsert(id);
}
}
public void remoteUpdate(Object id) {
for (int i = 0; i < chain.length; i++) {
chain[i].remoteUpdate(id);
}
}
public boolean updated(T bean, Set<String> updatedProperties) {
boolean notifyCluster = false;
for (int i = 0; i < chain.length; i++) {
if (chain[i].updated(bean, updatedProperties)) {
notifyCluster = true;
}
}
return notifyCluster;
}
}
@@ -0,0 +1,113 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import com.avaje.ebean.event.BeanQueryAdapter;
import com.avaje.ebean.event.BeanQueryRequest;
/**
* Handles multiple BeanQueryAdapter for a given entity type.
*/
public class ChainedBeanQueryAdapter implements BeanQueryAdapter {
private static final Sorter SORTER = new Sorter();
private final List<BeanQueryAdapter> list;
private final BeanQueryAdapter[] chain;
/**
* Construct adding 2 BeanQueryAdapter's.
*/
public ChainedBeanQueryAdapter(BeanQueryAdapter c1, BeanQueryAdapter c2) {
this(addList(c1, c2));
}
/**
* Helper method used to create a list from 2 BeanQueryAdapter.
*/
private static List<BeanQueryAdapter> addList(BeanQueryAdapter c1, BeanQueryAdapter c2) {
ArrayList<BeanQueryAdapter> addList = new ArrayList<BeanQueryAdapter>(2);
addList.add(c1);
addList.add(c2);
return addList;
}
/**
* Construct given the list of BeanQueryAdapter's.
* @param list
*/
public ChainedBeanQueryAdapter(List<BeanQueryAdapter> list) {
this.list = list;
BeanQueryAdapter[] c = list.toArray(new BeanQueryAdapter[list.size()]);
Arrays.sort(c, SORTER);
this.chain = c;
}
/**
* Register a new BeanQueryAdapter and return the resulting chain.
*/
public ChainedBeanQueryAdapter register(BeanQueryAdapter c) {
if (list.contains(c)){
return this;
} else {
List<BeanQueryAdapter> newList = new ArrayList<BeanQueryAdapter>();
newList.addAll(list);
newList.add(c);
return new ChainedBeanQueryAdapter(newList);
}
}
/**
* De-register a BeanQueryAdapter and return the resulting chain.
*/
public ChainedBeanQueryAdapter deregister(BeanQueryAdapter c) {
if (!list.contains(c)){
return this;
} else {
ArrayList<BeanQueryAdapter> newList = new ArrayList<BeanQueryAdapter>();
newList.addAll(list);
newList.remove(c);
return new ChainedBeanQueryAdapter(newList);
}
}
/**
* Return 0 as not used by this Chained adapter.
*/
public int getExecutionOrder() {
return 0;
}
/**
* Return false as only individual adapters are registered.
*/
public boolean isRegisterFor(Class<?> cls) {
return false;
}
public void preQuery(BeanQueryRequest<?> request) {
for (int i = 0; i < chain.length; i++) {
chain[i].preQuery(request);
}
}
/**
* Helper to order the BeanQueryAdapter's in a chain.
*/
private static class Sorter implements Comparator<BeanQueryAdapter> {
public int compare(BeanQueryAdapter o1, BeanQueryAdapter o2) {
int i1 = o1.getExecutionOrder() ;
int i2 = o2.getExecutionOrder() ;
return (i1<i2 ? -1 : (i1==i2 ? 0 : 1));
}
}
}
@@ -0,0 +1,43 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
/**
* Used to convert between collection types.
* <P>
* This typically means wrap and unwrap mutable scala collection types of Buffer, Set and Map.
* </p>
*
* @author rbygrave
*
*/
public interface CollectionTypeConverter {
/**
* Convert the wrapped type to the underlying Java List, Set or Map.
*/
public Object toUnderlying(Object wrapped);
/**
* Wrap the underlying Java List, Set or Map into the final collection type.
*/
public Object toWrapped(Object wrapped);
}
@@ -0,0 +1,40 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
/**
* Holds multiple column unique constraints defined for an entity.
*/
public class CompoundUniqueContraint {
private final String[] columns;
public CompoundUniqueContraint(String[] columns) {
this.columns = columns;
}
/**
* Return the columns that make up this unique constraint.
*/
public String[] getColumns() {
return columns;
}
}
@@ -0,0 +1,83 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.bean.PersistenceContext;
import com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext;
/**
* Provides context when performing a bean copy.
*
* @author rbygrave
*/
public class CopyContext {
private final boolean vanillaMode;
private final boolean sharing;
private final PersistenceContext pc;
public CopyContext(boolean vanillaMode, boolean sharing) {
this.vanillaMode = vanillaMode;
this.sharing = sharing;
this.pc = new DefaultPersistenceContext();
}
public CopyContext(boolean vanillaMode) {
this(vanillaMode, false);
}
/**
* Return true if the copy should be a vanilla bean.
*/
public boolean isVanillaMode() {
return vanillaMode;
}
/**
* Return true if the copy should be safe for sharing.
*/
public boolean isSharing() {
return sharing;
}
/**
* Return the persistence context used during the copy.
*/
public PersistenceContext getPersistenceContext() {
return pc;
}
/**
* Put the bean if absent into the persistence context.
*/
public Object putIfAbsent(Object id, Object bean){
return pc.putIfAbsent(id, bean);
}
/**
* Return the bean for the given type and id from the persistence context.
*/
public Object get(Class<?> beanType, Object beanId){
return pc.get(beanType, beanId);
}
}
@@ -0,0 +1,18 @@
package com.avaje.ebeaninternal.server.deploy;
/**
* A native query defined in deployment xml.
*/
public class DNativeQuery {
final String query;
public DNativeQuery(String query) {
this.query = query;
}
public String getQuery() {
return query;
}
}
@@ -0,0 +1,42 @@
/**
*
*/
package com.avaje.ebeaninternal.server.deploy;
public class DRawSqlColumnInfo {
final String name;
final String label;
final String propertyName;
final boolean scalarProperty;
public DRawSqlColumnInfo(String name, String label, String propertyName, boolean scalarProperty) {
this.name = name;
this.label = label;
this.propertyName = propertyName;
this.scalarProperty = scalarProperty;
}
public String getName() {
return name;
}
public String getLabel() {
return label;
}
public String getPropertyName() {
return propertyName;
}
public boolean isScalarProperty() {
return scalarProperty;
}
public String toString() {
return "name:" + name + " label:" + label + " prop:" + propertyName;
}
}
@@ -0,0 +1,139 @@
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.annotation.SqlSelect;
/**
* Meta data for a sql-select object.
* <p>
* Created from SqlSelect annotation or xml deployment.
* </p>
*/
public class DRawSqlMeta {
private String name;
private String tableAlias;
private String extend;
private String query;
private boolean debug;
private String where;
private String having;
private String columnMapping;
public DRawSqlMeta(SqlSelect sqlSelect) {
this.debug = sqlSelect.debug();
this.name = sqlSelect.name();
this.tableAlias = toNull(sqlSelect.tableAlias());
this.extend = toNull(sqlSelect.extend());
this.having = toNull(sqlSelect.having());
this.where = toNull(sqlSelect.where());
this.columnMapping = toNull(sqlSelect.columnMapping());
this.query = toNull(sqlSelect.query());
}
public DRawSqlMeta(String name, String extend, String query, boolean debug,
String where, String having, String columnMapping) {
this.name = name;
this.extend = extend;
this.query = query;
this.debug = debug;
this.having = having;
this.where = where;
this.columnMapping = columnMapping;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setTableAlias(String tableAlias) {
this.tableAlias = tableAlias;
}
public String getTableAlias() {
return tableAlias;
}
public String getExtend() {
return extend;
}
public void setExtend(String extend) {
this.extend = extend;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public String getWhere() {
return where;
}
public void setWhere(String where) {
this.where = where;
}
public String getHaving() {
return having;
}
public void setHaving(String having) {
this.having = having;
}
public String getColumnMapping() {
return columnMapping;
}
public void setColumnMapping(String columnMapping) {
this.columnMapping = columnMapping;
}
public void extend(DRawSqlMeta parentQuery){
extendQuery(parentQuery.getQuery());
extendColumnMapping(parentQuery.getColumnMapping());
}
/**
* Prepend sql from the parent query that this query 'extends'.
*/
private void extendQuery(String parentSql) {
if (query == null) {
query = parentSql;
} else {
query = parentSql + " " + query;
}
}
private void extendColumnMapping(String parentColumnMapping) {
if (columnMapping == null){
columnMapping = parentColumnMapping;
}
}
private static String toNull(String s) {
if (s != null && s.equals("")){
return null;
} else {
return s;
}
}
}
@@ -0,0 +1,281 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
import com.avaje.ebeaninternal.server.query.CQueryPredicates;
import com.avaje.ebeaninternal.server.query.SqlTree;
import com.avaje.ebeaninternal.server.query.SqlTreeNode;
import com.avaje.ebeaninternal.server.query.SqlTreeNodeRoot;
import com.avaje.ebeaninternal.server.query.SqlTreeProperties;
/**
* Represents a SqlSelect raw sql query.
*/
public class DRawSqlSelect {
private static final Logger logger = Logger.getLogger(DRawSqlSelect.class.getName());
private final BeanDescriptor<?> desc;
private final DRawSqlColumnInfo[] selectColumns;
private final Map<String,DRawSqlColumnInfo> columnMap;
private final String preWhereExprSql;
private final boolean andWhereExpr;
private final String preHavingExprSql;
private final boolean andHavingExpr;
private final String orderBySql;
private final String whereClause;
private final String havingClause;
private final String query;
private final String columnMapping;
private final String name;
private final SqlTree sqlTree;
private boolean withId;
private final String tableAlias;
public DRawSqlSelect(BeanDescriptor<?> desc, List<DRawSqlColumnInfo> selectColumns,
String tableAlias, String preWhereExprSql, boolean andWhereExpr, String preHavingExprSql,
boolean andHavingExpr, String orderBySql, DRawSqlMeta meta) {
this.desc = desc;
this.tableAlias = tableAlias;
this.selectColumns = selectColumns.toArray(new DRawSqlColumnInfo[selectColumns.size()]);
this.preHavingExprSql = preHavingExprSql;
this.preWhereExprSql = preWhereExprSql;
this.andHavingExpr = andHavingExpr;
this.andWhereExpr = andWhereExpr;
this.orderBySql = orderBySql;
this.name = meta.getName();
this.whereClause = meta.getWhere();
this.havingClause = meta.getHaving();
this.query = meta.getQuery();
this.columnMapping = meta.getColumnMapping();
this.sqlTree = initialise(desc);
this.columnMap = createColumnMap(this.selectColumns);
}
private Map<String,DRawSqlColumnInfo> createColumnMap(DRawSqlColumnInfo[] selectColumns) {
HashMap<String,DRawSqlColumnInfo> m = new HashMap<String,DRawSqlColumnInfo>();
for (int i = 0; i < selectColumns.length; i++) {
m.put(selectColumns[i].getPropertyName(), selectColumns[i]);
}
return m;
}
/**
* Find foreign keys for assoc one types and build SqlTree.
*/
private SqlTree initialise(BeanDescriptor<?> owner){
try {
return buildSqlTree(owner);
} catch (Exception e){
String m = "Bug? initialising query "+name+" on "+owner;
throw new RuntimeException(m, e);
}
}
/**
* Return the RawSqlColumnInfo given it's logical property name.
*/
public DRawSqlColumnInfo getRawSqlColumnInfo(String propertyName){
return columnMap.get(propertyName);
}
public String getTableAlias() {
return tableAlias;
}
/**
* Build the SqlTree for this query.
* <p>
* Most commonly this is just a simple list of properties - aka flat, but it
* could be a real object graph tree for more complex scenarios.
* </p>
*/
private SqlTree buildSqlTree(BeanDescriptor<?> desc){
SqlTree sqlTree = new SqlTree();
sqlTree.setSummary(desc.getName());
LinkedHashSet<String> includedProps = new LinkedHashSet<String>();
SqlTreeProperties selectProps = new SqlTreeProperties();
for (int i = 0; i < selectColumns.length; i++) {
DRawSqlColumnInfo columnInfo = selectColumns[i];
String propName = columnInfo.getPropertyName();
BeanProperty beanProperty = desc.getBeanProperty(propName);
if (beanProperty != null) {
if (beanProperty.isId()){
if (i > 0){
String m = "With "+desc+" query:"+name+" the ID is not the first column in the select. It must be...";
throw new PersistenceException(m);
} else {
withId = true;
}
} else {
includedProps.add(beanProperty.getName());
selectProps.add(beanProperty);
}
} else {
String m = "Mapping for " + desc.getFullName();
m += " query["+name+"] column[" + columnInfo + "] index[" + i;
m += "] not matched to bean property?";
logger.log(Level.SEVERE, m);
}
}
selectProps.setIncludedProperties(includedProps);
SqlTreeNode sqlRoot = new SqlTreeNodeRoot(desc, selectProps, null, withId);
sqlTree.setRootNode(sqlRoot);
return sqlTree;
}
/**
* Build the full SQL Select statement for the request.
*/
public String buildSql(String orderBy, CQueryPredicates predicates, OrmQueryRequest<?> request) {
StringBuilder sb = new StringBuilder();
sb.append(preWhereExprSql);
sb.append(" ");
String dynamicWhere = null;
if (request.getQuery().getId() != null) {
// need to convert this as well. This avoids the
// assumption that id has its proper dbColumn assigned
// which may change if using multiple raw sql statements
// against the same bean.
BeanDescriptor<?> descriptor = request.getBeanDescriptor();
//FIXME: I think this is broken... needs to be logical
// and then parsed for RawSqlSelect...
dynamicWhere = descriptor.getIdBinderIdSql();
}
String dbWhere = predicates.getDbWhere();
if (dbWhere != null && dbWhere.length() > 0) {
if (dynamicWhere == null) {
dynamicWhere = dbWhere;
} else {
dynamicWhere += " and " + dbWhere;
}
}
if (dynamicWhere != null) {
if (andWhereExpr) {
sb.append(" and ");
} else {
sb.append(" where ");
}
sb.append(dynamicWhere);
sb.append(" ");
}
if (preHavingExprSql != null) {
sb.append(preHavingExprSql);
sb.append(" ");
}
String dbHaving = predicates.getDbHaving();
if (dbHaving != null && dbHaving.length() > 0) {
if (andHavingExpr) {
sb.append(" and ");
} else {
sb.append(" having ");
}
sb.append(dbHaving);
sb.append(" ");
}
if (orderBy != null) {
sb.append(" order by ").append(orderBy);
}
return sb.toString();
}
public String getOrderBy(CQueryPredicates predicates) {
String orderBy = predicates.getDbOrderBy();
if (orderBy != null) {
return orderBy;
} else {
return orderBySql;
}
}
public String getName() {
return name;
}
public SqlTree getSqlTree() {
return sqlTree;
}
public boolean isWithId() {
return withId;
}
public String getQuery() {
return query;
}
public String getColumnMapping() {
return columnMapping;
}
public String getWhereClause() {
return whereClause;
}
public String getHavingClause() {
return havingClause;
}
public String toString() {
return Arrays.toString(selectColumns);
}
public BeanDescriptor<?> getBeanDescriptor() {
return desc;
}
public DeployParser createDeployPropertyParser() {
return new DeployPropertyParserRawSql(this);
}
}
@@ -0,0 +1,355 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.List;
import com.avaje.ebean.config.NamingConvention;
import com.avaje.ebeaninternal.server.querydefn.SimpleTextParser;
/**
* Parses sql-select queries to try and determine the location where WHERE and HAVING
* clauses can be added dynamically to the sql.
*/
public class DRawSqlSelectBuilder {
public static final String $_AND_HAVING = "${andHaving}";
public static final String $_HAVING = "${having}";
public static final String $_AND_WHERE = "${andWhere}";
public static final String $_WHERE = "${where}";
private static final String ORDER_BY = "order by";
private final BeanDescriptor<?> desc;
private final NamingConvention namingConvention;
private final DRawSqlMeta meta;
private final boolean debug;
private String sql;
private final SimpleTextParser textParser;
private List<DRawSqlColumnInfo> selectColumns;
private int placeHolderWhere;
private int placeHolderAndWhere;
private int placeHolderHaving;
private int placeHolderAndHaving;
private boolean hasPlaceHolders;
private int selectPos = -1;
private int fromPos = -1;
private int wherePos = -1;
private int groupByPos = -1;
private int havingPos = -1;
private int orderByPos = -1;
private boolean whereExprAnd;
private int whereExprPos = -1;
private boolean havingExprAnd;
private int havingExprPos = -1;
private String tableAlias;
public DRawSqlSelectBuilder(NamingConvention namingConvention, BeanDescriptor<?> desc, DRawSqlMeta sqlSelectMeta) {
this.namingConvention = namingConvention;
this.desc = desc;
this.tableAlias = sqlSelectMeta.getTableAlias();
this.meta = sqlSelectMeta;
this.debug = sqlSelectMeta.isDebug();
this.sql = sqlSelectMeta.getQuery().trim();
this.hasPlaceHolders = findAndRemovePlaceHolders();
this.textParser = new SimpleTextParser(this.sql);
}
protected NamingConvention getNamingConvention() {
return namingConvention;
}
protected BeanDescriptor<?> getBeanDescriptor() {
return desc;
}
protected boolean isDebug() {
return debug;
}
protected void debug(String msg) {
if (debug) {
System.out.println("debug> " + msg);
}
}
public DeployNamedQuery parse() {
if (debug) {
debug("");
debug("Parsing sql-select in " + getErrName());
}
if (hasPlaceHolders()) {
} else {
// parse the sql for the keywords...
// select, from, where, having, group by, order by
parseSqlFindKeywords(true);
}
selectColumns = findSelectColumns(meta.getColumnMapping());
whereExprPos = findWhereExprPosition();
havingExprPos = findHavingExprPosition();
String preWhereExprSql = removeWhitespace(findPreWhereExprSql());
String preHavingExprSql = removeWhitespace(findPreHavingExprSql());
preWhereExprSql = trimSelectKeyword(preWhereExprSql);
String orderBySql = findOrderBySql();
DRawSqlSelect rawSqlSelect = new DRawSqlSelect(desc, selectColumns, tableAlias, preWhereExprSql,
whereExprAnd, preHavingExprSql, havingExprAnd, orderBySql, meta);
return new DeployNamedQuery(rawSqlSelect);
}
/**
* Find and remove the known place holders such as ${where}.
*/
private boolean findAndRemovePlaceHolders() {
placeHolderWhere = removePlaceHolder($_WHERE);
placeHolderAndWhere = removePlaceHolder($_AND_WHERE);
placeHolderHaving = removePlaceHolder($_HAVING);
placeHolderAndHaving = removePlaceHolder($_AND_HAVING);
return hasPlaceHolders();
}
private int removePlaceHolder(String placeHolder) {
int pos = sql.indexOf(placeHolder);
if (pos > -1) {
int after = pos + placeHolder.length() + 1;
if (after > sql.length()) {
sql = sql.substring(0, pos);
} else {
sql = sql.substring(0, pos) + sql.substring(after);
}
}
return pos;
}
private boolean hasPlaceHolders() {
if (placeHolderWhere > -1) {
return true;
}
if (placeHolderAndWhere > -1) {
return true;
}
if (placeHolderHaving > -1) {
return true;
}
if (placeHolderAndHaving > -1) {
return true;
}
return false;
}
/**
* Trim off the select keyword (to support row_number() limit function).
*/
private String trimSelectKeyword(String preWhereExprSql) {
if (preWhereExprSql.length() < 7){
throw new RuntimeException("Expecting at least 7 chars in ["+preWhereExprSql+"]");
}
String select = preWhereExprSql.substring(0, 7);
if (!select.equalsIgnoreCase("select ")){
throw new RuntimeException("Expecting ["+preWhereExprSql+"] to start with \"select\"");
}
return preWhereExprSql.substring(7);
}
private String findOrderBySql() {
if (orderByPos > -1) {
int pos = orderByPos + ORDER_BY.length();
return sql.substring(pos);
}
return null;
}
private String findPreHavingExprSql() {
if (havingExprPos > whereExprPos) {
// an order by clause follows...
return sql.substring(whereExprPos, havingExprPos - 1);
}
if (whereExprPos > -1) {
// the rest of the sql...
return sql.substring(whereExprPos);
}
return null;
}
private String findPreWhereExprSql() {
if (whereExprPos > -1) {
return sql.substring(0, whereExprPos - 1);
} else {
return sql;
}
}
protected String getErrName() {
return "entity[" + desc.getFullName() + "] query[" + meta.getName() + "]";
}
/**
* Find the columns in the select clause including the table alias' and
* column alias.
*/
private List<DRawSqlColumnInfo> findSelectColumns(String selectClause) {
if (selectClause == null || selectClause.trim().length() == 0) {
if (hasPlaceHolders) {
if (debug) {
debug("... No explicit ColumnMapping, so parse the sql looking for SELECT and FROM keywords.");
}
parseSqlFindKeywords(false);
}
if (selectPos == -1 || fromPos == -1) {
String msg = "Error in [" + getErrName() + "] parsing sql looking ";
msg += "for SELECT and FROM keywords.";
msg += " select:" + selectPos + " from:" + fromPos;
msg += ". You could use an explicit columnMapping to bypass this error.";
throw new RuntimeException(msg);
}
selectPos += "select".length();
selectClause = sql.substring(selectPos, fromPos);
}
selectClause = selectClause.trim();
if (debug) {
debug("ColumnMapping ... [" + selectClause + "]");
}
return new DRawSqlSelectColumnsParser(this,selectClause).parse();
}
private void parseSqlFindKeywords(boolean allKeywords) {
debug("Parsing query looking for SELECT...");
selectPos = textParser.findWordLower("select");
if (selectPos == -1) {
String msg = "Error in "+getErrName()+" parsing sql, can not find SELECT keyword in:";
throw new RuntimeException(msg + sql);
}
debug("Parsing query looking for FROM... SELECT found at " + selectPos);
fromPos = textParser.findWordLower("from");
if (fromPos == -1) {
String msg = "Error in "+getErrName()+" parsing sql, can not find FROM keyword in:";
throw new RuntimeException(msg + sql);
}
if (!allKeywords) {
return;
}
debug("Parsing query looking for WHERE... FROM found at " + fromPos);
wherePos = textParser.findWordLower("where");
if (wherePos == -1) {
debug("Parsing query looking for GROUP... no WHERE found");
groupByPos = textParser.findWordLower("group", fromPos + 5);
} else {
debug("Parsing query looking for GROUP... WHERE found at " + wherePos);
groupByPos = textParser.findWordLower("group");
}
if (groupByPos > -1) {
debug("Parsing query looking for HAVING... GROUP found at " + groupByPos);
havingPos = textParser.findWordLower("having");
}
int startOrderBy = havingPos;
if (startOrderBy == -1) {
startOrderBy = groupByPos;
}
if (startOrderBy == -1) {
startOrderBy = wherePos;
}
if (startOrderBy == -1) {
startOrderBy = fromPos;
}
debug("Parsing query looking for ORDER... starting at " + startOrderBy);
orderByPos = textParser.findWordLower("order", startOrderBy);
}
private int findWhereExprPosition() {
if (hasPlaceHolders) {
if (placeHolderWhere > -1) {
return placeHolderWhere;
} else {
whereExprAnd = true;
return placeHolderAndWhere;
}
}
whereExprAnd = wherePos > 0;
if (groupByPos > 0) {
return groupByPos;
}
if (havingPos > 0) {
return havingPos;
}
if (orderByPos > 0) {
return orderByPos;
}
return -1;
}
private int findHavingExprPosition() {
if (hasPlaceHolders) {
if (placeHolderHaving > -1) {
return placeHolderHaving;
} else {
havingExprAnd = true;
return placeHolderAndHaving;
}
}
havingExprAnd = havingPos > 0;
if (orderByPos > 0) {
return orderByPos;
}
return -1;
}
private String removeWhitespace(String sql) {
if (sql == null) {
return "";
}
boolean removeWhitespace = false;
int length = sql.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
char c = sql.charAt(i);
if (removeWhitespace) {
if (!Character.isWhitespace(c)) {
sb.append(c);
removeWhitespace = false;
}
} else {
if (c == '\r' || c == '\n') {
sb.append('\n');
removeWhitespace = true;
} else {
sb.append(c);
}
}
}
return sb.toString();
}
}
@@ -0,0 +1,238 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import com.avaje.ebean.config.NamingConvention;
/**
* Parses columnMapping (select clause) mapping columns to bean properties.
*/
public final class DRawSqlSelectColumnsParser {
private static Logger logger = Logger.getLogger(DRawSqlSelectColumnsParser.class.getName());
/**
* Description of how the match was made.
*/
private String matchDescription;
/**
* The actual column string used in search for a matching property.
* <p>
* This has table alias' and quoted identifiers removed.
* </p>
*/
private String searchColumn;
private int columnIndex;
private int pos;
private final int end;
private final String sqlSelect;
private final List<DRawSqlColumnInfo> columns = new ArrayList<DRawSqlColumnInfo>();
private final BeanDescriptor<?> desc;
private final NamingConvention namingConvention;
private final DRawSqlSelectBuilder parent;
private final boolean debug;
public DRawSqlSelectColumnsParser(DRawSqlSelectBuilder parent, String sqlSelect) {
this.parent = parent;
this.debug = parent.isDebug();
this.namingConvention = parent.getNamingConvention();
this.desc = parent.getBeanDescriptor();
this.sqlSelect = sqlSelect;
this.end = sqlSelect.length();
}
public List<DRawSqlColumnInfo> parse() {
while (pos <= end) {
nextColumnInfo();
}
return columns;
}
private void nextColumnInfo() {
int start = pos;
nextComma();
String colInfo = sqlSelect.substring(start, pos);
pos++;
colInfo = colInfo.trim();
int secLastSpace = -1;
int lastSpace = colInfo.lastIndexOf(' ');
if (lastSpace > -1) {
secLastSpace = colInfo.lastIndexOf(' ', lastSpace - 1);
}
String colName = null;
String colLabel = null;
if (lastSpace == -1) {
// no column alias
colName = colInfo;
colLabel = colName;
} else if (secLastSpace == -1) {
// no 'as' keyword
colName = colInfo.substring(0, lastSpace);
colLabel = colInfo.substring(lastSpace + 1);
if (colName.equals("")) {
colName = colLabel;
}
} else {
// check for as keyword
String expectedAs = colInfo.substring(secLastSpace + 1, lastSpace);
if (expectedAs.toLowerCase().equals("as")) {
colName = colInfo.substring(0, secLastSpace);
colLabel = colInfo.substring(lastSpace + 1);
} else {
String msg = "Error in " + parent.getErrName() + ". ";
msg += "Expected \"AS\" keyword but got [" + expectedAs + "] in select clause ["
+ colInfo + "]";
throw new PersistenceException(msg);
}
}
BeanProperty prop = findProperty(colLabel);
if (prop == null) {
if (debug) {
String msg = "ColumnMapping ... idx[" + columnIndex
+ "] ERROR, no property found to match... column[" + colName + "] label[" + colLabel
+ "] search[" + searchColumn + "]";
parent.debug(msg);
}
String msg = "Error in " + parent.getErrName() + ". ";
msg += "No matching bean property for column[" + colName + "] columnLabel[" + colLabel
+ "] idx[" + columnIndex + "] using search[" + searchColumn + "] found?";
logger.log(Level.SEVERE, msg);
} else {
String msg = null;
if (debug || logger.isLoggable(Level.FINE)) {
msg = "ColumnMapping ... idx[" + columnIndex + "] match column[" + colName
+ "] label[" + colLabel + "] to property[" + prop + "]"
+ matchDescription;
}
if (debug) {
parent.debug(msg);
}
if (logger.isLoggable(Level.FINE)) {
logger.fine(msg);
}
DRawSqlColumnInfo info = new DRawSqlColumnInfo(colName, colLabel, prop.getName(), prop.isScalar());
columns.add(info);
columnIndex++;
}
}
private String removeQuotedIdentifierChars(String columnLabel) {
char c = columnLabel.charAt(0);
if (Character.isJavaIdentifierStart(c)) {
return columnLabel;
}
// trim off first and last character
String result = columnLabel.substring(1, columnLabel.length() - 1);
String msg = "sql-select trimming quoted identifier from["
+ columnLabel + "] to[" + result+ "]";
logger.fine(msg);
return result;
}
/**
* Find the property to match against the given resultSet column.
*/
private BeanProperty findProperty(String column) {
searchColumn = column;
int dotPos = searchColumn.indexOf(".");
if (dotPos > -1) {
searchColumn = searchColumn.substring(dotPos + 1);
}
searchColumn = removeQuotedIdentifierChars(searchColumn);
BeanProperty matchingProp = desc.getBeanProperty(searchColumn);
if (matchingProp != null) {
matchDescription = "";
return matchingProp;
}
// convert columnName using the namingConvention
String propertyName = namingConvention.getPropertyFromColumn(desc.getBeanType(), searchColumn);
matchingProp = desc.getBeanProperty(propertyName);
if (matchingProp != null) {
matchDescription = " ... using naming convention";
return matchingProp;
}
matchDescription = " ... by linear search";
// search all properties matching against the property db column
BeanProperty[] propertiesBase = desc.propertiesBaseScalar();
for (int i = 0; i < propertiesBase.length; i++) {
BeanProperty prop = propertiesBase[i];
if (isMatch(prop, searchColumn)) {
return prop;
}
}
BeanProperty[] propertiesId = desc.propertiesId();
for (int i = 0; i < propertiesId.length; i++) {
BeanProperty prop = propertiesId[i];
if (isMatch(prop, searchColumn)) {
return prop;
}
}
BeanPropertyAssocOne<?>[] propertiesAssocOne = desc.propertiesOne();
for (int i = 0; i < propertiesAssocOne.length; i++) {
BeanProperty prop = propertiesAssocOne[i];
if (isMatch(prop, searchColumn)) {
return prop;
}
}
return null;
}
private boolean isMatch(BeanProperty prop, String columnLabel) {
if (columnLabel.equalsIgnoreCase(prop.getDbColumn())) {
return true;
}
if (columnLabel.equalsIgnoreCase(prop.getName())) {
return true;
}
return false;
}
private int nextComma() {
boolean inQuote = false;
while (pos < end) {
char c = sqlSelect.charAt(pos);
if (c == '\'') {
inQuote = !inQuote;
} else if (!inQuote && c == ',') {
return pos;
}
pos++;
}
return pos;
}
}
@@ -0,0 +1,96 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.Map;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebean.bean.PersistenceContext;
import com.avaje.ebeaninternal.api.SpiQuery;
import com.avaje.ebeaninternal.server.type.DataReader;
/**
* Context provided when a BeanProperty reads from a ResultSet.
*/
public interface DbReadContext {
/**
* Return the state of the object graph.
*/
public Boolean isReadOnly();
/**
* Propagate the state to the bean.
*/
public void propagateState(Object e);
/**
* Return the DataReader.
*/
public DataReader getDataReader();
/**
* Return true if vanilla objects should be returned.
*/
public boolean isVanillaMode();
/**
* Return true if the query is using supplied SQL rather than generated SQL.
*/
public boolean isRawSql();
// /**
// * Return the reference options for a given bean property.
// */
// public ReferenceOptions getReferenceOptionsFor(BeanPropertyAssocOne<?> beanProperty);
/**
* Set the JoinNode - used by proxy/reference beans for profiling.
*/
public void setCurrentPrefix(String currentPrefix, Map<String,String> pathMap);
/**
* Return true if we are profiling this query.
*/
public boolean isAutoFetchProfiling();
/**
* Add autoFetch profiling for a loaded entity bean.
*/
public void profileBean(EntityBeanIntercept ebi, String prefix);
/**
* Return the persistence context.
*/
public PersistenceContext getPersistenceContext();
/**
* Register a reference for lazy loading.
*/
public void register(String path, EntityBeanIntercept ebi);
/**
* Register a collection for lazy loading.
*/
public void register(String path, BeanCollection<?> bc);
/**
* Return the property that is associated with the many. There can only be
* one. This can be null.
*/
public BeanPropertyAssocMany<?> getManyProperty();
/**
* Set back the bean that has just been loaded with its id.
*/
public void setLoadedBean(Object loadedBean, Object id);
/**
* Set back the 'detail' bean that has just been loaded.
*/
public void setLoadedManyBean(Object loadedBean);
/**
* Return the query mode.
*/
public SpiQuery.Mode getQueryMode();
}
@@ -0,0 +1,116 @@
package com.avaje.ebeaninternal.server.deploy;
/**
* Used to provide context during sql construction.
*/
public interface DbSqlContext {
/**
* Add a join to the sql query.
*/
public void addJoin(String type, String table, TableJoinColumn[] cols, String a1, String a2);
public void pushSecondaryTableAlias(String alias);
/**
* Push the current table alias onto the stack.
*/
public void pushTableAlias(String tableAlias);
/**
* Pop the current table alias from the stack.
*/
public void popTableAlias();
/**
* Add an encrypted property which will require additional binding.
*/
public void addEncryptedProp(BeanProperty prop);
/**
* Return a list of encrypted properties which require additional binding.
*/
public BeanProperty[] getEncryptedProps();
/**
* Append a char directly to the SQL buffer.
*/
public DbSqlContext append(char s);
/**
* Append a string directly to the SQL buffer.
*/
public DbSqlContext append(String s);
/**
* Peek the current table alias.
*/
public String peekTableAlias();
/**
* Add a raw column to the sql.
*/
public void appendRawColumn(String rawcolumnWithTableAlias);
/**
* Append a column with an explicit table alias.
*/
public void appendColumn(String tableAlias, String column);
/**
* Append a column with the current table alias.
*/
public void appendColumn(String column);
/**
* Append a Sql Formula select. This converts the "${ta}" keyword to the
* current table alias.
*/
public void appendFormulaSelect(String sqlFormulaSelect);
/**
* Append a Sql Formula join. This converts the "${ta}" keyword to the
* current table alias.
*/
public void appendFormulaJoin(String sqlFormulaJoin, boolean forceOuterJoin);
/**
* Return the current content length.
*/
public int length();
/**
* Return the current context of the sql context.
*/
public String getContent();
/**
* Return the current join node.
*/
public String peekJoin();
/**
* Push a join node onto the stack.
*/
public void pushJoin(String prefix);
/**
* Pop a join node off the stack.
*/
public void popJoin();
/**
* Return a table alias without many where clause joins.
* Typically this is for the select clause (fetch joins).
*/
public String getTableAlias(String prefix);
/**
* Return a table alias that takes into account many where joins.
*/
public String getTableAliasManyWhere(String prefix);
public String getRelativePrefix(String propName);
}
@@ -0,0 +1,80 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.util.HashMap;
import java.util.List;
import javax.persistence.PersistenceException;
import com.avaje.ebean.event.BeanFinder;
/**
* Default implementation for BeanFinderFactory.
*/
public class DefaultBeanFinderManager implements BeanFinderManager {
HashMap<Class<?>, BeanFinder<?>> registerFor = new HashMap<Class<?>, BeanFinder<?>>();
public int createBeanFinders(List<Class<?>> finderClassList) {
for (Class<?> cls : finderClassList) {
Class<?> entityType = getEntityClass(cls);
try {
BeanFinder<?> beanFinder = (BeanFinder<?>) cls.newInstance();
registerFor.put(entityType, beanFinder);
} catch (Exception ex) {
throw new PersistenceException(ex);
}
}
return registerFor.size();
}
public int getRegisterCount() {
return registerFor.size();
}
/**
* Return the BeanFinder for a given entity type.
*/
@SuppressWarnings("unchecked")
public <T> BeanFinder<T> getBeanFinder(Class<T> entityType) {
return (BeanFinder<T>)registerFor.get(entityType);
}
/**
* Find the entity class given the controller class.
* <p>
* This uses reflection to find the generics parameter type.
* </p>
*/
private Class<?> getEntityClass(Class<?> controller){
Class<?> cls = ParamTypeUtil.findParamType(controller, BeanFinder.class);
if (cls == null){
String msg = "Could not determine the entity class (generics parameter type) from "+controller+" using reflection.";
throw new PersistenceException(msg);
}
return cls;
}
}
@@ -0,0 +1,80 @@
package com.avaje.ebeaninternal.server.deploy;
import javax.persistence.NamedQuery;
import javax.persistence.QueryHint;
import com.avaje.ebean.RawSql;
public class DeployNamedQuery {
private final String name;
private final String query;
private final QueryHint[] hints;
private final DRawSqlSelect sqlSelect;
private final RawSql rawSql;
public DeployNamedQuery(NamedQuery namedQuery) {
this.name = namedQuery.name();
this.query = namedQuery.query();
this.hints = namedQuery.hints();
this.sqlSelect = null;
this.rawSql = null;
}
public DeployNamedQuery(String name, String query, QueryHint[] hints) {
this.name = name;
this.query = query;
this.hints = hints;
this.sqlSelect = null;
this.rawSql = null;
}
public DeployNamedQuery(String name, RawSql rawSql) {
this.name = name;
this.query = null;
this.hints = null;
this.sqlSelect = null;
this.rawSql = rawSql;
}
public DeployNamedQuery(DRawSqlSelect sqlSelect) {
this.name = sqlSelect.getName();
this.query = null;
this.hints = null;
this.sqlSelect = sqlSelect;
this.rawSql = null;
}
public boolean isRawSql() {
return rawSql != null;
}
public boolean isSqlSelect() {
return sqlSelect != null;
}
public String getName() {
return name;
}
public String getQuery() {
return query;
}
public QueryHint[] getHints() {
return hints;
}
public RawSql getRawSql() {
return rawSql;
}
public DRawSqlSelect getSqlSelect() {
return sqlSelect;
}
}
@@ -0,0 +1,40 @@
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebean.annotation.NamedUpdate;
/**
* Deployment information for a named update.
*/
public class DeployNamedUpdate {
private final String name;
private final String updateStatement;
private final boolean notifyCache;
private String sqlUpdateStatement;
public DeployNamedUpdate(NamedUpdate update) {
this.name = update.name();
this.updateStatement = update.update();
this.notifyCache = update.notifyCache();
}
public void initialise(DeployUpdateParser parser) {
sqlUpdateStatement = parser.parse(updateStatement);
}
public String getName() {
return name;
}
public String getSqlUpdateStatement() {
return sqlUpdateStatement;
}
public boolean isNotifyCache() {
return notifyCache;
}
}
@@ -0,0 +1,191 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebeaninternal.server.lib.resource.ResourceContent;
import com.avaje.ebeaninternal.server.lib.resource.ResourceSource;
import com.avaje.ebeaninternal.server.lib.util.Dnode;
import com.avaje.ebeaninternal.server.lib.util.DnodeReader;
/**
* Controls the creation and caching of BeanManager's, BeanDescriptors,
* BeanTable etc for both beans and tables(MapBeans).
* <p>
* Also supports some other deployment features such as type conversion.
* </p>
*/
public class DeployOrmXml {
private static final Logger logger = Logger.getLogger(DeployOrmXml.class.getName());
private final HashMap<String, DNativeQuery> nativeQueryCache;
private final ArrayList<Dnode> ormXmlList;
private final ResourceSource resSource;
public DeployOrmXml(ResourceSource resSource) {
this.resSource = resSource;
this.nativeQueryCache = new HashMap<String, DNativeQuery>();
this.ormXmlList = findAllOrmXml();
initialiseNativeQueries();
}
/**
* Register all the native queries in ALL orm xml deployment.
*/
private void initialiseNativeQueries() {
for (Dnode ormXml : ormXmlList) {
initialiseNativeQueries(ormXml);
}
}
/**
* Register the native queries in this particular orm xml deployment.
*/
private void initialiseNativeQueries(Dnode ormXml) {
Dnode entityMappings = ormXml.find("entity-mappings");
if (entityMappings != null) {
List<Dnode> nq = entityMappings.findAll("named-native-query", 1);
for (int i = 0; i < nq.size(); i++) {
Dnode nqNode = nq.get(i);
Dnode nqQueryNode = nqNode.find("query");
if (nqQueryNode != null) {
String queryContent = nqQueryNode.getNodeContent();
String queryName = (String) nqNode.getAttribute("name");
if (queryName != null && queryContent != null) {
DNativeQuery query = new DNativeQuery(queryContent);
nativeQueryCache.put(queryName, query);
}
}
}
}
}
/**
* Return a native named query.
* <p>
* These are loaded from the orm.xml deployment file.
* </p>
*/
public DNativeQuery getNativeQuery(String name) {
return nativeQueryCache.get(name);
}
private ArrayList<Dnode> findAllOrmXml() {
ArrayList<Dnode> ormXmlList = new ArrayList<Dnode>();
String defaultFile = "orm.xml";
readOrmXml(defaultFile, ormXmlList);
if (!ormXmlList.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (Dnode ox : ormXmlList) {
sb.append(", ").append(ox.getAttribute("ebean.filename"));
}
String loadedFiles = sb.toString().substring(2);
logger.info("Deployment xml [" + loadedFiles + "] loaded.");
}
return ormXmlList;
}
private boolean readOrmXml(String ormXmlName, ArrayList<Dnode> ormXmlList) {
try {
Dnode ormXml = null;
ResourceContent content = resSource.getContent(ormXmlName);
if (content != null) {
// servlet resource or file system...
ormXml = readOrmXml(content.getInputStream());
} else {
// try the classpath...
ormXml = readOrmXmlFromClasspath(ormXmlName);
}
if (ormXml != null) {
ormXml.setAttribute("ebean.filename", ormXmlName);
ormXmlList.add(ormXml);
return true;
} else {
return false;
}
} catch (IOException e) {
logger.log(Level.SEVERE, "error reading orm xml deployment " + ormXmlName, e);
return false;
}
}
private Dnode readOrmXmlFromClasspath(String ormXmlName) throws IOException {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(ormXmlName);
if (is == null) {
return null;
} else {
return readOrmXml(is);
}
}
private Dnode readOrmXml(InputStream in) throws IOException {
DnodeReader reader = new DnodeReader();
Dnode ormXml = reader.parseXml(in);
in.close();
return ormXml;
}
/**
* Find the deployment xml for a given entity. This will return null if no
* matching deployment xml is found for this entity.
* <p>
* This searches all the ormXml files and returns the first match.
* </p>
*/
public Dnode findEntityDeploymentXml(String className) {
for (Dnode ormXml : ormXmlList) {
Dnode entityMappings = ormXml.find("entity-mappings");
List<Dnode> entities = entityMappings.findAll("entity", "class", className, 1);
if (entities.size() == 1) {
return entities.get(0);
}
}
return null;
}
}
@@ -0,0 +1,183 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.Set;
/**
* Converts logical property names to database columns.
*/
public abstract class DeployParser {
/**
* used to identify sql literal.
*/
protected static final char SINGLE_QUOTE = '\'';
/**
* used to identify query named parameters.
*/
protected static final char COLON = ':';
/**
* Used to determine when a column name terminates.
*/
protected static final char UNDERSCORE = '_';
/**
* Used to determine when a column name terminates.
*/
protected static final char PERIOD = '.';
protected boolean encrypted;
protected String source;
protected StringBuilder sb;
protected int sourceLength;
protected int pos;
protected String word;
protected char wordTerminator;
protected abstract String convertWord();
public abstract String getDeployWord(String expression);
/**
* Return the join includes.
*/
public abstract Set<String> getIncludes();
public void setEncrypted(boolean encrytped) {
this.encrypted = encrytped;
}
public String parse(String source) {
if (source == null) {
return source;
}
pos = -1;
this.source = source;
this.sourceLength = source.length();
this.sb = new StringBuilder(source.length() + 20);
while (nextWord()) {
String deployWord = convertWord();
sb.append(deployWord);
if (pos < sourceLength) {
sb.append(wordTerminator);
}
}
return sb.toString();
}
private boolean nextWord() {
if (!findWordStart()) {
return false;
}
StringBuilder wordBuffer = new StringBuilder();
wordBuffer.append(source.charAt(pos));
while (++pos < sourceLength) {
char ch = source.charAt(pos);
if (isWordPart(ch)) {
wordBuffer.append(ch);
} else {
wordTerminator = ch;
break;
}
}
word = wordBuffer.toString();
return true;
}
private boolean findWordStart() {
while (++pos < sourceLength) {
char ch = source.charAt(pos);
if (ch == SINGLE_QUOTE) {
// read a literal value and just
// append to string builder
sb.append(ch);
readLiteral();
} else if (ch == COLON) {
// read a named parameter
// just append to string builder
sb.append(ch);
readNamedParameter();
} else if (isWordStart(ch)) {
// its the start of a word that could
// be translated
return true;
} else {
sb.append(ch);
}
}
return false;
}
/**
* Read the rest of a literal value. These do not get translated so are just
* read and appended to the string builder.
*/
private void readLiteral() {
while (++pos < sourceLength) {
char ch = source.charAt(pos);
sb.append(ch);
if (ch == SINGLE_QUOTE) {
break;
}
}
}
/**
* Read a named parameter. These are not translated. They will be replaced
* by positioned parameters later.
*/
private void readNamedParameter() {
while (++pos < sourceLength) {
char ch = source.charAt(pos);
sb.append(ch);
if (Character.isWhitespace(ch)) {
break;
} else if (ch == ',') {
break;
}
}
}
/**
* return true if the char is a letter, digit or underscore.
*/
private boolean isWordPart(char ch) {
if (Character.isLetterOrDigit(ch)) {
return true;
} else if (ch == UNDERSCORE) {
return true;
} else if (ch == PERIOD) {
return true;
} else {
return false;
}
}
private boolean isWordStart(char ch) {
if (Character.isLetter(ch)) {
return true;
} else {
return false;
}
}
}
@@ -0,0 +1,52 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.HashSet;
import java.util.Set;
import com.avaje.ebeaninternal.server.el.ElPropertyDeploy;
/**
* Converts logical property names to database columns with table alias.
* <p>
* In doing so it builds an 'includes' set which becomes the joins required to
* support the properties parsed.
* </p>
*/
public final class DeployPropertyParser extends DeployParser {
private final BeanDescriptor<?> beanDescriptor;
private final Set<String> includes = new HashSet<String>();
public DeployPropertyParser(BeanDescriptor<?> beanDescriptor) {
this.beanDescriptor = beanDescriptor;
}
public Set<String> getIncludes() {
return includes;
}
@Override
public String getDeployWord(String expression) {
ElPropertyDeploy elProp = beanDescriptor.getElPropertyDeploy(expression);
if (elProp == null){
return null;
} else {
addIncludes(elProp.getElPrefix());
return elProp.getElPlaceholder(encrypted);
}
}
@Override
public String convertWord() {
String r = getDeployWord(word);
return r == null ? word : r;
}
private void addIncludes(String prefix) {
if (prefix != null){
includes.add(prefix);
}
}
}
@@ -0,0 +1,40 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.Map;
import java.util.Set;
/**
* Converts logical property names to database columns using a Map.
*/
public final class DeployPropertyParserMap extends DeployParser {
private final Map<String,String> map;
public DeployPropertyParserMap(Map<String,String> map) {
this.map = map;
}
/**
* Returns null for raw sql queries.
*/
public Set<String> getIncludes() {
return null;
}
public String convertWord() {
String r = getDeployWord(word);
return r == null ? word : r;
}
@Override
public String getDeployWord(String expression) {
String deployExpr = map.get(expression);
if (deployExpr == null) {
return null;
} else {
return deployExpr;
}
}
}
@@ -0,0 +1,41 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.Set;
/**
* Converts logical property names to database columns for the raw sql.
* <p>
* This is used in building the where and having clauses for SqlSelect queries.
* </p>
*/
public final class DeployPropertyParserRawSql extends DeployParser {
private final DRawSqlSelect rawSqlSelect;
public DeployPropertyParserRawSql(DRawSqlSelect rawSqlSelect) {
this.rawSqlSelect = rawSqlSelect;
}
/**
* Returns null for raw sql queries.
*/
public Set<String> getIncludes() {
return null;
}
public String convertWord() {
String r = getDeployWord(word);
return r == null ? word : r;
}
@Override
public String getDeployWord(String expression) {
DRawSqlColumnInfo columnInfo = rawSqlSelect.getRawSqlColumnInfo(expression);
if (columnInfo == null) {
return null;
} else {
return columnInfo.getName();
}
}
}
@@ -0,0 +1,57 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebeaninternal.server.deploy.id.ImportedId;
/**
* Build a map of logical to physical names for use in Orm Updates.
*
*/
public class DeployUpdateMapFactory {
private static final Logger logger = Logger.getLogger(DeployUpdateMapFactory.class.getName());
/**
* Build a map of logical to physical names for use in Orm Updates for a given descriptor.
* <p>
* This includes the dbWrite scalar properties and imported foreign key properties.
* </p>
*/
public static Map<String,String> build(BeanDescriptor<?> descriptor) {
Map<String,String> deployMap = new HashMap<String,String>();
String shortName = descriptor.getName();
String beanName = shortName.toLowerCase();
deployMap.put(beanName, descriptor.getBaseTable());
BeanProperty[] baseScalar = descriptor.propertiesBaseScalar();
for (BeanProperty baseProp : baseScalar) {
// excluding formula, secondary table properties
if (baseProp.isDbInsertable() || baseProp.isDbUpdatable()){
deployMap.put(baseProp.getName().toLowerCase(), baseProp.getDbColumn());
}
}
BeanPropertyAssocOne<?>[] oneImported = descriptor.propertiesOneImported();
for (BeanPropertyAssocOne<?> assocOne : oneImported) {
ImportedId importedId = assocOne.getImportedId();
if (importedId == null){
String m = descriptor.getFullName()+" importedId is null for associated: "+assocOne.getFullBeanName();
logger.log(Level.SEVERE, m);
} else if (importedId.isScalar()){
deployMap.put(importedId.getLogicalName(), importedId.getDbColumn());
}
}
return deployMap;
}
}
@@ -0,0 +1,90 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.Set;
import com.avaje.ebeaninternal.server.el.ElPropertyDeploy;
/**
* For updates converts logical property names to database columns and bean type to base table.
*/
public final class DeployUpdateParser extends DeployParser {
private final BeanDescriptor<?> beanDescriptor;
public DeployUpdateParser(BeanDescriptor<?> beanDescriptor) {
this.beanDescriptor = beanDescriptor;
}
/**
* Return null as not used for updates.
*/
@Override
public Set<String> getIncludes() {
return null;
}
public String convertWord() {
String dbWord = getDeployWord(word);
if (dbWord != null) {
return dbWord;
}
// maybe tableAlias.propertyName
return convertSubword(0, word, null);
}
private String convertSubword(int start, String currentWord, StringBuilder localBuffer) {
int dotPos = currentWord.indexOf('.', start);
if (start == 0 && dotPos == -1){
return currentWord;
}
if (start == 0){
localBuffer = new StringBuilder();
}
if (dotPos == -1){
// no match...
localBuffer.append(currentWord.substring(start));
return localBuffer.toString();
}
// append up to the dot
localBuffer.append(currentWord.substring(start, dotPos+1));
if (dotPos == currentWord.length()-1){
// ends with a "." ???
return localBuffer.toString();
}
// get the remainder after the dot
start = dotPos+1;
String remainder = currentWord.substring(start, currentWord.length());
//String dbWord = deployMap.get(remainder.toLowerCase());
String dbWord = getDeployWord(remainder);
if (dbWord != null){
// we have found a match for the remainder
localBuffer.append(dbWord);
return localBuffer.toString();
} else {
//
return convertSubword(start, currentWord, localBuffer);
}
}
public String getDeployWord(String expression) {
if (expression.equalsIgnoreCase(beanDescriptor.getName())){
return beanDescriptor.getBaseTable();
}
ElPropertyDeploy elProp = beanDescriptor.getElPropertyDeploy(expression);
if (elProp != null){
return elProp.getDbColumn();
} else {
return null;
}
}
}
@@ -0,0 +1,64 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Determine the Many Type for a property.
* <p>
* Scala types require CollectionTypeConverter's to wrap and unwrap from the
* underlying java types used.
* </p>
*/
public class DetermineManyType {
private final boolean withScalaSupport;
private final ManyType scalaBufMany;
private final ManyType scalaSetMany;
private final ManyType scalaMapMany;
public DetermineManyType(boolean withScalaSupport) {
this.withScalaSupport = withScalaSupport;
if (withScalaSupport){
CollectionTypeConverter bufConverter = new ScalaBufferConverter();
CollectionTypeConverter setConverter = new ScalaSetConverter();
CollectionTypeConverter mapConverter = new ScalaMapConverter();
this.scalaBufMany = new ManyType(ManyType.Underlying.LIST, bufConverter);
this.scalaSetMany = new ManyType(ManyType.Underlying.SET, setConverter);
this.scalaMapMany = new ManyType(ManyType.Underlying.MAP, mapConverter);
} else {
this.scalaBufMany = null;
this.scalaSetMany = null;
this.scalaMapMany = null;
}
}
public ManyType getManyType(Class<?> type) {
if (type.equals(List.class)){
return ManyType.JAVA_LIST;
}
if (type.equals(Set.class)){
return ManyType.JAVA_SET;
}
if (type.equals(Map.class)){
return ManyType.JAVA_MAP;
}
if (withScalaSupport){
// only get in here when scala in classpath
if (type.equals(scala.collection.mutable.Buffer.class)){
return scalaBufMany;
}
if (type.equals(scala.collection.mutable.Set.class)){
return scalaSetMany;
}
if (type.equals(scala.collection.mutable.Map.class)){
return scalaMapMany;
}
}
return null;
}
}
@@ -0,0 +1,71 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebeaninternal.server.core.InternString;
/**
* The Exported foreign key and property.
* <p>
* Used to for Assoc Manys to create references etc.
* </p>
*/
public class ExportedProperty {
private final String foreignDbColumn;
private final BeanProperty property;
private final boolean embedded;
public ExportedProperty(boolean embedded, String foreignDbColumn, BeanProperty property) {
this.embedded = embedded;
this.foreignDbColumn = InternString.intern(foreignDbColumn);
this.property = property;
}
/**
* Return true if this is part of an embedded concatinated key.
*/
public boolean isEmbedded() {
return embedded;
}
/**
* Return the property value from the bean.
*/
public Object getValue(Object bean){
return property.getValue(bean);
}
/**
* Return the foreign database column matching this property.
* <p>
* We use this foreign database column in the query predicates
* in preference to a parentProperty.idProperty = value.
* Just using the foreign database column avoids triggering
* a join to the 'parent' table.
* </p>
*/
public String getForeignDbColumn() {
return foreignDbColumn;
}
}
@@ -0,0 +1,371 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.id.IdBinder;
import com.avaje.ebeaninternal.server.deploy.parse.DeployInheritInfo;
import com.avaje.ebeaninternal.server.query.SqlTreeProperties;
import com.avaje.ebeaninternal.server.subclass.SubClassUtil;
/**
* Represents a node in the Inheritance tree. Holds information regarding Super
* Subclass support.
*/
public class InheritInfo {
private final String discriminatorStringValue;
private final Object discriminatorValue;
private final String discriminatorColumn;
private final int discriminatorType;
private final int discriminatorLength;
private final String where;
private final Class<?> type;
private final ArrayList<InheritInfo> children = new ArrayList<InheritInfo>();
/**
* Map of discriminator values to InheritInfo.
*/
private final HashMap<String, InheritInfo> discMap;
/**
* Map of class types to InheritInfo (taking into account subclass proxy classes).
*/
private final HashMap<String, InheritInfo> typeMap;
private final InheritInfo parent;
private final InheritInfo root;
private BeanDescriptor<?> descriptor;
public InheritInfo(InheritInfo r, InheritInfo parent, DeployInheritInfo deploy) {
this.parent = parent;
this.type = deploy.getType();
this.discriminatorColumn = InternString.intern(deploy.getDiscriminatorColumn(parent));
this.discriminatorValue = deploy.getDiscriminatorObjectValue();
this.discriminatorStringValue = deploy.getDiscriminatorStringValue();
this.discriminatorType = deploy.getDiscriminatorType(parent);
this.discriminatorLength = deploy.getDiscriminatorLength(parent);
this.where = InternString.intern(deploy.getWhere());
if (r == null) {
// this is a root node
root = this;
discMap = new HashMap<String, InheritInfo>();
typeMap = new HashMap<String, InheritInfo>();
registerWithRoot(this);
} else {
this.root = r;
// register with the root node...
discMap = null;
typeMap = null;
root.registerWithRoot(this);
}
}
/**
* Visit all the children in the inheritance tree.
*/
public void visitChildren(InheritInfoVisitor visitor) {
for (int i = 0; i < children.size(); i++) {
InheritInfo child = children.get(i);
visitor.visit(child);
child.visitChildren(visitor);
}
}
/**
* return true if anything in the inheritance hierarchy has a relationship
* with a save cascade on it.
*/
public boolean isSaveRecurseSkippable() {
return root.isNodeSaveRecurseSkippable();
}
private boolean isNodeSaveRecurseSkippable() {
if (!descriptor.isSaveRecurseSkippable()){
return false;
}
for (int i = 0; i < children.size(); i++) {
InheritInfo child = children.get(i);
if (!child.isNodeSaveRecurseSkippable()){
return false;
}
}
return true;
}
/**
* return true if anything in the inheritance hierarchy has a relationship
* with a delete cascade on it.
*/
public boolean isDeleteRecurseSkippable() {
return root.isNodeDeleteRecurseSkippable();
}
private boolean isNodeDeleteRecurseSkippable() {
if (!descriptor.isDeleteRecurseSkippable()) {
return false;
}
for (int i = 0; i < children.size(); i++) {
InheritInfo child = children.get(i);
if (!child.isNodeDeleteRecurseSkippable()) {
return false;
}
}
return true;
}
/**
* Set the descriptor for this node.
*/
public void setDescriptor(BeanDescriptor<?> descriptor) {
this.descriptor = descriptor;
}
/**
* Return the associated BeanDescriptor for this node.
*/
public BeanDescriptor<?> getBeanDescriptor() {
return descriptor;
}
/**
* Get the bean property additionally looking in the sub types.
*/
public BeanProperty findSubTypeProperty(String propertyName) {
BeanProperty prop = null;
for (int i = 0, x=children.size(); i < x; i++) {
InheritInfo childInfo = children.get(i);
// recursively search this child bean descriptor
prop = childInfo.getBeanDescriptor().findBeanProperty(propertyName);
if (prop != null){
return prop;
}
}
return null;
}
/**
* Add the local properties for each sub class below this one.
*/
public void addChildrenProperties(SqlTreeProperties selectProps) {
for (int i = 0, x=children.size(); i < x; i++) {
InheritInfo childInfo = children.get(i);
selectProps.add(childInfo.descriptor.propertiesLocal());
childInfo.addChildrenProperties(selectProps);
}
}
/**
* Return the associated InheritInfo for this DB row read.
*/
public InheritInfo readType(DbReadContext ctx) throws SQLException {
String discValue = ctx.getDataReader().getString();
return readType(discValue);
}
/**
* Return the associated InheritInfo for this discriminator value.
*/
public InheritInfo readType(String discValue) {
if (discValue == null) {
return null;
}
InheritInfo typeInfo = root.getType(discValue);
if (typeInfo == null) {
String m = "Inheritance type for discriminator value [" + discValue + "] was not found?";
throw new PersistenceException(m);
}
return typeInfo;
}
/**
* Return the associated InheritInfo for this bean type.
*/
public InheritInfo readType(Class<?> beanType) {
InheritInfo typeInfo = root.getTypeByClass(beanType);
if (typeInfo == null) {
String m = "Inheritance type for bean type [" + beanType.getName() + "] was not found?";
throw new PersistenceException(m);
}
return typeInfo;
}
/**
* Create an EntityBean for this type.
*/
public Object createBean(boolean vanillaMode) {
return descriptor.createBean(vanillaMode);
}
/**
* Return the IdBinder for this type.
*/
public IdBinder getIdBinder() {
return descriptor.getIdBinder();
}
/**
* return the type.
*/
public Class<?> getType() {
return type;
}
/**
* Return the root node of the tree.
* <p>
* The root has a map of discriminator values to types.
* </p>
*/
public InheritInfo getRoot() {
return root;
}
/**
* Return the parent node.
*/
public InheritInfo getParent() {
return parent;
}
/**
* Return true if this is abstract node.
*/
public boolean isAbstract() {
return (discriminatorValue == null);
}
/**
* Return true if this is the root node.
*/
public boolean isRoot() {
return parent == null;
}
/**
* For a discriminator get the inheritance information for this tree.
*/
public InheritInfo getType(String discValue) {
return discMap.get(discValue);
}
/**
* Return the InheritInfo for the given bean type.
*/
private InheritInfo getTypeByClass(Class<?> beanType) {
String clsName = SubClassUtil.getSuperClassName(beanType.getName());
return typeMap.get(clsName);
}
private void registerWithRoot(InheritInfo info) {
if (info.getDiscriminatorStringValue() != null) {
String stringDiscValue = info.getDiscriminatorStringValue();
discMap.put(stringDiscValue, info);
}
String clsName = SubClassUtil.getSuperClassName(info.getType().getName());
typeMap.put(clsName, info);
}
/**
* Add a child node.
*/
public void addChild(InheritInfo childInfo) {
children.add(childInfo);
}
/**
* Return the derived where for the discriminator.
*/
public String getWhere() {
return where;
}
/**
* Return the column name of the discriminator.
*/
public String getDiscriminatorColumn() {
return discriminatorColumn;
}
/**
* Return the sql type of the discriminator value.
*/
public int getDiscriminatorType() {
return discriminatorType;
}
/**
* Return the length of the discriminator column.
*/
public int getDiscriminatorLength() {
return discriminatorLength;
}
/**
* Return the discriminator value for this node.
*/
public String getDiscriminatorStringValue() {
return discriminatorStringValue;
}
public Object getDiscriminatorValue() {
return discriminatorValue;
}
public String toString() {
return "InheritInfo[" + type.getName() + "] disc[" + discriminatorStringValue + "]";
}
}
@@ -0,0 +1,13 @@
package com.avaje.ebeaninternal.server.deploy;
/**
* Used to visit all the InheritInfo in a single inheritance hierarchy.
*/
public interface InheritInfoVisitor {
/**
* visit the InheritInfo for this node.
*/
public void visit(InheritInfo inheritInfo);
}
@@ -0,0 +1,143 @@
package com.avaje.ebeaninternal.server.deploy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.SqlUpdate;
import com.avaje.ebeaninternal.api.BindParams;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.expression.IdInExpression;
import com.avaje.ebeaninternal.util.DefaultExpressionRequest;
public class IntersectionRow {
private final String tableName;
private final LinkedHashMap<String,Object> values = new LinkedHashMap<String,Object>();
private ArrayList<Object> excludeIds;
private BeanDescriptor<?> excludeDescriptor;
public IntersectionRow(String tableName){
this.tableName = tableName;
}
/**
* Set Id's to exclude. This is for deleting non-attached detail Id's.
*/
public void setExcludeIds(ArrayList<Object> excludeIds, BeanDescriptor<?> excludeDescriptor){
this.excludeIds = excludeIds;
this.excludeDescriptor = excludeDescriptor;
}
public void put(String key, Object value){
values.put(key, value);
}
public SqlUpdate createInsert(EbeanServer server){
BindParams bindParams = new BindParams();
StringBuilder sb = new StringBuilder();
sb.append("insert into ").append(tableName).append(" (");
int count = 0;
Iterator<Entry<String, Object>> it = values.entrySet().iterator();
while (it.hasNext()) {
if (count++ > 0){
sb.append(", ");
}
Map.Entry<String, Object> entry = it.next();
sb.append(entry.getKey());
bindParams.setParameter(count, entry.getValue());
}
sb.append(") values (");
for (int i = 0; i < count; i++) {
if (i > 0){
sb.append(", ");
}
sb.append("?");
}
sb.append(")");
return new DefaultSqlUpdate(server, sb.toString(), bindParams);
}
public SqlUpdate createDelete(EbeanServer server){
BindParams bindParams = new BindParams();
StringBuilder sb = new StringBuilder();
sb.append("delete from ").append(tableName).append(" where ");
int count = 0;
Iterator<Entry<String, Object>> it = values.entrySet().iterator();
while (it.hasNext()) {
if (count++ > 0){
sb.append(" and ");
}
Map.Entry<String, Object> entry = it.next();
sb.append(entry.getKey());
sb.append(" = ?");
bindParams.setParameter(count, entry.getValue());
}
if (excludeIds != null){
IdInExpression idIn = new IdInExpression(excludeIds);
DefaultExpressionRequest er = new DefaultExpressionRequest(excludeDescriptor);
idIn.addSqlNoAlias(er);
idIn.addBindValues(er);
sb.append(" and not ( ");
sb.append(er.getSql());
sb.append(" ) ");
ArrayList<Object> bindValues = er.getBindValues();
for (int i = 0; i < bindValues.size(); i++) {
bindParams.setParameter(++count, bindValues.get(i));
}
}
return new DefaultSqlUpdate(server, sb.toString(), bindParams);
}
public SqlUpdate createDeleteChildren(EbeanServer server) {
BindParams bindParams = new BindParams();
StringBuilder sb = new StringBuilder();
sb.append("delete from ").append(tableName).append(" where ");
int count = 0;
Iterator<Entry<String, Object>> it = values.entrySet().iterator();
while (it.hasNext()) {
if (count++ > 0) {
sb.append(" and ");
}
Map.Entry<String, Object> entry = it.next();
sb.append(entry.getKey());
sb.append(" = ?");
bindParams.setParameter(count, entry.getValue());
}
return new DefaultSqlUpdate(server, sb.toString(), bindParams);
}
}
@@ -0,0 +1,87 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebeaninternal.api.SpiQuery;
/**
* Represents the type of a OneToMany or ManyToMany property.
*/
public class ManyType {
public static final ManyType JAVA_LIST = new ManyType(Underlying.LIST);
public static final ManyType JAVA_SET = new ManyType(Underlying.SET);
public static final ManyType JAVA_MAP = new ManyType(Underlying.MAP);
public enum Underlying {
LIST,
SET,
MAP
}
private final SpiQuery.Type queryType;
private final Underlying underlying;
private final CollectionTypeConverter typeConverter;
private ManyType(Underlying underlying) {
this(underlying, null);
}
public ManyType(Underlying underlying, CollectionTypeConverter typeConverter) {
this.underlying = underlying;
this.typeConverter = typeConverter;
switch (underlying) {
case LIST:
queryType = SpiQuery.Type.LIST;
break;
case SET:
queryType = SpiQuery.Type.SET;
break;
default:
queryType = SpiQuery.Type.MAP;
break;
}
}
/**
* Return the matching Query type.
*/
public SpiQuery.Type getQueryType() {
return queryType;
}
/**
* Return the underlying type.
*/
public Underlying getUnderlying() {
return underlying;
}
/**
* Return the type converter if there is one.
*/
public CollectionTypeConverter getTypeConverter() {
return typeConverter;
}
}
@@ -0,0 +1,78 @@
package com.avaje.ebeaninternal.server.deploy;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Helper object to find generic parameter types for a given class.
*/
public class ParamTypeUtil {
/**
* Find and return the parameter type given a generic interface or class.
* <p>
* This assumes there is only one generic parameter.
* </p>
* <p>
* Returns null if no match was found.
* </p>
* @param cls the class to search for the parameter type
* @param matchType the type which has the generic parameter
*/
public static Class<?> findParamType(Class<?> cls, Class<?> matchType) {
// search for: implementing a generic interface
Type paramType = matchByInterfaces(cls, matchType);
if (paramType == null){
// search for: extending a generic class
Type genericSuperclass = cls.getGenericSuperclass();
if (genericSuperclass != null){
paramType = matchParamType(genericSuperclass, matchType);
}
}
if (paramType instanceof Class<?>){
// only interested in classes
return (Class<?>)paramType;
} else {
return null;
}
}
/**
* Check if the type is a generic one with parameters and of the correct type we are
* searching for. Return the parameter type if this matches otherwise return null.
*/
private static Type matchParamType(Type type, Class<?> matchType) {
if (type instanceof ParameterizedType){
ParameterizedType pt = (ParameterizedType)type;
Type rawType = pt.getRawType();
boolean isAssignable = matchType.isAssignableFrom((Class<?>) rawType);
if (isAssignable) {
// assume there is only one parameter type
Type[] typeArguments = pt.getActualTypeArguments();
if (typeArguments.length != 1){
String m = "Expecting only 1 generic paramater but got "+typeArguments.length+" for "+type;
throw new RuntimeException(m);
}
return typeArguments[0];
}
}
return null;
}
/**
* Search the interfaces this class implements.
*/
private static Type matchByInterfaces(Class<?> cls, Class<?> matchType) {
Type[] gis = cls.getGenericInterfaces();
for (int i = 0; i < gis.length; i++) {
Type match = matchParamType(gis[i], matchType);
if (match != null){
return match;
}
}
return null;
}
}
@@ -0,0 +1,61 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.util.List;
import java.util.logging.Logger;
import com.avaje.ebean.event.BeanPersistController;
import com.avaje.ebeaninternal.server.core.BootupClasses;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanDescriptor;
/**
* Default implementation for creating BeanControllers.
*/
public class PersistControllerManager {
private static final Logger logger = Logger.getLogger(PersistControllerManager.class.getName());
private final List<BeanPersistController> list;
public PersistControllerManager(BootupClasses bootupClasses){
list = bootupClasses.getBeanPersistControllers();
}
public int getRegisterCount() {
return list.size();
}
/**
* Return the BeanPersistController for a given entity type.
*/
public void addPersistControllers(DeployBeanDescriptor<?> deployDesc){
for (int i = 0; i < list.size(); i++) {
BeanPersistController c = list.get(i);
if (c.isRegisterFor(deployDesc.getBeanType())){
logger.fine("BeanPersistController on[" + deployDesc.getFullName() + "] " + c.getClass().getName());
deployDesc.addPersistController(c);
}
}
}
}
@@ -0,0 +1,85 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import com.avaje.ebean.event.BeanPersistListener;
import com.avaje.ebeaninternal.server.core.BootupClasses;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanDescriptor;
/**
* Manages the assignment/registration of BeanPersistListener with their
* respective DeployBeanDescriptor's.
*/
public class PersistListenerManager {
private static final Logger logger = Logger.getLogger(PersistListenerManager.class.getName());
private final List<BeanPersistListener<?>> list;
public PersistListenerManager(BootupClasses bootupClasses) {
list = bootupClasses.getBeanPersistListeners();
}
public int getRegisterCount() {
return list.size();
}
/**
* Return the BeanPersistController for a given entity type.
*/
@SuppressWarnings("unchecked")
public <T> void addPersistListeners(DeployBeanDescriptor<T> deployDesc) {
for (int i = 0; i < list.size(); i++) {
BeanPersistListener<?> c = list.get(i);
if (isRegisterFor(deployDesc.getBeanType(), c)) {
logger.fine("BeanPersistListener on[" + deployDesc.getFullName() + "] " + c.getClass().getName());
deployDesc.addPersistListener((BeanPersistListener<T>) c);
}
}
}
public static boolean isRegisterFor(Class<?> beanType, BeanPersistListener<?> c) {
Class<?> listenerEntity = getEntityClass(c.getClass());
return beanType.equals(listenerEntity);
}
/**
* Find the entity class given the controller class.
* <p>
* This uses reflection to find the generics parameter type.
* </p>
*/
private static Class<?> getEntityClass(Class<?> controller) {
Class<?> cls = ParamTypeUtil.findParamType(controller, BeanPersistListener.class);
if (cls == null) {
String msg = "Could not determine the entity class (generics parameter type) from " + controller
+ " using reflection.";
throw new PersistenceException(msg);
}
return cls;
}
}
@@ -0,0 +1,104 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
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);
}
}
}
@@ -0,0 +1,72 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
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);
}
}
}
@@ -0,0 +1,48 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import scala.collection.JavaConversions;
/**
* Converts between Java List and Scala mutable Buffer.
*
* @author rbygrave
*/
public class ScalaBufferConverter implements CollectionTypeConverter {
// @SuppressWarnings({ "rawtypes" })
public Object toUnderlying(Object wrapped) {
throw new IllegalArgumentException("Scala types not supported in this build");
// if (wrapped instanceof JavaConversions.JListWrapper){
// return ((JavaConversions.JListWrapper)wrapped).underlying();
// }
// return null;
}
public Object toWrapped(Object wrapped) {
throw new IllegalArgumentException("Scala types not supported in this build");
// if (wrapped instanceof java.util.List<?>){
// return JavaConversions.asScalaBuffer((java.util.List<?>)wrapped);
// }
// return wrapped;
}
}
@@ -0,0 +1,48 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import scala.collection.JavaConversions;
/**
* Converts between Java Map and Scala mutable Map.
*
* @author rbygrave
*/
public class ScalaMapConverter implements CollectionTypeConverter {
// @SuppressWarnings({ "rawtypes" })
public Object toUnderlying(Object wrapped) {
throw new IllegalArgumentException("Scala types not supported in this build");
// if (wrapped instanceof JavaConversions.JMapWrapper){
// return ((JavaConversions.JMapWrapper)wrapped).underlying();
// }
// return null;
}
public Object toWrapped(Object wrapped) {
throw new IllegalArgumentException("Scala types not supported in this build");
// if (wrapped instanceof java.util.Map<?,?>){
// return JavaConversions.mapAsScalaMap((java.util.Map<?,?>)wrapped);
// }
// return wrapped;
}
}
@@ -0,0 +1,49 @@
/**
* Copyright (C) 2009 Authors
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import scala.collection.JavaConversions;
import scala.collection.convert.DecorateAsScala;
/**
* Converts between Java Set and Scala mutable Set.
*
* @author rbygrave
*/
public class ScalaSetConverter implements CollectionTypeConverter {
// @SuppressWarnings({ "rawtypes" })
public Object toUnderlying(Object wrapped) {
throw new IllegalArgumentException("Scala types not supported in this build");
// if (wrapped instanceof JavaConversions.JSetWrapper){
// return ((JavaConversions.JSetWrapper)wrapped).underlying();
// }
// return null;
}
public Object toWrapped(Object wrapped) {
throw new IllegalArgumentException("Scala types not supported in this build");
// if (wrapped instanceof java.util.Set<?>){
// return JavaConversions.asScalaSet((java.util.Set<?>)wrapped);
// }
// return wrapped;
}
}
@@ -0,0 +1,227 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import com.avaje.ebeaninternal.server.deploy.meta.DeployTableJoin;
import com.avaje.ebeaninternal.server.deploy.meta.DeployTableJoinColumn;
import com.avaje.ebeaninternal.server.query.SplitName;
import com.avaje.ebeaninternal.server.query.SqlBeanLoad;
import java.sql.SQLException;
import java.util.LinkedHashMap;
/**
* Represents a join to another table.
*/
public final class TableJoin {
public static final String NEW_LINE = "\n";
public static final String LEFT_OUTER = "left outer join";
public static final String JOIN = "join";
/**
* Flag set when the imported key maps to the primary key.
* This occurs for intersection tables (ManyToMany).
*/
private final boolean importedPrimaryKey;
/**
* The joined table.
*/
private final String table;
/**
* The type of join. LEFT OUTER etc.
*/
private final String type;
/**
* The persist cascade info.
*/
private final BeanCascadeInfo cascadeInfo;
/**
* Properties as an array.
*/
private final BeanProperty[] properties;
/**
* Columns as an array.
*/
private final TableJoinColumn[] columns;
/**
* Create a TableJoin.
*/
public TableJoin(DeployTableJoin deploy, LinkedHashMap<String,BeanProperty> propMap) {
this.importedPrimaryKey = deploy.isImportedPrimaryKey();
this.table = InternString.intern(deploy.getTable());
this.type = InternString.intern(deploy.getType());
this.cascadeInfo = deploy.getCascadeInfo();
DeployTableJoinColumn[] deployCols = deploy.columns();
this.columns = new TableJoinColumn[deployCols.length];
for (int i = 0; i < deployCols.length; i++) {
this.columns[i] = new TableJoinColumn(deployCols[i]);
}
DeployBeanProperty[] deployProps = deploy.properties();
if (deployProps.length > 0 && propMap == null){
throw new NullPointerException("propMap is null?");
}
this.properties = new BeanProperty[deployProps.length];
for (int i = 0; i < deployProps.length; i++) {
BeanProperty prop = propMap.get(deployProps[i].getName());
this.properties[i] = prop;
}
}
/**
* Create a tableJoin based on this object but with different alias.
*/
public TableJoin createWithAlias(String localAlias, String foreignAlias) {
return new TableJoin(this, localAlias, foreignAlias);
}
/**
* Construct a copy but with different table alias'.
*/
private TableJoin(TableJoin join, String localAlias, String foreignAlias){
// copy the immutable fields
this.importedPrimaryKey = join.importedPrimaryKey;
this.table = join.table;
this.type = join.type;
this.cascadeInfo = join.cascadeInfo;
this.properties = join.properties;
this.columns = join.columns;
}
public String toString() {
StringBuilder sb = new StringBuilder(30);
sb.append(type).append(" ").append(table).append(" ");
for (int i = 0; i < columns.length; i++) {
sb.append(columns[i]).append(" ");
}
return sb.toString();
}
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
for (int i = 0, x = properties.length; i < x; i++) {
properties[i].appendSelect(ctx, subQuery);
}
}
public void load(SqlBeanLoad sqlBeanLoad) throws SQLException {
for (int i = 0, x = properties.length; i < x; i++) {
properties[i].load(sqlBeanLoad);
}
}
public Object readSet(DbReadContext ctx, Object bean, Class<?> type) throws SQLException {
for (int i = 0, x = properties.length; i < x; i++) {
properties[i].readSet(ctx, bean, type);
}
return null;
}
/**
* Return true if the imported foreign key maps to the primary key.
*/
public boolean isImportedPrimaryKey() {
return importedPrimaryKey;
}
/**
* Return the persist info.
*/
public BeanCascadeInfo getCascadeInfo() {
return cascadeInfo;
}
/**
* Return the join columns.
*/
public TableJoinColumn[] columns() {
return columns;
}
/**
* For secondary table joins returns the properties mapped to that table.
*/
public BeanProperty[] properties() {
return properties;
}
/**
* Return the joined table name.
*/
public String getTable() {
return table;
}
/**
* Return the type of join. LEFT OUTER JOIN etc.
*/
public String getType() {
return type;
}
/**
* Return true if this join is a left outer join.
*/
public boolean isOuterJoin() {
return type.equals(LEFT_OUTER);
}
public boolean addJoin(boolean forceOuterJoin, String prefix, DbSqlContext ctx) {
String[] names = SplitName.split(prefix);
String a1 = ctx.getTableAlias(names[0]);
String a2 = ctx.getTableAlias(prefix);
return addJoin(forceOuterJoin, a1, a2, ctx);
}
public boolean addJoin(boolean forceOuterJoin, String a1, String a2, DbSqlContext ctx) {
ctx.addJoin(forceOuterJoin?LEFT_OUTER:type, table, columns(), a1, a2);
return forceOuterJoin || LEFT_OUTER.equals(type);
}
/**
* Explicitly add a (non-outer) join.
*/
public void addInnerJoin(String a1, String a2, DbSqlContext ctx) {
ctx.addJoin(JOIN, table, columns(), a1, a2);
}
}
@@ -0,0 +1,86 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.meta.DeployTableJoinColumn;
/**
* A join pair of local and foreign properties.
*/
public class TableJoinColumn {
/**
* The local database column name.
*/
private final String localDbColumn;
/**
* The foreign database column name.
*/
private final String foreignDbColumn;
private final boolean insertable;
private final boolean updateable;
/**
* Create the pair.
*/
public TableJoinColumn(DeployTableJoinColumn deploy) {
this.localDbColumn = InternString.intern(deploy.getLocalDbColumn());
this.foreignDbColumn = InternString.intern(deploy.getForeignDbColumn());
this.insertable = deploy.isInsertable();
this.updateable = deploy.isUpdateable();
}
public String toString() {
return localDbColumn+" = "+foreignDbColumn;
}
/**
* Return the foreign database column name.
*/
public String getForeignDbColumn() {
return foreignDbColumn;
}
/**
* Return the local database column name.
*/
public String getLocalDbColumn() {
return localDbColumn;
}
/**
* Return true if this column should be insertable.
*/
public boolean isInsertable() {
return insertable;
}
/**
* Return true if this column should be updateable.
*/
public boolean isUpdateable() {
return updateable;
}
}
@@ -0,0 +1,16 @@
<!ELEMENT ebean (table | iudextender | findextender | datasource | primarykeys | property)* >
<!ELEMENT table EMPTY >
<!ATTLIST table name CDATA #REQUIRED>
<!ELEMENT iudextender EMPTY >
<!ATTLIST iudextender classname CDATA #REQUIRED>
<!ELEMENT findextender EMPTY >
<!ATTLIST findextender classname CDATA #REQUIRED>
<!ELEMENT datasource EMPTY >
<!ATTLIST datasource name CDATA #REQUIRED>
<!ELEMENT primarykeys EMPTY >
<!ATTLIST primarykeys keys CDATA #REQUIRED>
<!ELEMENT property EMPTY >
<!ATTLIST property name CDATA #REQUIRED
datatype CDATA #REQUIRED
deploydatatype CDATA #IMPLIED
deployname CDATA #IMPLIED >
@@ -0,0 +1,83 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Types;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
/**
* Creates "Counter" GeneratedProperty for various types of number.
* <p>
* Aka, Integer, Long, Short etc.
* </p>
*/
public class CounterFactory {
final GeneratedCounterInteger integerCounter = new GeneratedCounterInteger();
final GeneratedCounterLong longCounter = new GeneratedCounterLong();
public void setCounter(DeployBeanProperty property) {
property.setGeneratedProperty(createCounter(property));
}
/**
* Create the GeneratedProperty based on the property type.
*/
private GeneratedProperty createCounter(DeployBeanProperty property) {
Class<?> propType = property.getPropertyType();
if (propType.equals(Integer.class) || propType.equals(int.class)) {
return integerCounter;
}
if (propType.equals(Long.class) || propType.equals(long.class)) {
return longCounter;
}
int type = getType(propType);
return new GeneratedCounter(type);
}
private int getType(Class<?> propType){
if (propType.equals(Short.class) || propType.equals(short.class)){
return Types.TINYINT;
}
if (propType.equals(BigDecimal.class)){
return Types.DECIMAL;
}
if (propType.equals(Double.class) || propType.equals(double.class)){
return Types.DOUBLE;
}
if (propType.equals(Float.class) || propType.equals(float.class)){
return Types.REAL;
}
if (propType.equals(BigInteger.class)){
return Types.BIGINT;
}
String msg = "Can not support Counter for type "+propType.getName();
throw new PersistenceException(msg);
}
}
@@ -0,0 +1,71 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebeaninternal.server.core.BasicTypeConverter;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* A general number counter for various number types.
*/
public class GeneratedCounter implements GeneratedProperty {
final int numberType;
public GeneratedCounter(int numberType) {
this.numberType = numberType;
}
/**
* Always returns a 1.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
Integer i = Integer.valueOf(1);
return BasicTypeConverter.convert(i, numberType);
}
/**
* Increments the current value by one.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
Number currVal = (Number) prop.getValue(bean);
Integer nextVal = Integer.valueOf(currVal.intValue() + 1);
return BasicTypeConverter.convert(nextVal, numberType);
}
/**
* Include this in every update.
*/
public boolean includeInUpdate() {
return true;
}
/**
* Include this in every insert setting initial counter value to 1.
*/
public boolean includeInInsert() {
return true;
}
public boolean isDDLNotNullable() {
return true;
}
}
@@ -0,0 +1,66 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* Used to create a counter version column for Integer.
*/
public class GeneratedCounterInteger implements GeneratedProperty {
public GeneratedCounterInteger() {
}
/**
* Always returns a 1.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
return Integer.valueOf(1);
}
/**
* Increments the current value by one.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
Integer i = (Integer) prop.getValue(bean);
return Integer.valueOf(i.intValue() + 1);
}
/**
* Include this in every update.
*/
public boolean includeInUpdate() {
return true;
}
/**
* Include this in every insert setting initial counter value to 1.
*/
public boolean includeInInsert() {
return true;
}
public boolean isDDLNotNullable() {
return true;
}
}
@@ -0,0 +1,66 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* Used to create a counter version column for Long.
*/
public class GeneratedCounterLong implements GeneratedProperty {
public GeneratedCounterLong() {
}
/**
* Always returns a 1.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
return Long.valueOf(1);
}
/**
* Increments the current value by one.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
Long i = (Long) prop.getValue(bean);
return Long.valueOf(i.longValue() + 1);
}
/**
* Include this in every update.
*/
public boolean includeInUpdate() {
return true;
}
/**
* Include this in every insert setting initial counter value to 1.
*/
public boolean includeInInsert() {
return true;
}
public boolean isDDLNotNullable() {
return true;
}
}
@@ -0,0 +1,63 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.util.Date;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* Used to generate a (java.util.Date) timestamp when a bean is inserted.
*/
public class GeneratedInsertDate implements GeneratedProperty {
/**
* Return the current time as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
return new Date(System.currentTimeMillis());
}
/**
* Just returns the beans original insert timestamp value.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
return prop.getValue(bean);
}
/**
* Return false.
*/
public boolean includeInUpdate() {
return false;
}
/**
* Return true.
*/
public boolean includeInInsert() {
return true;
}
public boolean isDDLNotNullable() {
return true;
}
}
@@ -0,0 +1,61 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* Used to generate a (Long) timestamp when a bean is inserted.
*/
public class GeneratedInsertLong implements GeneratedProperty {
/**
* Return the current time as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
return Long.valueOf(System.currentTimeMillis());
}
/**
* Just returns the beans original insert timestamp value.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
return prop.getValue(bean);
}
/**
* Return false.
*/
public boolean includeInUpdate() {
return false;
}
/**
* Return true.
*/
public boolean includeInInsert() {
return true;
}
public boolean isDDLNotNullable() {
return true;
}
}
@@ -0,0 +1,63 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.sql.Timestamp;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* Used to generate a timestamp when a bean is inserted.
*/
public class GeneratedInsertTimestamp implements GeneratedProperty {
/**
* Return the current time as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
return new Timestamp(System.currentTimeMillis());
}
/**
* Just returns the beans original insert timestamp value.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
return prop.getValue(bean);
}
/**
* Return false.
*/
public boolean includeInUpdate() {
return false;
}
/**
* Return true.
*/
public boolean includeInInsert() {
return true;
}
public boolean isDDLNotNullable() {
return true;
}
}
@@ -0,0 +1,59 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* Used to generate values for a property rather than have then set by the user.
* For example generate the update timestamp when a bean is updated.
*/
public interface GeneratedProperty {
/**
* Get the generated insert value for a specific property of a bean.
*/
public Object getInsertValue(BeanProperty prop, Object bean);
/**
* Get the generated update value for a specific property of a bean.
*/
public Object getUpdateValue(BeanProperty prop, Object bean);
/**
* Return true if this should always be includes in an update statement.
* <p>
* Used to include GeneratedUpdateTimestamp in dynamic table updates.
* </p>
*/
public boolean includeInUpdate();
/**
* Return true if this should be included in insert statements.
*/
public boolean includeInInsert();
/**
* Return true if the GeneratedProperty implies the DDL to create the DB
* column should have a not null constraint.
*/
public boolean isDDLNotNullable();
}
@@ -0,0 +1,84 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.math.BigDecimal;
import java.util.HashSet;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
/**
* Default implementation of GeneratedPropertyFactory.
*/
public class GeneratedPropertyFactory {
CounterFactory counterFactory;
InsertTimestampFactory insertFactory;
UpdateTimestampFactory updateFactory;
HashSet<String> numberTypes = new HashSet<String>();
public GeneratedPropertyFactory() {
counterFactory = new CounterFactory();
insertFactory = new InsertTimestampFactory();
updateFactory = new UpdateTimestampFactory();
numberTypes.add(Integer.class.getName());
numberTypes.add(int.class.getName());
numberTypes.add(Long.class.getName());
numberTypes.add(long.class.getName());
numberTypes.add(Short.class.getName());
numberTypes.add(short.class.getName());
numberTypes.add(Double.class.getName());
numberTypes.add(double.class.getName());
numberTypes.add(BigDecimal.class.getName());
}
private boolean isNumberType(String typeClassName) {
return numberTypes.contains(typeClassName);
}
public void setVersion(DeployBeanProperty property) {
if (isNumberType(property.getPropertyType().getName())) {
setCounter(property);
} else {
setUpdateTimestamp(property);
}
}
public void setCounter(DeployBeanProperty property) {
counterFactory.setCounter(property);
}
public void setInsertTimestamp(DeployBeanProperty property) {
insertFactory.setInsertTimestamp(property);
}
public void setUpdateTimestamp(DeployBeanProperty property) {
updateFactory.setUpdateTimestamp(property);
}
}
@@ -0,0 +1,64 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.util.Date;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* Generate a (java.util.Date) Timestamp whenever the bean is inserted or
* updated.
*/
public class GeneratedUpdateDate implements GeneratedProperty {
/**
* Return now as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
return new Date(System.currentTimeMillis());
}
/**
* Return now as a Timestamp.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
return new Date(System.currentTimeMillis());
}
/**
* For dynamic table updates make sure this is included.
*/
public boolean includeInUpdate() {
return true;
}
/**
* Include this in every insert.
*/
public boolean includeInInsert() {
return true;
}
public boolean isDDLNotNullable() {
return true;
}
}
@@ -0,0 +1,61 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* Generate a (Long) Timestamp whenever the bean is inserted or updated.
*/
public class GeneratedUpdateLong implements GeneratedProperty {
/**
* Return now as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
return Long.valueOf(System.currentTimeMillis());
}
/**
* Return now as a Timestamp.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
return Long.valueOf(System.currentTimeMillis());
}
/**
* For dynamic table updates make sure this is included.
*/
public boolean includeInUpdate() {
return true;
}
/**
* Include this in every insert.
*/
public boolean includeInInsert() {
return true;
}
public boolean isDDLNotNullable() {
return true;
}
}
@@ -0,0 +1,63 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.sql.Timestamp;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
/**
* Generate a Timestamp whenever the bean is inserted or updated.
*/
public class GeneratedUpdateTimestamp implements GeneratedProperty {
/**
* Return now as a Timestamp.
*/
public Object getInsertValue(BeanProperty prop, Object bean) {
return new Timestamp(System.currentTimeMillis());
}
/**
* Return now as a Timestamp.
*/
public Object getUpdateValue(BeanProperty prop, Object bean) {
return new Timestamp(System.currentTimeMillis());
}
/**
* For dynamic table updates make sure this is included.
*/
public boolean includeInUpdate() {
return true;
}
/**
* Include this in every insert.
*/
public boolean includeInInsert() {
return true;
}
public boolean isDDLNotNullable() {
return true;
}
}
@@ -0,0 +1,66 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.sql.Timestamp;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
/**
* Helper for creating Insert timestamp GeneratedProperty objects.
*/
public class InsertTimestampFactory {
final GeneratedInsertTimestamp timestamp = new GeneratedInsertTimestamp();
final GeneratedInsertDate utilDate = new GeneratedInsertDate();
final GeneratedInsertLong longTime = new GeneratedInsertLong();
public void setInsertTimestamp(DeployBeanProperty property) {
property.setGeneratedProperty(createInsertTimestamp(property));
}
/**
* Create the insert GeneratedProperty depending on the property type.
*/
public GeneratedProperty createInsertTimestamp(DeployBeanProperty property) {
Class<?> propType = property.getPropertyType();
if (propType.equals(Timestamp.class)) {
return timestamp;
}
if (propType.equals(java.util.Date.class)) {
return utilDate;
}
if (propType.equals(Long.class) || propType.equals(long.class)) {
return longTime;
}
//TODO: Support JODA Time objects ... perhaps others?
String msg = "Generated Insert Timestamp not supported on "+propType.getName();
throw new PersistenceException(msg);
}
}
@@ -0,0 +1,66 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
import java.sql.Timestamp;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
/**
* Helper for creating Update timestamp GeneratedProperty objects.
*/
public class UpdateTimestampFactory {
final GeneratedUpdateTimestamp timestamp = new GeneratedUpdateTimestamp();
final GeneratedUpdateDate utilDate = new GeneratedUpdateDate();
final GeneratedUpdateLong longTime = new GeneratedUpdateLong();
public void setUpdateTimestamp(DeployBeanProperty property) {
property.setGeneratedProperty(createUpdateTimestamp(property));
}
/**
* Create the update GeneratedProperty depending on the property type.
*/
private GeneratedProperty createUpdateTimestamp(DeployBeanProperty property) {
Class<?> propType = property.getPropertyType();
if (propType.equals(Timestamp.class)) {
return timestamp;
}
if (propType.equals(java.util.Date.class)) {
return utilDate;
}
if (propType.equals(Long.class) || propType.equals(long.class)) {
return longTime;
}
//TODO: Support JODA Time objects ... perhaps others?
String msg = "Generated update Timestamp not supported on "+propType.getName();
throw new PersistenceException(msg);
}
}
@@ -0,0 +1,9 @@
<HTML>
<HEAD>
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
<TITLE>Counter, Insert Timestamp, Update Timestamp support</TITLE>
</HEAD>
<Body BGCOLOR="#ffffff">
Counter, Insert Timestamp, Update Timestamp support
</Body>
</HTML>
@@ -0,0 +1,192 @@
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.List;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
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.type.DataBind;
/**
* Binds id values to prepared statements.
*/
public interface IdBinder {
/**
* Initialise the binder.
*/
public void initialise();
/**
* Convert the Id value as a Lucene string term.
*/
public String writeTerm(Object idValue);
/**
* Convert the Lucene string term into an Id value.
*/
public Object readTerm(String idTermValue);
/**
* Write the Id value to binary DataOuput.
*/
public void writeData(DataOutput dataOutput, Object idValue) throws IOException;
/**
* Read the Id value from the binary DataInput.
*/
public Object readData(DataInput dataInput) throws IOException;
/**
* Adds RDN's to the LdapName using the id value.
*/
public void createLdapNameById(LdapName name, Object id) throws InvalidNameException;
/**
* Adds RDN's to the LdapName using the id value from the bean.
*/
public void createLdapNameByBean(LdapName name, Object bean) throws InvalidNameException;
/**
* Return the name(s) of the Id property(s).
* Comma delimited if there is more than one.
* <p>
* This can be used to include in a query.
* </p>
*/
public String getIdProperty();
/**
* Find a BeanProperty that is mapped to the database column.
*/
public BeanProperty findBeanProperty(String dbColumnName);
/**
* Return the number of scalar properties for this id.
*/
public int getPropertyCount();
/**
* Return false if the id is a simple scalar and false if it is embedded or concatenated.
*/
public boolean isComplexId();
/**
* Return the default order by that may need to be used if the query includes a many property.
*/
public String getDefaultOrderBy();
public String getOrderBy(String pathPrefix, boolean ascending);
/**
* Return the values as an array of scalar bindable values.
* <p>
* For concatenated keys that use an Embedded bean or multiple id properties
* this determines the field values are returns them as an Object array.
* </p>
* <p>
* Added primarily for Query.addWhere().add(Expr.idEq()) support.
* </p>
*/
public Object[] getBindValues(Object idValue);
/**
* Return the id values for a given bean.
*/
public Object[] getIdValues(Object bean);
/**
* Build a string of the logical expressions.
* <p>
* Typically used to build a id = ? string.
* </p>
*/
public String getAssocOneIdExpr(String prefix, String operator);
/**
* Return the logical id in expression taking into account embedded id's.
*/
public String getAssocIdInExpr(String prefix);
/**
* Binds an id value to a prepared statement.
*/
public void bindId(DataBind dataBind, Object value) throws SQLException;
/**
* Bind the id value to a SqlUpdate statement.
*/
public void bindId(DefaultSqlUpdate sqlUpdate, Object value);
public void addIdInBindValue(SpiExpressionRequest request, Object value);
/**
* Return the sql for binding the id using an IN clause.
*/
public String getBindIdInSql(String baseTableAlias);
/**
* Return the binding expression (like "?" or "(?,?)")for the Id.
*/
public String getIdInValueExpr(int size);
/**
* Same as getIdInValueExpr but for delete by id.
*/
public String getIdInValueExprDelete(int size);
public void buildSelectExpressionChain(String prefix, List<String> selectChain);
/**
* 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;
/**
* Ignore the appropriate number of scalar properties for this id.
*/
public void loadIgnore(DbReadContext ctx);
/**
* Read the id value from the result set and return it.
*/
public Object read(DbReadContext ctx) throws SQLException;
/**
* Append to the select clause.
*/
public void appendSelect(DbSqlContext ctx, boolean subQuery);
/**
* Return the sql for binding the id to. This includes table alias and columns that make up the id.
*/
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>
* The Id value is not assumed to be the correct type so it is converted to
* the correct type. Typically this is because we could get a Integer, Long
* or BigDecimal depending on the JDBC driver and situation.
* </p>
* <p>
* If the bean is not null, then the value is set to the bean.
* </p>
*/
public Object convertSetId(Object idValue, Object bean);
}
@@ -0,0 +1,455 @@
package com.avaje.ebeaninternal.server.deploy.id;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
import com.avaje.ebeaninternal.server.query.SplitName;
import com.avaje.ebeaninternal.server.type.DataBind;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.persistence.PersistenceException;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
/**
* Bind an Id that is an Embedded bean.
*/
public final class IdBinderEmbedded implements IdBinder {
private final BeanPropertyAssocOne<?> embIdProperty;
private final boolean idInExpandedForm;
private BeanProperty[] props;
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();
}
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 void createLdapNameById(LdapName name, Object id) throws InvalidNameException {
for (int i = 0; i < props.length; i++) {
Object v = props[i].getValue(id);
Rdn rdn = new Rdn(props[i].getDbColumn(), v);
name.add(rdn);
}
}
public void createLdapNameByBean(LdapName name, Object bean) throws InvalidNameException {
Object id = embIdProperty.getValue(bean);
createLdapNameById(name, id);
}
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;
}
/**
* Convert the lucene string term value into embedded id.
*/
public Object readTerm(String idTermValue) {
String[] split = idTermValue.split("|");
if (split.length != props.length){
String msg = "Failed to split ["+idTermValue+"] using | for id.";
throw new PersistenceException(msg);
}
Object embId = idDesc.createVanillaBean();
for (int i = 0; i < props.length; i++) {
Object v = props[i].getScalarType().parse(split[i]);
props[i].setValue(embId, v);
}
return embId;
}
/**
* Write the embedded id as a Lucene string term value.
*/
public String writeTerm(Object idValue) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
Object v = props[i].getValue(idValue);
String formatValue = props[i].getScalarType().format(v);
if (i > 0){
sb.append("|");
}
sb.append(formatValue);
}
return sb.toString();
}
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.createVanillaBean();
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;
} 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(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 {
Object embId = idDesc.createVanillaBean();
boolean notNull = true;
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;
}
}
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;
}
}
@@ -0,0 +1,152 @@
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.List;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
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.type.DataBind;
/**
* For beans with no id properties AKA report type beans.
*/
public final class IdBinderEmpty implements IdBinder {
private static final String bindIdSql = "";
private static final BeanProperty[] properties = new BeanProperty[0];
public IdBinderEmpty() {
}
public void initialise(){
}
public Object readTerm(String idTermValue) {
return null;
}
public String writeTerm(Object idValue) {
return null;
}
public String getOrderBy(String pathPrefix, boolean ascending){
return pathPrefix;
}
public void buildSelectExpressionChain(String prefix, List<String> selectChain) {
}
public void createLdapNameById(LdapName name, Object id) throws InvalidNameException {
}
public void createLdapNameByBean(LdapName name, Object bean) throws InvalidNameException {
}
public int getPropertyCount() {
return 0;
}
public String getIdProperty() {
return null;
}
public BeanProperty findBeanProperty(String dbColumnName) {
return null;
}
public boolean isComplexId(){
return true;
}
public String getDefaultOrderBy() {
// this should never happen?
return "";
}
public BeanProperty[] getProperties() {
return properties;
}
public String getBindIdSql(String baseTableAlias) {
return bindIdSql;
}
public String getAssocOneIdExpr(String prefix, String operator){
return null;
}
public String getAssocIdInExpr(String prefix) {
return null;
}
public void addIdInBindValue(SpiExpressionRequest request, Object value) {
}
public String getIdInValueExprDelete(int size) {
return getIdInValueExpr(size);
}
public String getIdInValueExpr(int size) {
return "";
}
public String getBindIdInSql(String baseTableAlias) {
return null;
}
public Object[] getIdValues(Object bean){
return null;
}
public Object[] getBindValues(Object idValue){
return new Object[]{idValue};
}
public void bindId(DefaultSqlUpdate sqlUpdate, Object value) {
}
public void bindId(DataBind dataBind, Object value) throws SQLException {
}
public void loadIgnore(DbReadContext ctx) {
}
public Object readSet(DbReadContext ctx, Object bean) throws SQLException {
return null;
}
public Object read(DbReadContext ctx) throws SQLException {
return null;
}
public void appendSelect(DbSqlContext ctx, boolean subQuery) {
}
public Object convertSetId(Object idValue, Object bean){
return idValue;
}
public Object readData(DataInput dataOutput) throws IOException {
return null;
}
public void writeData(DataOutput dataOutput, Object idValue) throws IOException {
}
}
@@ -0,0 +1,59 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.id;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
/**
* Creates the appropriate IdConvertSet depending on the type of Id property(s).
*/
public class IdBinderFactory {
private static final IdBinderEmpty EMPTY = new IdBinderEmpty();
private final boolean idInExpandedForm;
public IdBinderFactory(boolean idInExpandedForm) {
this.idInExpandedForm = idInExpandedForm;
}
/**
* Create the IdConvertSet for the given type of Id properties.
*/
public IdBinder createIdBinder(BeanProperty[] uids) {
if (uids.length == 0){
// 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]);
}
} else {
return new IdBinderMultiple(uids);
}
}
}
@@ -0,0 +1,461 @@
package com.avaje.ebeaninternal.server.deploy.id;
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;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.persistence.PersistenceException;
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;
/**
* 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 createLdapNameById(LdapName name, Object id) throws InvalidNameException {
if (id instanceof Map<?,?> == false){
throw new RuntimeException("Expecting a Map for concatinated key");
}
Map<?,?> mapId = (Map<?,?>)id;
for (int i = 0; i < props.length; i++) {
Object v = mapId.get(props[i].getName());
if (v == null){
throw new RuntimeException("No value in Map for key "+props[i].getName());
}
Rdn rdn = new Rdn(props[i].getDbColumn(), v);
name.add(rdn);
}
}
public void buildSelectExpressionChain(String prefix, List<String> selectChain) {
for (int i = 0; i < props.length; i++) {
props[i].buildSelectExpressionChain(prefix, selectChain);
}
}
public void createLdapNameByBean(LdapName name, Object bean) throws InvalidNameException {
for (int i = 0; i < props.length; i++) {
Object v = props[i].getValue(bean);
Rdn rdn = new Rdn(props[i].getDbColumn(), v);
name.add(rdn);
}
}
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 readTerm(String idTermValue) {
String[] split = idTermValue.split("|");
if (split.length != props.length){
String msg = "Failed to split ["+idTermValue+"] using | for id.";
throw new PersistenceException(msg);
}
Map<String, Object> uidMap = new LinkedHashMap<String, Object>();
for (int i = 0; i < props.length; i++) {
Object v = props[i].getScalarType().parse(split[i]);
uidMap.put(props[i].getName(), v);
}
return uidMap;
}
@SuppressWarnings("unchecked")
public String writeTerm(Object idValue) {
Map<String, ?> uidMap = (Map<String, ?>) idValue;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
Object v = uidMap.get(props[i].getName());
String formatValue = props[i].getScalarType().format(v);
if (i > 0){
sb.append("|");
}
sb.append(formatValue);
}
return sb.toString();
}
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;
}
}
@@ -0,0 +1,233 @@
package com.avaje.ebeaninternal.server.deploy.id;
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.type.DataBind;
import com.avaje.ebeaninternal.server.type.ScalarType;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
/**
* Bind an Id where the Id is made of a single property (not embedded).
*/
public final class IdBinderSimple implements IdBinder {
private final BeanProperty idProperty;
private final String bindIdSql;
private final BeanProperty[] properties;
private final Class<?> expectedType;
@SuppressWarnings("rawtypes")
private final ScalarType scalarType;
public IdBinderSimple(BeanProperty idProperty) {
this.idProperty = idProperty;
this.scalarType = idProperty.getScalarType();
this.expectedType = idProperty.getPropertyType();
this.properties = new BeanProperty[1];
properties[0] = idProperty;
bindIdSql = InternString.intern(idProperty.getDbColumn()+" = ? ");
}
public void initialise(){
// do nothing
}
public Object readTerm(String idTermValue) {
return scalarType.parse(idTermValue);
}
public String writeTerm(Object idValue) {
return scalarType.format(idValue);
}
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) {
idProperty.buildSelectExpressionChain(prefix, selectChain);
}
public void createLdapNameById(LdapName name, Object id) throws InvalidNameException {
Rdn rdn = new Rdn(idProperty.getDbColumn(), id);
name.add(rdn);
}
public void createLdapNameByBean(LdapName name, Object bean) throws InvalidNameException {
Object id = idProperty.getValue(bean);
createLdapNameById(name, id);
}
/**
* Returns 1.
*/
public int getPropertyCount() {
return 1;
}
public String getIdProperty() {
return idProperty.getName();
}
public BeanProperty findBeanProperty(String dbColumnName) {
if (dbColumnName.equalsIgnoreCase(idProperty.getDbColumn())){
return idProperty;
}
return null;
}
public boolean isComplexId(){
return false;
}
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 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 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 {
value = idProperty.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;
}
}
@@ -0,0 +1,72 @@
package com.avaje.ebeaninternal.server.deploy.id;
import java.sql.SQLException;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
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;
/**
* Represents a imported property.
*/
public interface ImportedId {
public void addFkeys(String name);
/**
* Return true if this id is a simple single scalar value. False if it is a
* compound id (embedded or multiple).
*/
public boolean isScalar();
/**
* Return the logical property name.
*/
public String getLogicalName();
/**
* For scalar id return the related single db column.
* <p>
* This is essentially the imported foreign key column (where there is only
* one).
* </p>
*/
public String getDbColumn();
/**
* Append the the SQL query statement.
*/
public void sqlAppend(DbSqlContext ctx);
/**
* Append to the DML statement.
*/
public void dmlAppend(GenerateDmlRequest request);
/**
* 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);
/**
* Bind the value from the bean.
*/
public Object bind(BindableRequest request, Object bean, boolean bindNull) throws SQLException;
/**
* For inserting into ManyToMany intersection.
*/
public void buildImport(IntersectionRow row, Object other);
/**
* Used to derive a missing concatenated key from multiple imported keys.
*/
public BeanProperty findMatchImport(String matchDbColumn);
}
@@ -0,0 +1,164 @@
package com.avaje.ebeaninternal.server.deploy.id;
import java.sql.SQLException;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.server.deploy.BeanFkeyProperty;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssoc;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
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 Embedded id.
*/
public class ImportedIdEmbedded implements ImportedId {
final BeanPropertyAssoc<?> owner;
final BeanPropertyAssocOne<?> foreignAssocOne;
final ImportedIdSimple[] imported;
public ImportedIdEmbedded(BeanPropertyAssoc<?> owner, BeanPropertyAssocOne<?> foreignAssocOne, ImportedIdSimple[] imported) {
this.owner = owner;
this.foreignAssocOne = foreignAssocOne;
this.imported = imported;
}
public void addFkeys(String name) {
BeanProperty[] embeddedProps = foreignAssocOne.getProperties();
for (int i = 0; i < imported.length; i++) {
String n = name+"."+foreignAssocOne.getName()+"."+embeddedProps[i].getName();
BeanFkeyProperty fkey = new BeanFkeyProperty(null, n, imported[i].localDbColumn, foreignAssocOne.getDeployOrder());
owner.getBeanDescriptor().add(fkey);
}
}
public boolean isScalar(){
return false;
}
public String getLogicalName() {
return owner.getName()+"."+foreignAssocOne.getName();
}
public String getDbColumn(){
return null;
}
public void sqlAppend(DbSqlContext ctx) {
for (int i = 0; i < imported.length; i++) {
ctx.appendColumn(imported[i].localDbColumn);
}
}
public void dmlAppend(GenerateDmlRequest request) {
for (int i = 0; i < imported.length; i++) {
request.appendColumn(imported[i].localDbColumn);
}
}
public void dmlWhere(GenerateDmlRequest request, Object bean){
Object embeddedId = null;
if (bean != null) {
embeddedId = foreignAssocOne.getValue(bean);
}
if (embeddedId == null){
for (int i = 0; i < imported.length; i++) {
if (imported[i].owner.isDbUpdatable()) {
request.appendColumnIsNull(imported[i].localDbColumn);
}
}
} else {
for (int i = 0; i < imported.length; i++) {
if (imported[i].owner.isDbUpdatable()) {
Object value = imported[i].foreignProperty.getValue(embeddedId);
if (value == null){
request.appendColumnIsNull(imported[i].localDbColumn);
} else {
request.appendColumn(imported[i].localDbColumn);
}
}
}
}
}
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 {
Object embeddedId = null;
if (bean != null) {
embeddedId = foreignAssocOne.getValue(bean);
}
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);
}
}
} else {
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);
}
}
}
// hmmm, not worrying about this just yet
return null;
}
public void buildImport(IntersectionRow row, Object other){
Object embeddedId = foreignAssocOne.getValue(other);
if (embeddedId == null){
String msg = "Foreign Key value null?";
throw new PersistenceException(msg);
}
for (int i = 0; i < imported.length; i++) {
Object scalarValue = imported[i].foreignProperty.getValue(embeddedId);
row.put(imported[i].localDbColumn, scalarValue);
}
}
/**
* Not supported for embedded id.
*/
public BeanProperty findMatchImport(String matchDbColumn) {
BeanProperty p = null;
for (int i = 0; i < imported.length; i++) {
p = imported[i].findMatchImport(matchDbColumn);
if (p != null){
return p;
}
}
return p;
}
}
@@ -0,0 +1,123 @@
package com.avaje.ebeaninternal.server.deploy.id;
import java.sql.SQLException;
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.
*/
public class ImportedIdMultiple implements ImportedId {
final BeanPropertyAssoc<?> owner;
final ImportedIdSimple[] imported;
public ImportedIdMultiple(BeanPropertyAssoc<?> owner, ImportedIdSimple[] imported) {
this.owner = owner;
this.imported = imported;
}
public void addFkeys(String name) {
// not supporting addFkeys for ImportedIdMultiple
}
public String getLogicalName() {
return null;
}
public boolean isScalar(){
return false;
}
public String getDbColumn(){
return null;
}
public void sqlAppend(DbSqlContext ctx) {
for (int i = 0; i < imported.length; i++) {
ctx.appendColumn(imported[i].localDbColumn);
}
}
public void dmlAppend(GenerateDmlRequest request) {
for (int i = 0; i < imported.length; i++) {
request.appendColumn(imported[i].localDbColumn);
}
}
public void dmlWhere(GenerateDmlRequest request, Object bean){
if (bean == null){
for (int i = 0; i < imported.length; i++) {
request.appendColumnIsNull(imported[i].localDbColumn);
}
} else {
for (int i = 0; i < imported.length; i++) {
Object value = imported[i].foreignProperty.getValue(bean);
if (value == null){
request.appendColumnIsNull(imported[i].localDbColumn);
} else {
request.appendColumn(imported[i].localDbColumn);
}
}
}
}
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 {
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);
}
}
// hmmm, not worrying about this just yet
return null;
}
public void buildImport(IntersectionRow row, Object other){
for (int i = 0; i < imported.length; i++) {
Object scalarValue = imported[i].foreignProperty.getValue(other);
row.put(imported[i].localDbColumn, scalarValue);
}
}
/**
* Not supported for concatenated id.
*/
public BeanProperty findMatchImport(String matchDbColumn) {
BeanProperty p = null;
for (int i = 0; i < imported.length; i++) {
p = imported[i].findMatchImport(matchDbColumn);
if (p != null){
return p;
}
}
return p;
}
}
@@ -0,0 +1,161 @@
package com.avaje.ebeaninternal.server.deploy.id;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.BeanFkeyProperty;
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;
/**
* Single scalar imported id.
*/
public final class ImportedIdSimple implements ImportedId, Comparable<ImportedIdSimple> {
/**
* Helper class to sort ImportedIdSimple.
*/
private final static class EntryComparator implements Comparator<ImportedIdSimple> {
public int compare(ImportedIdSimple o1, ImportedIdSimple o2) {
return o1.compareTo(o2);
}
}
private static final EntryComparator COMPARATOR = new EntryComparator();
protected final BeanPropertyAssoc<?> owner;
protected final String localDbColumn;
protected final String logicalName;
protected final BeanProperty foreignProperty;
protected final int position;
public ImportedIdSimple(BeanPropertyAssoc<?> owner, String localDbColumn, BeanProperty foreignProperty, int position) {
this.owner = owner;
this.localDbColumn = InternString.intern(localDbColumn);
this.foreignProperty = foreignProperty;
this.position = position;
this.logicalName = InternString.intern(owner.getName()+"."+foreignProperty.getName());
}
/**
* Return the list as an array sorted into the same order as the Bean Properties.
*/
public static ImportedIdSimple[] sort(List<ImportedIdSimple> list) {
ImportedIdSimple[] importedIds = (ImportedIdSimple[]) list.toArray(new ImportedIdSimple[list.size()]);
// sort into the same order as the BeanProperties
Arrays.sort(importedIds, COMPARATOR);
return importedIds;
}
@Override
public boolean equals(Object obj) {
// remove FindBugs warning
return obj == this;
}
public int compareTo(ImportedIdSimple other) {
return (position < other.position ? -1 : (position == other.position ? 0 : 1));
}
public void addFkeys(String name) {
BeanFkeyProperty fkey = new BeanFkeyProperty(null, name+"."+foreignProperty.getName(), localDbColumn, owner.getDeployOrder());
owner.getBeanDescriptor().add(fkey);
}
public boolean isScalar(){
return true;
}
public String getLogicalName() {
return logicalName;
}
public String getDbColumn(){
return localDbColumn;
}
private Object getIdValue(Object bean) {
return foreignProperty.getValueWithInheritance(bean);
}
public void buildImport(IntersectionRow row, Object other){
Object value = getIdValue(other);
if (value == null){
String msg = "Foreign Key value null?";
throw new PersistenceException(msg);
}
row.put(localDbColumn, value);
}
public void sqlAppend(DbSqlContext ctx) {
ctx.appendColumn(localDbColumn);
}
public void dmlAppend(GenerateDmlRequest request) {
request.appendColumn(localDbColumn);
}
public void dmlWhere(GenerateDmlRequest request, Object bean){
if (owner.isDbUpdatable()){
Object value = null;
if (bean != null){
value = getIdValue(bean);
}
if (value == null){
request.appendColumnIsNull(localDbColumn);
} else {
request.appendColumn(localDbColumn);
}
}
}
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 {
Object value = null;
if (bean != null){
value = getIdValue(bean);
}
request.bind(value, foreignProperty, localDbColumn, bindNull);
return value;
}
public BeanProperty findMatchImport(String matchDbColumn) {
if (matchDbColumn.equals(localDbColumn)) {
return foreignProperty;
}
return null;
}
}
@@ -0,0 +1,10 @@
<HTML>
<HEAD>
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
<TITLE>Helpers for Id property conversion</TITLE>
</HEAD>
<Body BGCOLOR="#ffffff">
Helpers for Id property conversion
</Body>
</HTML>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,61 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.meta;
import java.util.HashMap;
import java.util.Map;
/**
* Collects Deployment information on Embedded beans.
* <p>
* Typically collects the overridden column names mapped
* to the Embedded bean.
* </p>
*/
public class DeployBeanEmbedded {
/**
* A map of property names to dbColumns.
*/
Map<String,String> propMap = new HashMap<String, String>();
/**
* Set a property name to use a specific dbColumn.
*/
public void put(String propertyName, String dbCoumn){
propMap.put(propertyName, dbCoumn);
}
/**
* Set a Map of property names to dbColumns.
*/
public void putAll(Map<String,String> propertyColumnMap){
propMap.putAll(propertyColumnMap);
}
/**
* Return a map of property names to dbColumns.
*/
public Map<String, String> getPropertyColumnMap() {
return propMap;
}
}
@@ -0,0 +1,965 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.meta;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.persistence.EmbeddedId;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.Version;
import com.avaje.ebean.annotation.CreatedTimestamp;
import com.avaje.ebean.annotation.UpdatedTimestamp;
import com.avaje.ebean.config.ScalarTypeConverter;
import com.avaje.ebean.config.dbplatform.DbEncrypt;
import com.avaje.ebean.config.dbplatform.DbEncryptFunction;
import com.avaje.ebean.config.ldap.LdapAttributeAdapter;
import com.avaje.ebean.validation.factory.Validator;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor.EntityType;
import com.avaje.ebeaninternal.server.deploy.generatedproperty.GeneratedProperty;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
import com.avaje.ebeaninternal.server.reflect.BeanReflectGetter;
import com.avaje.ebeaninternal.server.reflect.BeanReflectSetter;
import com.avaje.ebeaninternal.server.type.ScalarType;
import com.avaje.ebeaninternal.server.type.ScalarTypeEnum;
import com.avaje.ebeaninternal.server.type.ScalarTypeWrapper;
/**
* Description of a property of a bean. Includes its deployment information such
* as database column mapping information.
*/
public class DeployBeanProperty {
private static final int ID_ORDER = 1000000;
private static final int UNIDIRECTIONAL_ORDER = 100000;
private static final int AUDITCOLUMN_ORDER = -1000000;
private static final int VERSIONCOLUMN_ORDER = -1000000;
/**
* Advanced bean deployment. To exclude this property from update where
* clause.
*/
public static final String EXCLUDE_FROM_UPDATE_WHERE = "EXCLUDE_FROM_UPDATE_WHERE";
/**
* Advanced bean deployment. To exclude this property from delete where
* clause.
*/
public static final String EXCLUDE_FROM_DELETE_WHERE = "EXCLUDE_FROM_DELETE_WHERE";
/**
* Advanced bean deployment. To exclude this property from insert.
*/
public static final String EXCLUDE_FROM_INSERT = "EXCLUDE_FROM_INSERT";
/**
* Advanced bean deployment. To exclude this property from update set
* clause.
*/
public static final String EXCLUDE_FROM_UPDATE = "EXCLUDE_FROM_UPDATE";
/**
* Flag to mark this at part of the unique id.
*/
private boolean id;
/**
* Flag to mark the property as embedded. This could be on
* BeanPropertyAssocOne rather than here. Put it here for checking Id type
* (embedded or not).
*/
private boolean embedded;
/**
* Flag indicating if this the version property.
*/
private boolean versionColumn;
private boolean fetchEager = true;
/**
* Set if this property is nullable.
*/
private boolean nullable = true;
private boolean unique;
private LdapAttributeAdapter ldapAttributeAdapter;
/**
* The length or precision of the DB column.
*/
private int dbLength;
private int dbScale;
private String dbColumnDefn;
private boolean isTransient;
private boolean localEncrypted;
private boolean dbEncrypted;
private DbEncryptFunction dbEncryptFunction;
private int dbEncryptedType;
private String dbBind = "?";
/**
* Is this property include in database resultSet.
*/
private boolean dbRead;
/**
* Include this in DB insert.
*/
private boolean dbInsertable;
/**
* Include this in a DB update.
*/
private boolean dbUpdateable;
private DeployTableJoin secondaryTableJoin;
private String secondaryTableJoinPrefix;
/**
* Set to true if this property is based on a secondary table.
*/
private String secondaryTable;
/**
* The type that owns this property.
*/
private Class<?> owningType;
/**
* True if the property is a Clob, Blob LongVarchar or LongVarbinary.
*/
private boolean lob;
private boolean naturalKey;
/**
* The logical bean property name.
*/
private String name;
/**
* The reflected field.
*/
private Field field;
/**
* The bean type.
*/
private Class<?> propertyType;
/**
* Set for Non-JDBC types to provide logical to db type conversion.
*/
private ScalarType<?> scalarType;
/**
* The database column. This can include quoted identifiers.
*/
private String dbColumn;
private String sqlFormulaSelect;
private String sqlFormulaJoin;
/**
* The jdbc data type this maps to.
*/
private int dbType;
/**
* The default value to insert if null.
*/
private Object defaultValue;
/**
* Extra deployment parameters.
*/
private HashMap<String, String> extraAttributeMap = new HashMap<String, String>();
/**
* The method used to read the property.
*/
private Method readMethod;
/**
* The method used to write the property.
*/
private Method writeMethod;
private BeanReflectGetter getter;
private BeanReflectSetter setter;
/**
* Generator for insert or update timestamp etc.
*/
private GeneratedProperty generatedProperty;
private List<Validator> validators = new ArrayList<Validator>();
private final DeployBeanDescriptor<?> desc;
private boolean undirectionalShadow;
private int sortOrder;
public DeployBeanProperty(DeployBeanDescriptor<?> desc, Class<?> propertyType, ScalarType<?> scalarType, ScalarTypeConverter<?, ?> typeConverter) {
this.desc = desc;
this.propertyType = propertyType;
this.scalarType = wrapScalarType(propertyType, scalarType, typeConverter);
}
/**
* Wrap the ScalarType using a ScalarTypeConverter.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private ScalarType<?> wrapScalarType(Class<?> propertyType, ScalarType<?> scalarType, ScalarTypeConverter<?, ?> typeConverter) {
if (typeConverter == null){
return scalarType;
}
return new ScalarTypeWrapper(propertyType, scalarType, typeConverter);
}
public int getSortOverride() {
if (field == null) {
return 0;
}
if (field.getAnnotation(Id.class) != null) {
return ID_ORDER;
} else if (field.getAnnotation(EmbeddedId.class) != null) {
return ID_ORDER;
} else if (undirectionalShadow){
return UNIDIRECTIONAL_ORDER;
} else if (field.getAnnotation(CreatedTimestamp.class) != null) {
return AUDITCOLUMN_ORDER;
} else if (field.getAnnotation(UpdatedTimestamp.class) != null) {
return AUDITCOLUMN_ORDER;
} else if (field.getAnnotation(Version.class) != null) {
return VERSIONCOLUMN_ORDER;
}
return 0;
}
/**
* Return true is this is a simple scalar property.
*/
public boolean isScalar() {
return true;
}
public String getFullBeanName() {
return desc.getFullName() + "." + name;
}
/**
* Return true if this is a primitive type with a nullable DB column.
* <p>
* This should log a WARNING as primitive types can't be null.
* </p>
*/
public boolean isNullablePrimitive() {
if (nullable && propertyType.isPrimitive()) {
return true;
}
return false;
}
/**
* Return the DB column length for character columns.
* <p>
* Note if there is no length explicitly defined then the scalarType is
* checked to see if that has one (primarily to support putting a length on
* Enum types).
* </p>
*/
public int getDbLength() {
if (dbLength == 0 && scalarType != null) {
return scalarType.getLength();
}
return dbLength;
}
/**
* Return the sortOrder for the properties.
*/
public int getSortOrder() {
return sortOrder;
}
/**
* Set the sortOrder for the properties.
*/
public void setSortOrder(int sortOrder) {
this.sortOrder = sortOrder;
}
/**
* Return true if this is a placeholder property for a unidirectional relationship.
*/
public boolean isUndirectionalShadow() {
return undirectionalShadow;
}
/**
* Mark this property as a placeholder for a unidirectional relationship.
*/
public void setUndirectionalShadow(boolean undirectionalShadow) {
this.undirectionalShadow = undirectionalShadow;
}
/**
* Return true if the property is encrypted in java rather than in the DB.
*/
public boolean isLocalEncrypted() {
return localEncrypted;
}
/**
* Set to true when the property is encrypted in java rather than in the DB.
*/
public void setLocalEncrypted(boolean localEncrypted) {
this.localEncrypted = localEncrypted;
}
/**
* Set the DB column length for character columns.
*/
public void setDbLength(int dbLength) {
this.dbLength = dbLength;
}
/**
* Return the Db scale for numeric columns.
*/
public int getDbScale() {
return dbScale;
}
/**
* Set the Db scale for numeric columns.
*/
public void setDbScale(int dbScale) {
this.dbScale = dbScale;
}
/**
* Return the DB column definition if defined.
*/
public String getDbColumnDefn() {
return dbColumnDefn;
}
/**
* Set a specific DB column definition.
*/
public void setDbColumnDefn(String dbColumnDefn) {
if (dbColumnDefn == null || dbColumnDefn.trim().length() == 0) {
this.dbColumnDefn = null;
} else {
this.dbColumnDefn = InternString.intern(dbColumnDefn);
}
}
public String getDbConstraintExpression() {
if (scalarType instanceof ScalarTypeEnum) {
// create a check constraint for the enum
ScalarTypeEnum etype = (ScalarTypeEnum) scalarType;
// check dbColName IN ('A', 'I', 'D')
return "check (" + dbColumn + " in " + etype.getContraintInValues() + ")";
}
return null;
}
/**
* Add a validator to this property.
*/
public void addValidator(Validator validator) {
validators.add(validator);
}
/**
* Return true if the property contains a validator of a given type.
* <p>
* Used to detect if a validator has already been assigned when trying to
* automatically add validators such as Length and NotNull.
* </p>
*/
public boolean containsValidatorType(Class<?> type) {
Iterator<Validator> it = validators.iterator();
while (it.hasNext()) {
Validator validator = (Validator) it.next();
if (validator.getClass().equals(type)) {
return true;
}
}
return false;
}
/**
* Return the validators for this property.
*/
public Validator[] getValidators() {
return validators.toArray(new Validator[validators.size()]);
}
/**
* Return the scalarType. This returns null for native JDBC types, otherwise
* it is used to convert between logical types and jdbc types.
*/
public ScalarType<?> getScalarType() {
return scalarType;
}
public void setScalarType(ScalarType<?> scalarType) {
this.scalarType = scalarType;
}
public BeanReflectGetter getGetter() {
return getter;
}
public BeanReflectSetter getSetter() {
return setter;
}
/**
* Return the getter method.
*/
public Method getReadMethod() {
return readMethod;
}
/**
* Return the setter method.
*/
public Method getWriteMethod() {
return writeMethod;
}
/**
* Set to the owning type form a Inheritance heirarchy.
*/
public void setOwningType(Class<?> owningType) {
this.owningType = owningType;
}
public Class<?> getOwningType() {
return owningType;
}
/**
* Return true if this is local to this type - aka not from a super type.
*/
public boolean isLocal() {
return owningType == null || owningType.equals(desc.getBeanType());
}
/**
* Set the getter used to read the property value from a bean.
*/
public void setGetter(BeanReflectGetter getter) {
this.getter = getter;
}
/**
* Set the setter used to set the property value to a bean.
*/
public void setSetter(BeanReflectSetter setter) {
this.setter = setter;
}
/**
* Return the name of the property.
*/
public String getName() {
return name;
}
/**
* Set the name of the property.
*/
public void setName(String name) {
this.name = InternString.intern(name);
}
/**
* Return the bean Field associated with this property.
*/
public Field getField() {
return field;
}
/**
* Set the bean Field associated with this property.
*/
public void setField(Field field) {
this.field = field;
}
public boolean isNaturalKey() {
return naturalKey;
}
public void setNaturalKey(boolean naturalKey) {
this.naturalKey = naturalKey;
}
/**
* Return true if this is a generated property like update timestamp and
* create timestamp.
*/
public boolean isGenerated() {
return generatedProperty != null;
}
/**
* Return the GeneratedValue. Used to generate update timestamp etc.
*/
public GeneratedProperty getGeneratedProperty() {
return generatedProperty;
}
/**
* Set the GeneratedValue. Used to generate update timestamp etc.
*/
public void setGeneratedProperty(GeneratedProperty generatedValue) {
this.generatedProperty = generatedValue;
}
/**
* Return true if this property is mandatory.
*/
public boolean isNullable() {
return nullable;
}
/**
* Set the not nullable of this property.
*/
public void setNullable(boolean isNullable) {
this.nullable = isNullable;
}
/**
* Return true if the DB column is unique.
*/
public boolean isUnique() {
return unique;
}
/**
* Set to true if the DB column is unique.
*/
public void setUnique(boolean unique) {
this.unique = unique;
}
/**
* Return the LdapAttributeAdapter.
*/
public LdapAttributeAdapter getLdapAttributeAdapter() {
return ldapAttributeAdapter;
}
/**
* Set the LdapAttributeAdapter.
*/
public void setLdapAttributeAdapter(LdapAttributeAdapter ldapAttributeAdapter) {
this.ldapAttributeAdapter = ldapAttributeAdapter;
}
/**
* Return true if this is a version column used for concurrency checking.
*/
public boolean isVersionColumn() {
return versionColumn;
}
/**
* Set if this is a version column used for concurrency checking.
*/
public void setVersionColumn(boolean isVersionColumn) {
this.versionColumn = isVersionColumn;
}
/**
* Return true if this should be eager fetched by default.
*/
public boolean isFetchEager() {
return fetchEager;
}
/**
* Set the default fetch type for this property.
*/
public void setFetchType(FetchType fetchType) {
this.fetchEager = FetchType.EAGER.equals(fetchType);
}
/**
* Return the formula this property is based on.
*/
public String getSqlFormulaSelect() {
return sqlFormulaSelect;
}
public String getSqlFormulaJoin() {
return sqlFormulaJoin;
}
/**
* The property is based on a formula.
*/
public void setSqlFormula(String formulaSelect, String formulaJoin) {
this.sqlFormulaSelect = formulaSelect;
this.sqlFormulaJoin = formulaJoin.equals("") ? null : formulaJoin;
this.dbRead = true;
this.dbInsertable = false;
this.dbUpdateable = false;
}
public String getElPlaceHolder(EntityType et) {
if (sqlFormulaSelect != null) {
return sqlFormulaSelect;
} else if (EntityType.LDAP.equals(et)){
return getDbColumn();
} else {
if (secondaryTableJoinPrefix != null){
return "${"+secondaryTableJoinPrefix+"}"+getDbColumn();
}
// prepend table alias placeholder
return ElPropertyValue.ROOT_ELPREFIX + getDbColumn();
}
}
/**
* The database column name this is mapped to.
*/
public String getDbColumn() {
if (sqlFormulaSelect != null) {
return sqlFormulaSelect;
}
return dbColumn;
}
/**
* Set the database column name this is mapped to.
*/
public void setDbColumn(String dbColumn) {
this.dbColumn = InternString.intern(dbColumn);
}
/**
* Return the database jdbc data type this is mapped to.
*/
public int getDbType() {
return dbType;
}
/**
* Set the database jdbc data type this is mapped to.
*/
public void setDbType(int dbType) {
this.dbType = dbType;
this.lob = isLobType(dbType);
}
/**
* Return true if this is mapped to a Clob Blob LongVarchar or
* LongVarbinary.
*/
public boolean isLob() {
return lob;
}
private boolean isLobType(int type) {
switch (type) {
case Types.CLOB:
return true;
case Types.BLOB:
return true;
case Types.LONGVARBINARY:
return true;
case Types.LONGVARCHAR:
return true;
default:
return false;
}
}
/**
* Return true if this property is based on a secondary table.
*/
public boolean isSecondaryTable() {
return secondaryTable != null;
}
/**
* Return the secondary table this property is associated with.
*/
public String getSecondaryTable() {
return secondaryTable;
}
/**
* Set to true if this property is included in persisting.
*/
public void setSecondaryTable(String secondaryTable) {
this.secondaryTable = secondaryTable;
this.dbInsertable = false;
this.dbUpdateable = false;
}
/**
*
*/
public String getSecondaryTableJoinPrefix() {
return secondaryTableJoinPrefix;
}
public DeployTableJoin getSecondaryTableJoin() {
return secondaryTableJoin;
}
public void setSecondaryTableJoin(DeployTableJoin secondaryTableJoin, String prefix) {
this.secondaryTableJoin = secondaryTableJoin;
this.secondaryTableJoinPrefix = prefix;
}
/**
* Return the DB Bind parameter. Typically is "?" but can be different for
* encrypted bind.
*/
public String getDbBind() {
return dbBind;
}
/**
* Set the DB bind parameter (if different from "?").
*/
public void setDbBind(String dbBind) {
this.dbBind = dbBind;
}
/**
* Return true if this property is encrypted in the DB.
*/
public boolean isDbEncrypted() {
return dbEncrypted;
}
// /**
// * Set true if this property should be encrypted in the DB.
// */
// public void setDbEncrypted(boolean dbEncrypted) {
// this.dbEncrypted = dbEncrypted;
// }
public DbEncryptFunction getDbEncryptFunction() {
return dbEncryptFunction;
}
public void setDbEncryptFunction(DbEncryptFunction dbEncryptFunction, DbEncrypt dbEncrypt, int dbLen) {
this.dbEncryptFunction = dbEncryptFunction;
this.dbEncrypted = true;
this.dbBind = dbEncryptFunction.getEncryptBindSql();
this.dbEncryptedType = isLob() ? Types.BLOB : dbEncrypt.getEncryptDbType();
if (dbLen > 0){
setDbLength(dbLen);
}
}
/**
* Return the DB type for the encrypted property. This can differ from the
* logical type (String encrypted and stored in a VARBINARY)
*/
public int getDbEncryptedType() {
return dbEncryptedType;
}
/**
* Set the DB type used to store the encrypted value.
*/
public void setDbEncryptedType(int dbEncryptedType) {
this.dbEncryptedType = dbEncryptedType;
}
/**
* Return true if this property is included in database queries.
*/
public boolean isDbRead() {
return dbRead;
}
/**
* Set to true if this property is included in database queries.
*/
public void setDbRead(boolean isDBRead) {
this.dbRead = isDBRead;
}
public boolean isDbInsertable() {
return dbInsertable;
}
public void setDbInsertable(boolean insertable) {
this.dbInsertable = insertable;
}
public boolean isDbUpdateable() {
return dbUpdateable;
}
public void setDbUpdateable(boolean updateable) {
this.dbUpdateable = updateable;
}
/**
* Return true if the property is transient.
*/
public boolean isTransient() {
return isTransient;
}
/**
* Mark the property explicitly as a transient property.
*/
public void setTransient(boolean isTransient) {
this.isTransient = isTransient;
}
/**
* Set the bean read method.
* <p>
* NB: That a BeanReflectGetter is used to actually perform the getting of
* property values from a bean. This is due to performance considerations.
* </p>
*/
public void setReadMethod(Method readMethod) {
this.readMethod = readMethod;
}
/**
* Set the bean write method.
* <p>
* NB: That a BeanReflectSetter is used to actually perform the setting of
* property values to a bean. This is due to performance considerations.
* </p>
*/
public void setWriteMethod(Method writeMethod) {
this.writeMethod = writeMethod;
}
/**
* Return the property type.
*/
public Class<?> getPropertyType() {
return propertyType;
}
/**
* Return true if this is included in the unique id.
*/
public boolean isId() {
return id;
}
/**
* Set to true if this is included in the unique id.
*/
public void setId(boolean id) {
this.id = id;
}
/**
* Return true if this is an Embedded property. In this case it shares the
* table and pk of its owner object.
*/
public boolean isEmbedded() {
return embedded;
}
/**
* Set to true if this is an embedded property.
*/
public void setEmbedded(boolean embedded) {
this.embedded = embedded;
}
public Map<String, String> getExtraAttributeMap() {
return extraAttributeMap;
}
/**
* Return an extra attribute set on this property.
*/
public String getExtraAttribute(String key) {
return (String) extraAttributeMap.get(key);
}
/**
* Set an extra attribute set on this property.
*/
public void setExtraAttribute(String key, String value) {
extraAttributeMap.put(key, value);
}
/**
* Return the default value.
*/
public Object getDefaultValue() {
return defaultValue;
}
/**
* Set the default value. Inserted if the value is null.
*/
public void setDefaultValue(Object defaultValue) {
this.defaultValue = defaultValue;
}
public String toString() {
return desc.getFullName() + "." + name;
}
}
@@ -0,0 +1,175 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This file is part of Ebean.
*
* Ebean is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Ebean is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.deploy.meta;
import com.avaje.ebeaninternal.server.deploy.BeanCascadeInfo;
import com.avaje.ebeaninternal.server.deploy.BeanTable;
/**
* Abstract base for properties mapped to an associated bean, list, set or map.
*/
public abstract class DeployBeanPropertyAssoc<T> extends DeployBeanProperty {
/**
* The type of the joined bean.
*/
Class<T> targetType;
/**
* Persist settings.
*/
BeanCascadeInfo cascadeInfo = new BeanCascadeInfo();
/**
* The join table information.
*/
BeanTable beanTable;
/**
* Join between the beans.
*/
DeployTableJoin tableJoin = new DeployTableJoin();
/**
* Whether the associated join type should be an outer join.
*/
boolean isOuterJoin = false;
/**
* Literal added to where clause of lazy loading query.
*/
String extraWhere;
/**
* From the deployment mappedBy attribute.
*/
String mappedBy;
/**
* Construct the property.
*/
public DeployBeanPropertyAssoc(DeployBeanDescriptor<?> desc, Class<T> targetType) {
super(desc, targetType, null, null);
this.targetType = targetType;
}
/**
* Return false.
*/
@Override
public boolean isScalar() {
return false;
}
/**
* Return the type of the target.
* <p>
* This is the class of the associated bean, or beans contained in a list,
* set or map.
* </p>
*/
public Class<T> getTargetType() {
return targetType;
}
/**
* Return if this association should use an Outer join.
*/
public boolean isOuterJoin() {
return isOuterJoin;
}
/**
* Specify that this bean should use an outer join.
*/
public void setOuterJoin(boolean isOuterJoin) {
this.isOuterJoin = isOuterJoin;
}
/**
* Return a literal expression that is added to the query that lazy loads
* the collection.
*/
public String getExtraWhere() {
return extraWhere;
}
/**
* Set a literal expression to add to the query that lazy loads the
* collection.
*/
public void setExtraWhere(String extraWhere) {
this.extraWhere = extraWhere;
}
/**
* return the join to use for the bean.
*/
public DeployTableJoin getTableJoin() {
return tableJoin;
}
/**
* Return the BeanTable for this association.
* <p>
* This has the table name which is used to determine the relationship for
* this association.
* </p>
*/
public BeanTable getBeanTable() {
return beanTable;
}
/**
* Set the bean table.
*/
public void setBeanTable(BeanTable beanTable) {
this.beanTable = beanTable;
getTableJoin().setTable(beanTable.getBaseTable());
}
/**
* Get the persist info.
*/
public BeanCascadeInfo getCascadeInfo() {
return cascadeInfo;
}
/**
* Return the mappedBy deployment attribute.
* <p>
* This is the name of the property in the 'detail' bean that maps back to
* this 'master' bean.
* </p>
*/
public String getMappedBy() {
return mappedBy;
}
/**
* Set mappedBy deployment attribute.
*/
public void setMappedBy(String mappedBy) {
if (!"".equals(mappedBy)) {
this.mappedBy = mappedBy;
}
}
}
Loaded 100 of 1188 files, more files were not shown because too many files have changed in this diff. Show more