Organise imports

This commit is contained in:
rbygrave
2012-10-02 13:34:30 +13:00
parent 902990e159
commit 21d63c7424
83 changed files with 5188 additions and 5156 deletions
@@ -1,5 +1,8 @@
package com.avaje.ebeaninternal.api;
import java.util.ArrayList;
import java.util.List;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.OrderBy;
import com.avaje.ebean.Query;
@@ -18,9 +21,6 @@ import com.avaje.ebeaninternal.server.querydefn.NaturalKeyBindParam;
import com.avaje.ebeaninternal.server.querydefn.OrmQueryDetail;
import com.avaje.ebeaninternal.server.querydefn.OrmQueryProperties;
import java.util.ArrayList;
import java.util.List;
/**
* Object Relational query - Internal extension to Query object.
*/
@@ -1,97 +1,97 @@
package com.avaje.ebeaninternal.server.autofetch;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.resource.ResourceManager;
public class AutoFetchManagerFactory {
private static final Logger logger = Logger.getLogger(AutoFetchManagerFactory.class.getName());
public static AutoFetchManager create(SpiEbeanServer server, ServerConfig serverConfig, ResourceManager resourceManager) {
AutoFetchManagerFactory me = new AutoFetchManagerFactory();
return me.createAutoFetchManager(server, serverConfig, resourceManager);
}
private AutoFetchManager createAutoFetchManager(SpiEbeanServer server, ServerConfig serverConfig, ResourceManager resourceManager){
AutoFetchManager manager = createAutoFetchManager(server.getName(), resourceManager);
manager.setOwner(server, serverConfig);
return manager;
}
private AutoFetchManager createAutoFetchManager(String serverName, ResourceManager resourceManager) {
File autoFetchFile = getAutoFetchFile(serverName, resourceManager);
AutoFetchManager autoFetchManager = null;
boolean readFile = GlobalProperties.getBoolean("autofetch.readfromfile", true);
if (readFile) {
autoFetchManager = deserializeAutoFetch(autoFetchFile);
}
if (autoFetchManager == null) {
// not deserialized from file so create as empty
// It will be populated automatically by querying the
// database meta data
autoFetchManager = new DefaultAutoFetchManager(autoFetchFile.getAbsolutePath());
}
return autoFetchManager;
}
private AutoFetchManager deserializeAutoFetch(File autoFetchFile) {
try {
if (!autoFetchFile.exists()) {
return null;
}
FileInputStream fi = new FileInputStream(autoFetchFile);
ObjectInputStream ois = new ObjectInputStream(fi);
AutoFetchManager profListener = (AutoFetchManager) ois.readObject();
logger.info("AutoFetch deserialized from file ["+autoFetchFile.getAbsolutePath()+"]");
return profListener;
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error loading autofetch file "+autoFetchFile.getAbsolutePath(), ex);
return null;
}
}
/**
* Return the file name of the autoFetch meta data.
*/
private File getAutoFetchFile(String serverName, ResourceManager resourceManager) {
String fileName = ".ebean."+serverName+".autofetch";
File dir = resourceManager.getAutofetchDirectory();
if (!dir.exists()) {
// automatically create the directory if it does not exist.
// this is probably a fairly reasonable thing to do
if (!dir.mkdirs()) {
String m = "Unable to create directory [" + dir + "] for autofetch file ["+ fileName + "]";
throw new PersistenceException(m);
}
}
return new File(dir, fileName);
}
}
package com.avaje.ebeaninternal.server.autofetch;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.resource.ResourceManager;
public class AutoFetchManagerFactory {
private static final Logger logger = Logger.getLogger(AutoFetchManagerFactory.class.getName());
public static AutoFetchManager create(SpiEbeanServer server, ServerConfig serverConfig, ResourceManager resourceManager) {
AutoFetchManagerFactory me = new AutoFetchManagerFactory();
return me.createAutoFetchManager(server, serverConfig, resourceManager);
}
private AutoFetchManager createAutoFetchManager(SpiEbeanServer server, ServerConfig serverConfig, ResourceManager resourceManager){
AutoFetchManager manager = createAutoFetchManager(server.getName(), resourceManager);
manager.setOwner(server, serverConfig);
return manager;
}
private AutoFetchManager createAutoFetchManager(String serverName, ResourceManager resourceManager) {
File autoFetchFile = getAutoFetchFile(serverName, resourceManager);
AutoFetchManager autoFetchManager = null;
boolean readFile = GlobalProperties.getBoolean("autofetch.readfromfile", true);
if (readFile) {
autoFetchManager = deserializeAutoFetch(autoFetchFile);
}
if (autoFetchManager == null) {
// not deserialized from file so create as empty
// It will be populated automatically by querying the
// database meta data
autoFetchManager = new DefaultAutoFetchManager(autoFetchFile.getAbsolutePath());
}
return autoFetchManager;
}
private AutoFetchManager deserializeAutoFetch(File autoFetchFile) {
try {
if (!autoFetchFile.exists()) {
return null;
}
FileInputStream fi = new FileInputStream(autoFetchFile);
ObjectInputStream ois = new ObjectInputStream(fi);
AutoFetchManager profListener = (AutoFetchManager) ois.readObject();
logger.info("AutoFetch deserialized from file ["+autoFetchFile.getAbsolutePath()+"]");
return profListener;
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error loading autofetch file "+autoFetchFile.getAbsolutePath(), ex);
return null;
}
}
/**
* Return the file name of the autoFetch meta data.
*/
private File getAutoFetchFile(String serverName, ResourceManager resourceManager) {
String fileName = ".ebean."+serverName+".autofetch";
File dir = resourceManager.getAutofetchDirectory();
if (!dir.exists()) {
// automatically create the directory if it does not exist.
// this is probably a fairly reasonable thing to do
if (!dir.mkdirs()) {
String m = "Unable to create directory [" + dir + "] for autofetch file ["+ fileName + "]";
throw new PersistenceException(m);
}
}
return new File(dir, fileName);
}
}
@@ -1,112 +1,111 @@
package com.avaje.ebeaninternal.server.autofetch;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebean.config.AutofetchConfig;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebeaninternal.server.lib.BackgroundThread;
import com.avaje.ebeaninternal.server.querydefn.OrmQueryDetail;
import com.avaje.ebeaninternal.server.transaction.log.SimpleLogger;
/**
* Handles the logging aspects for the DefaultAutoFetchListener.
* <p>
* Note that java util logging loggers generally should not be serialised and
* that is one of the main reasons for pulling out the logging to this class.
* </p>
*/
public class DefaultAutoFetchManagerLogging {
private static final Logger logger = Logger.getLogger(DefaultAutoFetchManagerLogging.class.getName());
private final SimpleLogger fileLogger;
private final DefaultAutoFetchManager manager;
private final boolean useFileLogger;
private final boolean traceUsageCollection;
public DefaultAutoFetchManagerLogging(ServerConfig serverConfig, DefaultAutoFetchManager profileListener) {
this.manager = profileListener;
AutofetchConfig autofetchConfig = serverConfig.getAutofetchConfig();
traceUsageCollection = GlobalProperties.getBoolean("ebean.autofetch.traceUsageCollection", false);
useFileLogger = autofetchConfig.isUseFileLogging();
if (!useFileLogger) {
fileLogger = null;
} else {
// a separate log file just like the transaction logging
// for putting the profiling log messages. The benefit is that
// this doesn't pollute the main log with heaps of messages.
String baseDir = serverConfig.getLoggingDirectoryWithEval();
fileLogger = new SimpleLogger(baseDir, "autofetch", true, "csv");
}
int updateFreqInSecs = autofetchConfig.getProfileUpdateFrequency();
BackgroundThread.add(updateFreqInSecs, new UpdateProfile());
}
private final class UpdateProfile implements Runnable {
public void run() {
manager.updateTunedQueryInfo();
}
}
public void logError(Level level, String msg, Throwable e) {
if (useFileLogger) {
String errMsg = e == null ? "" : e.getMessage();
fileLogger.log("\"Error\",\"" + msg+" "+errMsg+"\",,,,");
}
logger.log(level, msg, e);
}
public void logToJavaLogger(String msg) {
logger.info(msg);
}
public void logSummary(String summaryInfo) {
String msg = "\"Summary\",\""+summaryInfo+"\",,,,";
if (useFileLogger) {
fileLogger.log(msg);
}
logger.fine(msg);
}
public void logChanged(TunedQueryInfo tunedFetch, OrmQueryDetail newQueryDetail) {
String msg = tunedFetch.getLogOutput(newQueryDetail);
if (useFileLogger) {
fileLogger.log(msg);
} else {
logger.fine(msg);
}
}
public void logNew(TunedQueryInfo tunedFetch) {
String msg = tunedFetch.getLogOutput(null);
if (useFileLogger) {
fileLogger.log(msg);
} else {
logger.fine(msg);
}
}
public boolean isTraceUsageCollection() {
return traceUsageCollection;
}
}
package com.avaje.ebeaninternal.server.autofetch;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebean.config.AutofetchConfig;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebeaninternal.server.lib.BackgroundThread;
import com.avaje.ebeaninternal.server.querydefn.OrmQueryDetail;
import com.avaje.ebeaninternal.server.transaction.log.SimpleLogger;
/**
* Handles the logging aspects for the DefaultAutoFetchListener.
* <p>
* Note that java util logging loggers generally should not be serialised and
* that is one of the main reasons for pulling out the logging to this class.
* </p>
*/
public class DefaultAutoFetchManagerLogging {
private static final Logger logger = Logger.getLogger(DefaultAutoFetchManagerLogging.class.getName());
private final SimpleLogger fileLogger;
private final DefaultAutoFetchManager manager;
private final boolean useFileLogger;
private final boolean traceUsageCollection;
public DefaultAutoFetchManagerLogging(ServerConfig serverConfig, DefaultAutoFetchManager profileListener) {
this.manager = profileListener;
AutofetchConfig autofetchConfig = serverConfig.getAutofetchConfig();
traceUsageCollection = GlobalProperties.getBoolean("ebean.autofetch.traceUsageCollection", false);
useFileLogger = autofetchConfig.isUseFileLogging();
if (!useFileLogger) {
fileLogger = null;
} else {
// a separate log file just like the transaction logging
// for putting the profiling log messages. The benefit is that
// this doesn't pollute the main log with heaps of messages.
String baseDir = serverConfig.getLoggingDirectoryWithEval();
fileLogger = new SimpleLogger(baseDir, "autofetch", true, "csv");
}
int updateFreqInSecs = autofetchConfig.getProfileUpdateFrequency();
BackgroundThread.add(updateFreqInSecs, new UpdateProfile());
}
private final class UpdateProfile implements Runnable {
public void run() {
manager.updateTunedQueryInfo();
}
}
public void logError(Level level, String msg, Throwable e) {
if (useFileLogger) {
String errMsg = e == null ? "" : e.getMessage();
fileLogger.log("\"Error\",\"" + msg+" "+errMsg+"\",,,,");
}
logger.log(level, msg, e);
}
public void logToJavaLogger(String msg) {
logger.info(msg);
}
public void logSummary(String summaryInfo) {
String msg = "\"Summary\",\""+summaryInfo+"\",,,,";
if (useFileLogger) {
fileLogger.log(msg);
}
logger.fine(msg);
}
public void logChanged(TunedQueryInfo tunedFetch, OrmQueryDetail newQueryDetail) {
String msg = tunedFetch.getLogOutput(newQueryDetail);
if (useFileLogger) {
fileLogger.log(msg);
} else {
logger.fine(msg);
}
}
public void logNew(TunedQueryInfo tunedFetch) {
String msg = tunedFetch.getLogOutput(null);
if (useFileLogger) {
fileLogger.log(msg);
} else {
logger.fine(msg);
}
}
public boolean isTraceUsageCollection() {
return traceUsageCollection;
}
}
@@ -7,9 +7,9 @@ import java.sql.SQLException;
import com.avaje.ebean.CallableSql;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebeaninternal.api.BindParams;
import com.avaje.ebeaninternal.api.BindParams.Param;
import com.avaje.ebeaninternal.api.SpiCallableSql;
import com.avaje.ebeaninternal.api.TransactionEventTable;
import com.avaje.ebeaninternal.api.BindParams.Param;
public class DefaultCallableSql implements Serializable, SpiCallableSql {
@@ -19,6 +19,21 @@
*/
package com.avaje.ebeaninternal.server.core;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.persistence.PersistenceException;
import javax.sql.DataSource;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.cache.ServerCacheFactory;
import com.avaje.ebean.cache.ServerCacheManager;
@@ -43,20 +58,6 @@ import com.avaje.ebeaninternal.server.lib.sql.DataSourcePool;
import com.avaje.ebeaninternal.server.lib.thread.ThreadPool;
import com.avaje.ebeaninternal.server.lib.thread.ThreadPoolManager;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.persistence.PersistenceException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Default Server side implementation of ServerFactory.
*/
@@ -6,11 +6,11 @@ import java.util.List;
import com.avaje.ebean.CallableSql;
import com.avaje.ebeaninternal.api.BindParams;
import com.avaje.ebeaninternal.api.BindParams.Param;
import com.avaje.ebeaninternal.api.SpiCallableSql;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.api.TransactionEventTable;
import com.avaje.ebeaninternal.api.BindParams.Param;
import com.avaje.ebeaninternal.server.persist.PersistExecute;
/**
@@ -9,9 +9,9 @@ import java.util.Set;
import com.avaje.ebean.config.NamingConvention;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebean.config.dbplatform.DbDdlSyntax;
import com.avaje.ebean.config.dbplatform.DbType;
import com.avaje.ebean.config.dbplatform.DbTypeMap;
import com.avaje.ebean.config.dbplatform.DbDdlSyntax;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
import com.avaje.ebeaninternal.server.type.ScalarType;
@@ -1,5 +1,9 @@
package com.avaje.ebeaninternal.server.deploy;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import com.avaje.ebean.config.ScalarTypeConverter;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanPropertyCompound;
import com.avaje.ebeaninternal.server.el.ElPropertyChainBuilder;
@@ -11,10 +15,6 @@ 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>
@@ -1,5 +1,8 @@
package com.avaje.ebeaninternal.server.deploy;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import com.avaje.ebeaninternal.server.deploy.meta.DeployTableJoin;
@@ -7,9 +10,6 @@ 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.
*/
@@ -1,455 +1,456 @@
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;
}
}
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 javax.naming.ldap.Rdn;
import javax.persistence.PersistenceException;
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;
/**
* 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;
}
}
@@ -1,461 +1,462 @@
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;
}
}
package com.avaje.ebeaninternal.server.deploy.id;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate;
import com.avaje.ebeaninternal.server.core.InternString;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.DbReadContext;
import com.avaje.ebeaninternal.server.deploy.DbSqlContext;
import com.avaje.ebeaninternal.server.lib.util.MapFromString;
import com.avaje.ebeaninternal.server.type.DataBind;
/**
* Bind an Id that is made up of multiple separate properties.
* <p>
* The id passed in for binding is expected to be a map with the key being the
* String name of the property and the value being that properties bind value.
* </p>
*/
public final class IdBinderMultiple implements IdBinder {
private final BeanProperty[] props;
private final String idProperties;
private final String idInValueSql;
public IdBinderMultiple(BeanProperty[] idProps) {
this.props = idProps;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < idProps.length; i++) {
if (i > 0){
sb.append(",");
}
sb.append(idProps[i].getName());
}
idProperties = InternString.intern(sb.toString());
sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < props.length; i++) {
if (i > 0){
sb.append(",");
}
sb.append("?");
}
sb.append(")");
idInValueSql = sb.toString();
}
public void initialise(){
// do nothing
}
public String getOrderBy(String pathPrefix, boolean ascending){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < props.length; i++) {
if (i > 0) {
sb.append(" ");
}
if (pathPrefix != null){
sb.append(pathPrefix).append(".");
}
sb.append(props[i].getName());
if (!ascending){
sb.append(" desc");
}
}
return sb.toString();
}
public void 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;
}
}
@@ -1,233 +1,234 @@
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;
}
}
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 javax.naming.ldap.Rdn;
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;
/**
* 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;
}
}
@@ -32,8 +32,8 @@ import com.avaje.ebean.annotation.LdapAttribute;
import com.avaje.ebean.annotation.LdapId;
import com.avaje.ebean.annotation.UpdatedTimestamp;
import com.avaje.ebean.config.EncryptDeploy;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebean.config.EncryptDeploy.Mode;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebean.config.dbplatform.DbEncrypt;
import com.avaje.ebean.config.dbplatform.DbEncryptFunction;
import com.avaje.ebean.config.dbplatform.IdType;
@@ -1,13 +1,13 @@
package com.avaje.ebeaninternal.server.lib.sql;
import com.avaje.ebeaninternal.jdbc.PreparedStatementDelegator;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import com.avaje.ebeaninternal.jdbc.PreparedStatementDelegator;
/**
* Implements the Statement methods for ExtendedPreparedStatement.
* <p>
@@ -1,7 +1,5 @@
package com.avaje.ebeaninternal.server.lib.sql;
import com.avaje.ebeaninternal.jdbc.ConnectionDelegator;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
@@ -16,6 +14,8 @@ import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.avaje.ebeaninternal.jdbc.ConnectionDelegator;
/**
* Is a connection that belongs to a DataSourcePool.
*
@@ -6,8 +6,6 @@ import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
/**
* Parse an xml document into a Dnode tree.
*/
@@ -11,8 +11,8 @@ import com.avaje.ebeaninternal.api.BindParams;
import com.avaje.ebeaninternal.api.SpiSqlUpdate;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.core.PersistRequestUpdateSql;
import com.avaje.ebeaninternal.server.core.PstmtBatch;
import com.avaje.ebeaninternal.server.core.PersistRequestUpdateSql.SqlType;
import com.avaje.ebeaninternal.server.core.PstmtBatch;
import com.avaje.ebeaninternal.server.type.DataBind;
import com.avaje.ebeaninternal.server.util.BindParamsParser;
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,10 @@
package com.avaje.ebeaninternal.server.query;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebean.config.dbplatform.SqlLimitResponse;
import com.avaje.ebean.config.dbplatform.SqlLimiter;
@@ -12,10 +17,6 @@ import com.avaje.ebeaninternal.server.deploy.DeployParser;
import com.avaje.ebeaninternal.server.persist.Binder;
import com.avaje.ebeaninternal.server.querydefn.OrmQueryLimitRequest;
import javax.persistence.PersistenceException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Factory for SqlSelectClause based on raw sql.
* <p>
@@ -1,5 +1,11 @@
package com.avaje.ebeaninternal.server.query;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
@@ -16,12 +22,6 @@ import com.avaje.ebeaninternal.server.deploy.TableJoin;
import com.avaje.ebeaninternal.server.deploy.id.IdBinder;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Normal bean included in the query.
*/
@@ -1,12 +1,12 @@
package com.avaje.ebeaninternal.server.text.json;
import com.avaje.ebean.text.json.JsonElement;
import com.avaje.ebean.text.json.JsonElementArray;
import com.avaje.ebean.text.json.JsonElementBoolean;
import com.avaje.ebean.text.json.JsonElementNull;
import com.avaje.ebean.text.json.JsonElementNumber;
import com.avaje.ebean.text.json.JsonElementObject;
import com.avaje.ebean.text.json.JsonElementString;
import com.avaje.ebean.text.json.JsonElement;
@@ -13,8 +13,8 @@ import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer;
import com.avaje.ebeaninternal.server.transaction.TransactionLogWriter;
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer.LogEntry;
import com.avaje.ebeaninternal.server.transaction.TransactionLogWriter;
/**
* Default transaction logger implementation.
@@ -6,8 +6,8 @@ import java.util.logging.Logger;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer;
import com.avaje.ebeaninternal.server.transaction.TransactionLogWriter;
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer.LogEntry;
import com.avaje.ebeaninternal.server.transaction.TransactionLogWriter;
/**
* A transactionLogger that uses a java.util.logging.Logger.
@@ -3,8 +3,8 @@ package com.avaje.ebeaninternal.server.type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;
import java.util.Set;
import com.avaje.ebean.config.CompoundTypeProperty;
import com.avaje.ebeaninternal.server.query.SplitName;
@@ -1,8 +1,8 @@
package com.avaje.ebeaninternal.server.type;
import com.avaje.ebean.config.Encryptor;
import com.avaje.ebean.config.EncryptKey;
import com.avaje.ebean.config.EncryptKeyManager;
import com.avaje.ebean.config.Encryptor;
public class DataEncryptSupport {
@@ -1,22 +1,22 @@
package com.avaje.ebean;
import org.junit.Assert;
import com.avaje.ebean.RawSql.Sql;
import junit.framework.TestCase;
public class TestRawSqlBuilderDistinct extends TestCase {
public void testDistinct() {
RawSqlBuilder r = RawSqlBuilder.parse("select distinct id, name from t_cust");
Sql sql = r.getSql();
Assert.assertEquals("id, name", sql.getPreFrom());
Assert.assertEquals("from t_cust", sql.getPreWhere());
Assert.assertEquals("", sql.getPreHaving());
Assert.assertNull(sql.getOrderBy());
}
}
package com.avaje.ebean;
import junit.framework.TestCase;
import org.junit.Assert;
import com.avaje.ebean.RawSql.Sql;
public class TestRawSqlBuilderDistinct extends TestCase {
public void testDistinct() {
RawSqlBuilder r = RawSqlBuilder.parse("select distinct id, name from t_cust");
Sql sql = r.getSql();
Assert.assertEquals("id, name", sql.getPreFrom());
Assert.assertEquals("from t_cust", sql.getPreWhere());
Assert.assertEquals("", sql.getPreHaving());
Assert.assertNull(sql.getOrderBy());
}
}
@@ -1,129 +1,129 @@
package com.avaje.ebean;
import java.util.Map;
import com.avaje.ebean.RawSql.ColumnMapping;
import com.avaje.ebean.RawSql.ColumnMapping.Column;
import junit.framework.TestCase;
public class TestRawSqlColumnParsing extends TestCase {
public void test_simple() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a,b,c");
Map<String, Column> mapping = columnMapping.mapping();
Column c = mapping.get("a");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a",c.getPropertyName());
c = mapping.get("b");
assertEquals("b",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b",c.getPropertyName());
c = mapping.get("c");
assertEquals("c",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c",c.getPropertyName());
}
public void test_simpleWithSpacing() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse(" a , b , c ");
Map<String, Column> mapping = columnMapping.mapping();
Column c = mapping.get("a");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a", c.getPropertyName());
c = mapping.get("b");
assertEquals("b",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b",c.getPropertyName());
c = mapping.get("c");
assertEquals("c",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c",c.getPropertyName());
}
public void test_withAlias() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a a0,b b1, c c2 , d d3 , e e4 ");
Map<String, Column> mapping = columnMapping.mapping();
assertEquals(5, mapping.size());
Column c = mapping.get("a");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0",c.getPropertyName());
c = mapping.get("b");
assertEquals("b",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1",c.getPropertyName());
c = mapping.get("c");
assertEquals("c",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c2",c.getPropertyName());
c = mapping.get("d");
assertEquals("d",c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3",c.getPropertyName());
c = mapping.get("e");
assertEquals("e",c.getDbColumn());
assertEquals(4, c.getIndexPos());
assertEquals("e4",c.getPropertyName());
}
public void test_withAsAlias() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a as a0,'b' b1, \"c(blah)\" as c2 , d as d3 , e as e4 ");
Map<String, Column> mapping = columnMapping.mapping();
assertEquals(5, mapping.size());
Column c = mapping.get("a");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0",c.getPropertyName());
c = mapping.get("'b'");
assertEquals("'b'",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1",c.getPropertyName());
c = mapping.get("\"c(blah)\"");
assertEquals("\"c(blah)\"",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c2",c.getPropertyName());
c = mapping.get("d");
assertEquals("d",c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3",c.getPropertyName());
c = mapping.get("e");
assertEquals("e",c.getDbColumn());
assertEquals(4, c.getIndexPos());
assertEquals("e4",c.getPropertyName());
}
}
package com.avaje.ebean;
import java.util.Map;
import junit.framework.TestCase;
import com.avaje.ebean.RawSql.ColumnMapping;
import com.avaje.ebean.RawSql.ColumnMapping.Column;
public class TestRawSqlColumnParsing extends TestCase {
public void test_simple() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a,b,c");
Map<String, Column> mapping = columnMapping.mapping();
Column c = mapping.get("a");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a",c.getPropertyName());
c = mapping.get("b");
assertEquals("b",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b",c.getPropertyName());
c = mapping.get("c");
assertEquals("c",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c",c.getPropertyName());
}
public void test_simpleWithSpacing() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse(" a , b , c ");
Map<String, Column> mapping = columnMapping.mapping();
Column c = mapping.get("a");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a", c.getPropertyName());
c = mapping.get("b");
assertEquals("b",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b",c.getPropertyName());
c = mapping.get("c");
assertEquals("c",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c",c.getPropertyName());
}
public void test_withAlias() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a a0,b b1, c c2 , d d3 , e e4 ");
Map<String, Column> mapping = columnMapping.mapping();
assertEquals(5, mapping.size());
Column c = mapping.get("a");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0",c.getPropertyName());
c = mapping.get("b");
assertEquals("b",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1",c.getPropertyName());
c = mapping.get("c");
assertEquals("c",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c2",c.getPropertyName());
c = mapping.get("d");
assertEquals("d",c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3",c.getPropertyName());
c = mapping.get("e");
assertEquals("e",c.getDbColumn());
assertEquals(4, c.getIndexPos());
assertEquals("e4",c.getPropertyName());
}
public void test_withAsAlias() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a as a0,'b' b1, \"c(blah)\" as c2 , d as d3 , e as e4 ");
Map<String, Column> mapping = columnMapping.mapping();
assertEquals(5, mapping.size());
Column c = mapping.get("a");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0",c.getPropertyName());
c = mapping.get("'b'");
assertEquals("'b'",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1",c.getPropertyName());
c = mapping.get("\"c(blah)\"");
assertEquals("\"c(blah)\"",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c2",c.getPropertyName());
c = mapping.get("d");
assertEquals("d",c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3",c.getPropertyName());
c = mapping.get("e");
assertEquals("e",c.getDbColumn());
assertEquals(4, c.getIndexPos());
assertEquals("e4",c.getPropertyName());
}
}
@@ -1,30 +1,28 @@
package com.avaje.ebean.text;
import junit.framework.TestCase;
import com.avaje.ebean.text.PathProperties;
public class TestPathPropertiesParse extends TestCase {
public void test() {
PathProperties s0 = PathProperties.parse("(id,name)");
assertEquals(1,s0.getPaths().size());
assertTrue(s0.get(null).contains("id"));
assertTrue(s0.get(null).contains("name"));
assertFalse(s0.get(null).contains("status"));
PathProperties s1 = PathProperties.parse(":(id,name,shipAddr(*))");
assertEquals(2,s1.getPaths().size());
assertEquals(3,s1.get(null).size());
assertTrue(s1.get(null).contains("id"));
assertTrue(s1.get(null).contains("name"));
assertTrue(s1.get(null).contains("shipAddr"));
assertTrue(s1.get("shipAddr").contains("*"));
assertEquals(1,s1.get("shipAddr").size());
}
}
package com.avaje.ebean.text;
import junit.framework.TestCase;
public class TestPathPropertiesParse extends TestCase {
public void test() {
PathProperties s0 = PathProperties.parse("(id,name)");
assertEquals(1,s0.getPaths().size());
assertTrue(s0.get(null).contains("id"));
assertTrue(s0.get(null).contains("name"));
assertFalse(s0.get(null).contains("status"));
PathProperties s1 = PathProperties.parse(":(id,name,shipAddr(*))");
assertEquals(2,s1.getPaths().size());
assertEquals(3,s1.get(null).size());
assertTrue(s1.get(null).contains("id"));
assertTrue(s1.get(null).contains("name"));
assertTrue(s1.get(null).contains("shipAddr"));
assertTrue(s1.get("shipAddr").contains("*"));
assertEquals(1,s1.get("shipAddr").size());
}
}
@@ -1,98 +1,94 @@
package com.avaje.ebeaninternal.server.querydefn;
import java.util.Set;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebeaninternal.server.expression.DefaultExpressionFactory;
import com.avaje.ebeaninternal.server.querydefn.DefaultOrmQuery;
import com.avaje.ebeaninternal.server.querydefn.OrmQueryDetail;
import com.avaje.ebeaninternal.server.querydefn.OrmQueryDetailParser;
import com.avaje.ebeaninternal.server.querydefn.OrmQueryProperties;
import com.avaje.tests.model.basic.Order;
public class TestQueryLanguage extends TestCase {
public void test() {
DefaultOrmQuery<Order> q = check("find order join customer (id, name)");
OrmQueryDetail detail = q.getDetail();
OrmQueryProperties chunk = detail.getChunk("customer", false);
Set<String> props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
q = check("find order join customer(id, name)");
detail = q.getDetail();
chunk = detail.getChunk("customer", false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
Assert.assertFalse(chunk.isCache());
Assert.assertFalse(chunk.isReadOnly());
q = check("find order join customer(+cache +readonly, id, name)");
detail = q.getDetail();
chunk = detail.getChunk("customer", false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
Assert.assertTrue(chunk.isCache());
Assert.assertTrue(chunk.isReadOnly());
q = check("find order join customer(+cache +readonly,id,name)");
detail = q.getDetail();
chunk = detail.getChunk("customer", false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
Assert.assertTrue(chunk.isCache());
Assert.assertTrue(chunk.isReadOnly());
q = check("find order(id,status) join customer(+cache +readonly,id,name)");
detail = q.getDetail();
chunk = detail.getChunk("customer", false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
Assert.assertTrue(chunk.isCache());
Assert.assertTrue(chunk.isReadOnly());
chunk = detail.getChunk(null, false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("status"));
Assert.assertFalse(props.contains("orderDate"));
q = check("find order(id,status) join customer(+cache +readonly,id,name) where id > :minId order by status");
detail = q.getDetail();
chunk = detail.getChunk("customer", false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
Assert.assertTrue(chunk.isCache());
Assert.assertTrue(chunk.isReadOnly());
String orderBy = q.getOrderBy().toStringFormat();
Assert.assertEquals("status", orderBy);
}
private DefaultOrmQuery<Order> check(String q) {
EbeanServer server = Ebean.getServer(null);
OrmQueryDetailParser p = new OrmQueryDetailParser(q);
p.parse();
DefaultOrmQuery<Order> qry = new DefaultOrmQuery<Order>(Order.class, server, new DefaultExpressionFactory(), (String)null);
p.assign(qry);
return qry;
}
}
package com.avaje.ebeaninternal.server.querydefn;
import java.util.Set;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebeaninternal.server.expression.DefaultExpressionFactory;
import com.avaje.tests.model.basic.Order;
public class TestQueryLanguage extends TestCase {
public void test() {
DefaultOrmQuery<Order> q = check("find order join customer (id, name)");
OrmQueryDetail detail = q.getDetail();
OrmQueryProperties chunk = detail.getChunk("customer", false);
Set<String> props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
q = check("find order join customer(id, name)");
detail = q.getDetail();
chunk = detail.getChunk("customer", false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
Assert.assertFalse(chunk.isCache());
Assert.assertFalse(chunk.isReadOnly());
q = check("find order join customer(+cache +readonly, id, name)");
detail = q.getDetail();
chunk = detail.getChunk("customer", false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
Assert.assertTrue(chunk.isCache());
Assert.assertTrue(chunk.isReadOnly());
q = check("find order join customer(+cache +readonly,id,name)");
detail = q.getDetail();
chunk = detail.getChunk("customer", false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
Assert.assertTrue(chunk.isCache());
Assert.assertTrue(chunk.isReadOnly());
q = check("find order(id,status) join customer(+cache +readonly,id,name)");
detail = q.getDetail();
chunk = detail.getChunk("customer", false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
Assert.assertTrue(chunk.isCache());
Assert.assertTrue(chunk.isReadOnly());
chunk = detail.getChunk(null, false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("status"));
Assert.assertFalse(props.contains("orderDate"));
q = check("find order(id,status) join customer(+cache +readonly,id,name) where id > :minId order by status");
detail = q.getDetail();
chunk = detail.getChunk("customer", false);
props = chunk.getAllIncludedProperties();
Assert.assertTrue(props.contains("id"));
Assert.assertTrue(props.contains("name"));
Assert.assertTrue(chunk.isCache());
Assert.assertTrue(chunk.isReadOnly());
String orderBy = q.getOrderBy().toStringFormat();
Assert.assertEquals("status", orderBy);
}
private DefaultOrmQuery<Order> check(String q) {
EbeanServer server = Ebean.getServer(null);
OrmQueryDetailParser p = new OrmQueryDetailParser(q);
p.parse();
DefaultOrmQuery<Order> qry = new DefaultOrmQuery<Order>(Order.class, server, new DefaultExpressionFactory(), (String)null);
p.assign(qry);
return qry;
}
}
@@ -1,31 +1,31 @@
package com.avaje.ebeaninternal.server.rawsql;
import junit.framework.TestCase;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;
import com.avaje.ebean.RawSql.Sql;
public class TestRawSqlParsing extends TestCase {
public void test() {
String sql
= " select order_id, sum(order_qty*unit_price) as totalAmount"
+ " from o_order_detail "
+ " group by order_id";
RawSql rawSql = RawSqlBuilder
.parse(sql)
.columnMapping("order_id","order.id")
//.columnMapping("sum(order_qty*unit_price)","totalAmount")
.create();
Sql rs = rawSql.getSql();
String s = rs.toString();
System.out.println(s);
assertTrue(s, s.contains("[order_id, sum"));
}
}
package com.avaje.ebeaninternal.server.rawsql;
import junit.framework.TestCase;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSql.Sql;
import com.avaje.ebean.RawSqlBuilder;
public class TestRawSqlParsing extends TestCase {
public void test() {
String sql
= " select order_id, sum(order_qty*unit_price) as totalAmount"
+ " from o_order_detail "
+ " group by order_id";
RawSql rawSql = RawSqlBuilder
.parse(sql)
.columnMapping("order_id","order.id")
//.columnMapping("sum(order_qty*unit_price)","totalAmount")
.create();
Sql rs = rawSql.getSql();
String s = rs.toString();
System.out.println(s);
assertTrue(s, s.contains("[order_id, sum"));
}
}
@@ -1,43 +1,43 @@
package com.avaje.tests.autofetch;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
import java.util.List;
public class MainAutoQueryTune1 {
public static void main(String[] args) {
//GlobalProperties.put("ebean.ddl.run", "false");
//GlobalProperties.put("ebean.ddl.generate", "false");
GlobalProperties.put("ebean.autofetch.queryTuning", "true");
// GlobalProperties.put("ebean.autofetch.queryTuningAddVersion", "true");
ResetBasicData.reset();
MainAutoQueryTune1 me = new MainAutoQueryTune1();
me.tuneJoin();
}
private void tuneJoin()
{
List<Order> list = Ebean.find(Order.class)
.setAutofetch(true)
.fetch("customer")
.where()
.eq("status", Order.Status.NEW)
.eq("customer.name", "Rob")
.order().asc("id")
.findList();
for (Order order : list)
{
System.out.println(order.getId() + " " + order.getOrderDate());
}
}
}
package com.avaje.tests.autofetch;
import java.util.List;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
public class MainAutoQueryTune1 {
public static void main(String[] args) {
//GlobalProperties.put("ebean.ddl.run", "false");
//GlobalProperties.put("ebean.ddl.generate", "false");
GlobalProperties.put("ebean.autofetch.queryTuning", "true");
// GlobalProperties.put("ebean.autofetch.queryTuningAddVersion", "true");
ResetBasicData.reset();
MainAutoQueryTune1 me = new MainAutoQueryTune1();
me.tuneJoin();
}
private void tuneJoin()
{
List<Order> list = Ebean.find(Order.class)
.setAutofetch(true)
.fetch("customer")
.where()
.eq("status", Order.Status.NEW)
.eq("customer.name", "Rob")
.order().asc("id")
.findList();
for (Order order : list)
{
System.out.println(order.getId() + " " + order.getOrderDate());
}
}
}
@@ -1,29 +1,29 @@
package com.avaje.tests.basic;
import com.avaje.ebeaninternal.server.lib.sql.DataSourcePoolListener;
import java.sql.Connection;
public class MyTestDataSourcePoolListener implements DataSourcePoolListener
{
public static int SLEEP_AFTER_BORROW = 0;
public void onAfterBorrowConnection(Connection c)
{
if (SLEEP_AFTER_BORROW > 0)
{
try
{
Thread.sleep(SLEEP_AFTER_BORROW);
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
}
public void onBeforeReturnConnection(Connection c)
{
}
}
package com.avaje.tests.basic;
import java.sql.Connection;
import com.avaje.ebeaninternal.server.lib.sql.DataSourcePoolListener;
public class MyTestDataSourcePoolListener implements DataSourcePoolListener
{
public static int SLEEP_AFTER_BORROW = 0;
public void onAfterBorrowConnection(Connection c)
{
if (SLEEP_AFTER_BORROW > 0)
{
try
{
Thread.sleep(SLEEP_AFTER_BORROW);
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
}
public void onBeforeReturnConnection(Connection c)
{
}
}
@@ -1,41 +1,42 @@
package com.avaje.tests.basic;
import com.avaje.ebean.AdminAutofetch;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.OrderDetail;
import com.avaje.tests.model.basic.ResetBasicData;
import junit.framework.TestCase;
import java.util.List;
public class TestBatchLazy extends TestCase {
public void testMe() {
ResetBasicData.reset();
Query<Order> query = Ebean.find(Order.class);
List<Order> list = query.findList();
for (Order order : list) {
Customer customer = order.getCustomer();
customer.getName();
List<OrderDetail> details = order.getDetails();
for (OrderDetail orderDetail : details) {
orderDetail.getProduct().getSku();
}
}
AdminAutofetch adminAutofetch = Ebean.getServer(null).getAdminAutofetch();
adminAutofetch.collectUsageViaGC();
}
}
package com.avaje.tests.basic;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.AdminAutofetch;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.OrderDetail;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestBatchLazy extends TestCase {
public void testMe() {
ResetBasicData.reset();
Query<Order> query = Ebean.find(Order.class);
List<Order> list = query.findList();
for (Order order : list) {
Customer customer = order.getCustomer();
customer.getName();
List<OrderDetail> details = order.getDetails();
for (OrderDetail orderDetail : details) {
orderDetail.getProduct().getSku();
}
}
AdminAutofetch adminAutofetch = Ebean.getServer(null).getAdminAutofetch();
adminAutofetch.collectUsageViaGC();
}
}
@@ -1,42 +1,42 @@
package com.avaje.tests.basic;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
import com.avaje.tests.model.basic.Order.Status;
public class TestBeanReferenceRefresh extends TestCase {
public void testMe() {
ResetBasicData.reset();
Order order = Ebean.getReference(Order.class, 1);
Assert.assertTrue("isReference",Ebean.getBeanState(order).isReference());
order.getOrderDate();
Assert.assertFalse(Ebean.getBeanState(order).isReference());
Assert.assertNotNull(order.getStatus());
Assert.assertNotNull(order.getDetails());
Assert.assertNull(Ebean.getBeanState(order).getLoadedProps());
Status status = order.getStatus();
Assert.assertTrue(status != Order.Status.SHIPPED);
order.setStatus(Order.Status.SHIPPED);
Ebean.refresh(order);
Status statusRefresh = order.getStatus();
Assert.assertEquals(status,statusRefresh);
System.out.println("done");
}
}
package com.avaje.tests.basic;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.Order.Status;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestBeanReferenceRefresh extends TestCase {
public void testMe() {
ResetBasicData.reset();
Order order = Ebean.getReference(Order.class, 1);
Assert.assertTrue("isReference",Ebean.getBeanState(order).isReference());
order.getOrderDate();
Assert.assertFalse(Ebean.getBeanState(order).isReference());
Assert.assertNotNull(order.getStatus());
Assert.assertNotNull(order.getDetails());
Assert.assertNull(Ebean.getBeanState(order).getLoadedProps());
Status status = order.getStatus();
Assert.assertTrue(status != Order.Status.SHIPPED);
order.setStatus(Order.Status.SHIPPED);
Ebean.refresh(order);
Status statusRefresh = order.getStatus();
Assert.assertEquals(status,statusRefresh);
System.out.println("done");
}
}
@@ -1,38 +1,38 @@
package com.avaje.tests.basic;
import org.junit.Assert;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.PFile;
import com.avaje.tests.model.basic.PFileContent;
import junit.framework.TestCase;
public class TestDeleteImportedPartial extends TestCase {
public void test() {
PFile persistentFile = new PFile("test.txt", new PFileContent("test".getBytes()));
Ebean.save(persistentFile);
Integer id = persistentFile.getId();
Integer contentId = persistentFile.getFileContent().getId();
PFile partialPfile = Ebean.find(PFile.class)
.select("id")
.where().idEq(persistentFile.getId())
.findUnique();
// should delete file and fileContent
Ebean.delete(partialPfile);
System.out.println("finished delete");
PFile file1 = Ebean.find(PFile.class, id);
PFileContent content1 = Ebean.find(PFileContent.class, contentId);
Assert.assertNull(file1);
Assert.assertNull(content1);
}
}
package com.avaje.tests.basic;
import junit.framework.TestCase;
import org.junit.Assert;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.PFile;
import com.avaje.tests.model.basic.PFileContent;
public class TestDeleteImportedPartial extends TestCase {
public void test() {
PFile persistentFile = new PFile("test.txt", new PFileContent("test".getBytes()));
Ebean.save(persistentFile);
Integer id = persistentFile.getId();
Integer contentId = persistentFile.getFileContent().getId();
PFile partialPfile = Ebean.find(PFile.class)
.select("id")
.where().idEq(persistentFile.getId())
.findUnique();
// should delete file and fileContent
Ebean.delete(partialPfile);
System.out.println("finished delete");
PFile file1 = Ebean.find(PFile.class, id);
PFileContent content1 = Ebean.find(PFileContent.class, contentId);
Assert.assertNull(file1);
Assert.assertNull(content1);
}
}
@@ -1,10 +1,11 @@
package com.avaje.tests.basic;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.LogLevel;
import com.avaje.tests.model.embedded.EMain;
import junit.framework.TestCase;
public class TestDynamicUpdate extends TestCase {
@@ -1,29 +1,29 @@
package com.avaje.tests.basic;
import javax.persistence.PersistenceException;
import org.junit.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.tests.model.basic.Order;
public class TestErrorBindLog extends TestCase {
public void test() {
GlobalProperties.put("somethingelse", "d:/junk2");
try {
Ebean.find(Order.class)
.where().gt("id", "JUNK")
.findList();
} catch (PersistenceException e){
String msg = e.getMessage();
e.printStackTrace();
Assert.assertTrue(msg.contains("Bind values:"));
}
}
}
package com.avaje.tests.basic;
import javax.persistence.PersistenceException;
import junit.framework.TestCase;
import org.junit.Assert;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.tests.model.basic.Order;
public class TestErrorBindLog extends TestCase {
public void test() {
GlobalProperties.put("somethingelse", "d:/junk2");
try {
Ebean.find(Order.class)
.where().gt("id", "JUNK")
.findList();
} catch (PersistenceException e){
String msg = e.getMessage();
e.printStackTrace();
Assert.assertTrue(msg.contains("Bind values:"));
}
}
}
@@ -1,59 +1,59 @@
package com.avaje.tests.basic;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.OCar;
import com.avaje.tests.model.basic.OEngine;
import com.avaje.tests.model.basic.OGearBox;
import junit.framework.TestCase;
public class TestMultipleOneToOneIUD extends TestCase {
public void test() {
OEngine engine = new OEngine();
engine.setShortDesc("engine 1");
OGearBox gearBox = new OGearBox();
gearBox.setBoxDesc("6 speed manual");
gearBox.setSize(6);
OCar car = new OCar();
car.setVin("xx4534");
car.setName("test car");
car.setEngine(engine);
Ebean.beginTransaction();
try {
Ebean.save(gearBox);
Ebean.save(car);
assertNotNull(car.getId());
assertNotNull(engine.getEngineId());
assertNotNull(gearBox.getId());
Ebean.commitTransaction();
} finally {
Ebean.endTransaction();
}
OCar c2 = Ebean.find(OCar.class, car.getId());
assertNotNull(c2);
assertNotNull(c2.getEngine());
// gearBox not assigned yet
assertNull(c2.getGearBox());
// ok, assign gearBox
c2.setGearBox(gearBox);
Ebean.save(c2);
// now all should be there...
OCar c3 = Ebean.find(OCar.class, car.getId());
assertNotNull(c3);
assertNotNull(c3.getEngine());
assertNotNull(c3.getGearBox());
}
}
package com.avaje.tests.basic;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.OCar;
import com.avaje.tests.model.basic.OEngine;
import com.avaje.tests.model.basic.OGearBox;
public class TestMultipleOneToOneIUD extends TestCase {
public void test() {
OEngine engine = new OEngine();
engine.setShortDesc("engine 1");
OGearBox gearBox = new OGearBox();
gearBox.setBoxDesc("6 speed manual");
gearBox.setSize(6);
OCar car = new OCar();
car.setVin("xx4534");
car.setName("test car");
car.setEngine(engine);
Ebean.beginTransaction();
try {
Ebean.save(gearBox);
Ebean.save(car);
assertNotNull(car.getId());
assertNotNull(engine.getEngineId());
assertNotNull(gearBox.getId());
Ebean.commitTransaction();
} finally {
Ebean.endTransaction();
}
OCar c2 = Ebean.find(OCar.class, car.getId());
assertNotNull(c2);
assertNotNull(c2.getEngine());
// gearBox not assigned yet
assertNull(c2.getGearBox());
// ok, assign gearBox
c2.setGearBox(gearBox);
Ebean.save(c2);
// now all should be there...
OCar c3 = Ebean.find(OCar.class, car.getId());
assertNotNull(c3);
assertNotNull(c3.getEngine());
assertNotNull(c3.getGearBox());
}
}
@@ -1,35 +1,36 @@
package com.avaje.tests.basic;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.util.List;
public class TestOrderByAnnotation extends TestCase {
public void testOrderBy() {
ResetBasicData.reset();
Customer custTest = ResetBasicData.createCustAndOrder("testOrderByAnn");
Customer customer = Ebean.find(Customer.class, custTest.getId());
List<Order> orders = customer.getOrders();
Assert.assertTrue(orders.size() > 0);
Query<Order> q1 = Ebean.find(Order.class)
.fetch("details");
q1.findList();
String s1 = q1.getGeneratedSql();
Assert.assertTrue(s1.contains("order by t0.id, t1.id asc, t1.order_qty asc, t1.cretime desc"));
}
package com.avaje.tests.basic;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestOrderByAnnotation extends TestCase {
public void testOrderBy() {
ResetBasicData.reset();
Customer custTest = ResetBasicData.createCustAndOrder("testOrderByAnn");
Customer customer = Ebean.find(Customer.class, custTest.getId());
List<Order> orders = customer.getOrders();
Assert.assertTrue(orders.size() > 0);
Query<Order> q1 = Ebean.find(Order.class)
.fetch("details");
q1.findList();
String s1 = q1.getGeneratedSql();
Assert.assertTrue(s1.contains("order by t0.id, t1.id asc, t1.order_qty asc, t1.cretime desc"));
}
}
@@ -1,58 +1,59 @@
package com.avaje.tests.basic;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestQuery extends TestCase
{
public void testCountOrderBy()
{
ResetBasicData.reset();
Query<Order> query = Ebean.find(Order.class)
.setAutofetch(false)
.order().asc("orderDate")
.order().desc("id");
//.orderBy("orderDate");
int rc = query.findList().size();
//int rc = query.findRowCount();
Assert.assertTrue(rc > 0);
//String generatedSql = query.getGeneratedSql();
//Assert.assertFalse(generatedSql.contains("order by"));
}
public void testForUpdate()
{
ResetBasicData.reset();
Query<Order> query = Ebean.find(Order.class)
.setAutofetch(false)
.setForUpdate(false)
.setMaxRows(1)
.order().asc("orderDate")
.order().desc("id");
int rc = query.findList().size();
Assert.assertTrue(rc > 0);
assertTrue(query.getGeneratedSql().toLowerCase().indexOf("for update") < 0);
query = Ebean.find(Order.class)
.setAutofetch(false)
.setForUpdate(true)
.setMaxRows(1)
.order().asc("orderDate")
.order().desc("id");
rc = query.findList().size();
Assert.assertTrue(rc > 0);
assertTrue(query.getGeneratedSql().toLowerCase().indexOf("for update") > -1);
}
}
package com.avaje.tests.basic;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestQuery extends TestCase
{
public void testCountOrderBy()
{
ResetBasicData.reset();
Query<Order> query = Ebean.find(Order.class)
.setAutofetch(false)
.order().asc("orderDate")
.order().desc("id");
//.orderBy("orderDate");
int rc = query.findList().size();
//int rc = query.findRowCount();
Assert.assertTrue(rc > 0);
//String generatedSql = query.getGeneratedSql();
//Assert.assertFalse(generatedSql.contains("order by"));
}
public void testForUpdate()
{
ResetBasicData.reset();
Query<Order> query = Ebean.find(Order.class)
.setAutofetch(false)
.setForUpdate(false)
.setMaxRows(1)
.order().asc("orderDate")
.order().desc("id");
int rc = query.findList().size();
Assert.assertTrue(rc > 0);
assertTrue(query.getGeneratedSql().toLowerCase().indexOf("for update") < 0);
query = Ebean.find(Order.class)
.setAutofetch(false)
.setForUpdate(true)
.setMaxRows(1)
.order().asc("orderDate")
.order().desc("id");
rc = query.findList().size();
Assert.assertTrue(rc > 0);
assertTrue(query.getGeneratedSql().toLowerCase().indexOf("for update") > -1);
}
}
@@ -1,124 +1,120 @@
package com.avaje.tests.basic;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.BeanState;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.ebean.cache.ServerCache;
import com.avaje.ebean.cache.ServerCacheManager;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.core.CacheOptions;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.tests.model.basic.Country;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestQueryWithCache extends TestCase {
// public void testJoinCache() {
//
// ResetBasicData.reset();
//
// Ebean.getServer(null).runCacheWarming();
//
// Query<Order> query = Ebean.createQuery(Order.class)
// .setAutofetch(false)
// .fetch("customer","+cache +readonly")
// .setId(1);
//
// Order order = query.findUnique();
// Customer customer = order.getCustomer();
// Assert.assertTrue(Ebean.getBeanState(customer).isReadOnly());
//
//// // invoke lazy loading
//// customer.getName();
////
//// order = query.findUnique();
//// customer = order.getCustomer();
//// custState = Ebean.getBeanState(customer);
//// Assert.assertFalse(custState.isReadOnly());
//
// }
//
// public void testFindId() {
//
// ResetBasicData.reset();
//
// Order o = Ebean.find(Order.class)
// .setUseCache(true)
// .setReadOnly(true)
// .setId(1)
// .findUnique();
//
// BeanState beanState = Ebean.getBeanState(o);
// Assert.assertTrue(beanState.isReadOnly());
//
// Order o2 = Ebean.find(Order.class)
// .setUseCache(true)
// .setReadOnly(true)
// .setId(1)
// .findUnique();
//
// BeanState beanState2 = Ebean.getBeanState(o2);
//
// // same instance as readOnly = true
// Assert.assertTrue("not same instance", o != o2);
// Assert.assertTrue(beanState2.isReadOnly());
//
// Order o3 = Ebean.find(Order.class)
// .setUseCache(true)
// .setReadOnly(false)
// .setId(1)
// .findUnique();
//
// // NOT the same instance as readOnly = false
// Assert.assertTrue("not same instance", o != o3);
// }
public void testCountryDeploy() {
ResetBasicData.reset();
SpiEbeanServer server = (SpiEbeanServer)Ebean.getServer(null);
BeanDescriptor<Country> beanDescriptor = server.getBeanDescriptor(Country.class);
CacheOptions cacheOptions = beanDescriptor.getCacheOptions();
Assert.assertNotNull(cacheOptions);
Assert.assertTrue(cacheOptions.isUseCache());
Assert.assertTrue(cacheOptions.isReadOnly());
Assert.assertTrue(beanDescriptor.isCacheSharableBeans());
ServerCacheManager serverCacheManager = server.getServerCacheManager();
serverCacheManager.clear(Country.class);
ServerCache beanCache = serverCacheManager.getBeanCache(Country.class);
Assert.assertEquals(0, beanCache.size());
Country nz1 = Ebean.getReference(Country.class, "NZ");
Assert.assertEquals(0, beanCache.size());
// has the effect of loading the cache via lazy loading
nz1.getName();
Assert.assertEquals(1, beanCache.size());
Country nz2 = Ebean.getReference(Country.class, "NZ");
Country nz2b = Ebean.getReference(Country.class, "NZ");
Country nz3 = Ebean.find(Country.class, "NZ");
Country nz4 = Ebean.find(Country.class)
.setId("NZ")
.setAutofetch(false)
.setUseCache(false)
.findUnique();
Assert.assertTrue(nz2 == nz2b);
Assert.assertTrue(nz2 == nz3);
Assert.assertTrue(nz3 != nz4);
}
}
package com.avaje.tests.basic;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.cache.ServerCache;
import com.avaje.ebean.cache.ServerCacheManager;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.core.CacheOptions;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.tests.model.basic.Country;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestQueryWithCache extends TestCase {
// public void testJoinCache() {
//
// ResetBasicData.reset();
//
// Ebean.getServer(null).runCacheWarming();
//
// Query<Order> query = Ebean.createQuery(Order.class)
// .setAutofetch(false)
// .fetch("customer","+cache +readonly")
// .setId(1);
//
// Order order = query.findUnique();
// Customer customer = order.getCustomer();
// Assert.assertTrue(Ebean.getBeanState(customer).isReadOnly());
//
//// // invoke lazy loading
//// customer.getName();
////
//// order = query.findUnique();
//// customer = order.getCustomer();
//// custState = Ebean.getBeanState(customer);
//// Assert.assertFalse(custState.isReadOnly());
//
// }
//
// public void testFindId() {
//
// ResetBasicData.reset();
//
// Order o = Ebean.find(Order.class)
// .setUseCache(true)
// .setReadOnly(true)
// .setId(1)
// .findUnique();
//
// BeanState beanState = Ebean.getBeanState(o);
// Assert.assertTrue(beanState.isReadOnly());
//
// Order o2 = Ebean.find(Order.class)
// .setUseCache(true)
// .setReadOnly(true)
// .setId(1)
// .findUnique();
//
// BeanState beanState2 = Ebean.getBeanState(o2);
//
// // same instance as readOnly = true
// Assert.assertTrue("not same instance", o != o2);
// Assert.assertTrue(beanState2.isReadOnly());
//
// Order o3 = Ebean.find(Order.class)
// .setUseCache(true)
// .setReadOnly(false)
// .setId(1)
// .findUnique();
//
// // NOT the same instance as readOnly = false
// Assert.assertTrue("not same instance", o != o3);
// }
public void testCountryDeploy() {
ResetBasicData.reset();
SpiEbeanServer server = (SpiEbeanServer)Ebean.getServer(null);
BeanDescriptor<Country> beanDescriptor = server.getBeanDescriptor(Country.class);
CacheOptions cacheOptions = beanDescriptor.getCacheOptions();
Assert.assertNotNull(cacheOptions);
Assert.assertTrue(cacheOptions.isUseCache());
Assert.assertTrue(cacheOptions.isReadOnly());
Assert.assertTrue(beanDescriptor.isCacheSharableBeans());
ServerCacheManager serverCacheManager = server.getServerCacheManager();
serverCacheManager.clear(Country.class);
ServerCache beanCache = serverCacheManager.getBeanCache(Country.class);
Assert.assertEquals(0, beanCache.size());
Country nz1 = Ebean.getReference(Country.class, "NZ");
Assert.assertEquals(0, beanCache.size());
// has the effect of loading the cache via lazy loading
nz1.getName();
Assert.assertEquals(1, beanCache.size());
Country nz2 = Ebean.getReference(Country.class, "NZ");
Country nz2b = Ebean.getReference(Country.class, "NZ");
Country nz3 = Ebean.find(Country.class, "NZ");
Country nz4 = Ebean.find(Country.class)
.setId("NZ")
.setAutofetch(false)
.setUseCache(false)
.findUnique();
Assert.assertTrue(nz2 == nz2b);
Assert.assertTrue(nz2 == nz3);
Assert.assertTrue(nz3 != nz4);
}
}
@@ -1,12 +1,12 @@
package com.avaje.tests.basic;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.PersistentFile;
import com.avaje.tests.model.basic.PersistentFileContent;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestSaveDeleteOneToOne extends TestCase {
public void testCreateDeletePersistentFile() {
@@ -1,12 +1,12 @@
package com.avaje.tests.basic;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.PFile;
import com.avaje.tests.model.basic.PFileContent;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestSaveDeleteOneToOneMultiple extends TestCase {
// public void testCreateDeletePFile() {
@@ -1,133 +1,133 @@
package com.avaje.tests.basic;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebean.bean.SerializeControl;
import com.avaje.ebean.common.BeanList;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.OrderDetail;
import com.avaje.tests.model.basic.Order.Status;
public class TestSerialization extends TestCase {
public void testSerialization() {
EbeanServer server = Ebean.getServer(null);
Customer customer = server.getReference(Customer.class, 1);
Order o = server.createEntityBean(Order.class);
o.setOrderDate(new Date(System.currentTimeMillis()));
o.setStatus(Status.NEW);
o.setCustomer(customer);
BeanList<OrderDetail> details = new BeanList<OrderDetail>();
o.setDetails(details);
EntityBean eb = (EntityBean)o;
Order orderCopy = (Order)eb._ebean_createCopy();
Assert.assertNotNull(orderCopy.getDetails());
Assert.assertNotNull(orderCopy.getCustomer());
EntityBeanIntercept ebi = eb._ebean_getIntercept();
o.setStatus(Status.APPROVED);
ebi.setReadOnly(true);
ebi.setLoaded();
try {
o.setStatus(Status.COMPLETE);
Assert.assertTrue("dont get here",false);
} catch (IllegalStateException e){
Assert.assertTrue("throws exception",true);
}
SerializeControl.setVanilla(true);
Assert.assertTrue(SerializeControl.isVanillaBeans());
Assert.assertTrue(SerializeControl.isVanillaCollections());
Order testUsingSubclassing = new Order();
if (testUsingSubclassing instanceof EntityBean){
System.out.println("Need to run serialisation test with 'subclassing/proxies'");
} else {
System.out.println("Testing serialisation of 'subclassing/proxies'");
Object vanillaOrder = serialWriteRead(o, true);
Assert.assertFalse("should be an EntityBean", (vanillaOrder instanceof EntityBean));
Assert.assertTrue("should be an Order", (vanillaOrder instanceof Order));
Order vanOrder = (Order)vanillaOrder;
Customer vanCustomer = vanOrder.getCustomer();
List<OrderDetail> vanDetails = vanOrder.getDetails();
Assert.assertFalse("should NOT be an EntityBean", (vanCustomer instanceof EntityBean));
Assert.assertFalse("should NOT be an BeanList", (vanDetails instanceof BeanList<?>));
Assert.assertTrue("should be an ArrayList", (vanDetails instanceof ArrayList<?>));
Assert.assertTrue("should be an Customer", (vanCustomer instanceof Customer));
}
SerializeControl.setVanilla(false);
Object subclassOrder = serialWriteRead(o, false);
Assert.assertTrue("should be an Order", (subclassOrder instanceof Order));
Assert.assertTrue("should be an EntityBean", (subclassOrder instanceof EntityBean));
SerializeControl.setVanilla(true);
File serTestFile = new File("serTest");
if (serTestFile.exists()){
serTestFile.delete();
}
}
private Object serialWriteRead(Object inputObject, boolean vanilla){
try {
File serTestFile = new File("serTest");
FileOutputStream fout = new FileOutputStream(serTestFile);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(inputObject);
oos.close();
FileInputStream fin = new FileInputStream(serTestFile);
ObjectInputStream ois;
if (vanilla){
ois = new ObjectInputStream(fin);
} else {
ois = Ebean.getServer(null).createProxyObjectInputStream(fin);
}
Object readObject = ois.readObject();
ois.close();
return readObject;
} catch (Exception e){
e.printStackTrace();
Assert.assertTrue(false);
return null;
}
}
}
package com.avaje.tests.basic;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebean.bean.SerializeControl;
import com.avaje.ebean.common.BeanList;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.Order.Status;
import com.avaje.tests.model.basic.OrderDetail;
public class TestSerialization extends TestCase {
public void testSerialization() {
EbeanServer server = Ebean.getServer(null);
Customer customer = server.getReference(Customer.class, 1);
Order o = server.createEntityBean(Order.class);
o.setOrderDate(new Date(System.currentTimeMillis()));
o.setStatus(Status.NEW);
o.setCustomer(customer);
BeanList<OrderDetail> details = new BeanList<OrderDetail>();
o.setDetails(details);
EntityBean eb = (EntityBean)o;
Order orderCopy = (Order)eb._ebean_createCopy();
Assert.assertNotNull(orderCopy.getDetails());
Assert.assertNotNull(orderCopy.getCustomer());
EntityBeanIntercept ebi = eb._ebean_getIntercept();
o.setStatus(Status.APPROVED);
ebi.setReadOnly(true);
ebi.setLoaded();
try {
o.setStatus(Status.COMPLETE);
Assert.assertTrue("dont get here",false);
} catch (IllegalStateException e){
Assert.assertTrue("throws exception",true);
}
SerializeControl.setVanilla(true);
Assert.assertTrue(SerializeControl.isVanillaBeans());
Assert.assertTrue(SerializeControl.isVanillaCollections());
Order testUsingSubclassing = new Order();
if (testUsingSubclassing instanceof EntityBean){
System.out.println("Need to run serialisation test with 'subclassing/proxies'");
} else {
System.out.println("Testing serialisation of 'subclassing/proxies'");
Object vanillaOrder = serialWriteRead(o, true);
Assert.assertFalse("should be an EntityBean", (vanillaOrder instanceof EntityBean));
Assert.assertTrue("should be an Order", (vanillaOrder instanceof Order));
Order vanOrder = (Order)vanillaOrder;
Customer vanCustomer = vanOrder.getCustomer();
List<OrderDetail> vanDetails = vanOrder.getDetails();
Assert.assertFalse("should NOT be an EntityBean", (vanCustomer instanceof EntityBean));
Assert.assertFalse("should NOT be an BeanList", (vanDetails instanceof BeanList<?>));
Assert.assertTrue("should be an ArrayList", (vanDetails instanceof ArrayList<?>));
Assert.assertTrue("should be an Customer", (vanCustomer instanceof Customer));
}
SerializeControl.setVanilla(false);
Object subclassOrder = serialWriteRead(o, false);
Assert.assertTrue("should be an Order", (subclassOrder instanceof Order));
Assert.assertTrue("should be an EntityBean", (subclassOrder instanceof EntityBean));
SerializeControl.setVanilla(true);
File serTestFile = new File("serTest");
if (serTestFile.exists()){
serTestFile.delete();
}
}
private Object serialWriteRead(Object inputObject, boolean vanilla){
try {
File serTestFile = new File("serTest");
FileOutputStream fout = new FileOutputStream(serTestFile);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(inputObject);
oos.close();
FileInputStream fin = new FileInputStream(serTestFile);
ObjectInputStream ois;
if (vanilla){
ois = new ObjectInputStream(fin);
} else {
ois = Ebean.getServer(null).createProxyObjectInputStream(fin);
}
Object readObject = ois.readObject();
ois.close();
return readObject;
} catch (Exception e){
e.printStackTrace();
Assert.assertTrue(false);
return null;
}
}
}
@@ -1,28 +1,28 @@
package com.avaje.tests.basic.event;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.TWithPreInsert;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestPreInsertValidation extends TestCase {
public void test() {
TWithPreInsert e = new TWithPreInsert();
e.setTitle("Mister");
// the perInsert should populate the
// name with should not be null
Ebean.save(e);
// the save worked
Assert.assertNotNull(e.getId());
TWithPreInsert e1 = Ebean.find(TWithPreInsert.class, e.getId());
e1.setTitle("Missus");
Ebean.save(e1);
}
}
package com.avaje.tests.basic.event;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.TWithPreInsert;
public class TestPreInsertValidation extends TestCase {
public void test() {
TWithPreInsert e = new TWithPreInsert();
e.setTitle("Mister");
// the perInsert should populate the
// name with should not be null
Ebean.save(e);
// the save worked
Assert.assertNotNull(e.getId());
TWithPreInsert e1 = Ebean.find(TWithPreInsert.class, e.getId());
e1.setTitle("Missus");
Ebean.save(e1);
}
}
@@ -1,64 +1,65 @@
package com.avaje.tests.basic.event;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Transaction;
import com.avaje.tests.model.basic.TWithPreInsert;
import junit.framework.TestCase;
public class TestTransactionEvent extends TestCase {
@Override
protected void tearDown() throws Exception {
MyTestTransactionEventListener.setDoTest(false);
}
@Override
protected void setUp() throws Exception {
MyTestTransactionEventListener.setDoTest(true);
}
public void test() {
assertNull(MyTestTransactionEventListener.getLastCommitted());
assertNull(MyTestTransactionEventListener.getLastRollbacked());
final Object myUserObject = new Object();
Transaction tx = Ebean.beginTransaction();
tx.putUserObject("myUserObject", myUserObject);
TWithPreInsert e = new TWithPreInsert();
e.setTitle("Mister Transaction1");
Ebean.save(e);
tx.commit();
assertNotNull(MyTestTransactionEventListener.getLastCommitted());
assertSame(MyTestTransactionEventListener.getLastCommitted(), tx);
assertNotNull(MyTestTransactionEventListener.getLastCommitted().getUserObject("myUserObject"));
assertSame(MyTestTransactionEventListener.getLastCommitted().getUserObject("myUserObject"), myUserObject);
assertNull(MyTestTransactionEventListener.getLastRollbacked());
Transaction tx2 = Ebean.beginTransaction();
tx2.putUserObject("myUserObject2", myUserObject);
TWithPreInsert e2 = new TWithPreInsert();
e2.setTitle("Mister Transaction2");
Ebean.save(e2);
tx2.rollback();
assertNotNull(MyTestTransactionEventListener.getLastCommitted());
assertNotNull(MyTestTransactionEventListener.getLastRollbacked());
assertNotSame(MyTestTransactionEventListener.getLastCommitted(), MyTestTransactionEventListener.getLastRollbacked());
assertSame(MyTestTransactionEventListener.getLastCommitted(), tx);
assertNotNull(MyTestTransactionEventListener.getLastCommitted().getUserObject("myUserObject"));
assertSame(MyTestTransactionEventListener.getLastCommitted().getUserObject("myUserObject"), myUserObject);
assertSame(MyTestTransactionEventListener.getLastRollbacked(), tx2);
assertNotNull(MyTestTransactionEventListener.getLastRollbacked().getUserObject("myUserObject2"));
assertSame(MyTestTransactionEventListener.getLastRollbacked().getUserObject("myUserObject2"), myUserObject);
}
}
package com.avaje.tests.basic.event;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Transaction;
import com.avaje.tests.model.basic.TWithPreInsert;
public class TestTransactionEvent extends TestCase {
@Override
protected void tearDown() throws Exception {
MyTestTransactionEventListener.setDoTest(false);
}
@Override
protected void setUp() throws Exception {
MyTestTransactionEventListener.setDoTest(true);
}
public void test() {
assertNull(MyTestTransactionEventListener.getLastCommitted());
assertNull(MyTestTransactionEventListener.getLastRollbacked());
final Object myUserObject = new Object();
Transaction tx = Ebean.beginTransaction();
tx.putUserObject("myUserObject", myUserObject);
TWithPreInsert e = new TWithPreInsert();
e.setTitle("Mister Transaction1");
Ebean.save(e);
tx.commit();
assertNotNull(MyTestTransactionEventListener.getLastCommitted());
assertSame(MyTestTransactionEventListener.getLastCommitted(), tx);
assertNotNull(MyTestTransactionEventListener.getLastCommitted().getUserObject("myUserObject"));
assertSame(MyTestTransactionEventListener.getLastCommitted().getUserObject("myUserObject"), myUserObject);
assertNull(MyTestTransactionEventListener.getLastRollbacked());
Transaction tx2 = Ebean.beginTransaction();
tx2.putUserObject("myUserObject2", myUserObject);
TWithPreInsert e2 = new TWithPreInsert();
e2.setTitle("Mister Transaction2");
Ebean.save(e2);
tx2.rollback();
assertNotNull(MyTestTransactionEventListener.getLastCommitted());
assertNotNull(MyTestTransactionEventListener.getLastRollbacked());
assertNotSame(MyTestTransactionEventListener.getLastCommitted(), MyTestTransactionEventListener.getLastRollbacked());
assertSame(MyTestTransactionEventListener.getLastCommitted(), tx);
assertNotNull(MyTestTransactionEventListener.getLastCommitted().getUserObject("myUserObject"));
assertSame(MyTestTransactionEventListener.getLastCommitted().getUserObject("myUserObject"), myUserObject);
assertSame(MyTestTransactionEventListener.getLastRollbacked(), tx2);
assertNotNull(MyTestTransactionEventListener.getLastRollbacked().getUserObject("myUserObject2"));
assertSame(MyTestTransactionEventListener.getLastRollbacked().getUserObject("myUserObject2"), myUserObject);
}
}
@@ -1,33 +1,33 @@
package com.avaje.tests.basic.join;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
import com.avaje.tests.model.basic.Order.Status;
public class TestSecondaryJoin extends TestCase {
public void test() {
ResetBasicData.reset();
List<Order> list = Ebean.find(Order.class)
//.select("*")
//.join("customer")
.findList();
Order o0 = list.get(0);
o0.setCustomerName("Banan");
o0.setStatus(Status.APPROVED);
Ebean.save(o0);
System.out.println("done");
}
}
package com.avaje.tests.basic.join;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.Order.Status;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestSecondaryJoin extends TestCase {
public void test() {
ResetBasicData.reset();
List<Order> list = Ebean.find(Order.class)
//.select("*")
//.join("customer")
.findList();
Order o0 = list.get(0);
o0.setCustomerName("Banan");
o0.setStatus(Status.APPROVED);
Ebean.save(o0);
System.out.println("done");
}
}
@@ -1,10 +1,10 @@
package com.avaje.tests.basic.one2one;
import com.avaje.ebean.Ebean;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
public class TestOne2OneBookingInvoice extends TestCase {
public void test() {
@@ -1,254 +1,256 @@
package com.avaje.tests.batchload;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Expr;
import com.avaje.ebean.FetchConfig;
import com.avaje.ebean.Transaction;
import com.avaje.tests.basic.MyTestDataSourcePoolListener;
import com.avaje.tests.model.basic.Address;
import com.avaje.tests.model.basic.Contact;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
import junit.framework.TestCase;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class TestBasicLazy extends TestCase
{
public void testQueries()
{
ResetBasicData.reset();
Order order = Ebean.find(Order.class)
.select("totalAmount")
.setMaxRows(1)
.order("id")
.findUnique();
Assert.assertNotNull(order);
Customer customer = order.getCustomer();
Assert.assertNotNull(customer);
Assert.assertNotNull(customer.getName());
Address address = customer.getBillingAddress();
Assert.assertNotNull(address);
Assert.assertNotNull(address.getCity());
}
public void test_N1N()
{
ResetBasicData.reset();
// safety check to see if our customer we are going to use for the test has some contacts
Customer c = Ebean.find(Customer.class).setId(1).findUnique();
assertNotNull(c.getContacts());
assertTrue("no contacts on test customer 1", c.getContacts().size() > 0);
// start transaction so we have a "long running" persistence context
Transaction tx = Ebean.beginTransaction();
try
{
List<Order> order = Ebean.find(Order.class)
.where(Expr.eq("customer.id", 1))
.findList();
assertNotNull(order);
assertTrue(order.size() > 0);
Customer customer = order.get(0).getCustomer();
assertNotNull(customer);
assertEquals(1, customer.getId().intValue());
// this should lazily fetch the contacts
List<Contact> contacts = customer.getContacts();
assertNotNull(contacts);
assertTrue("contacts not lazily fetched", contacts.size() > 0);
}
finally
{
tx.commit();
}
}
public void testRaceCondition_Simple() throws Throwable
{
ResetBasicData.reset();
Order order = Ebean.find(Order.class)
.select("totalAmount")
.setMaxRows(1)
.order("id")
.findUnique();
Assert.assertNotNull(order);
final Customer customer = order.getCustomer();
Assert.assertNotNull(customer);
Assert.assertTrue(Ebean.getBeanState(customer).isReference());
final Throwable throwables[] = new Throwable[2];
Thread t1 = new Thread()
{
@Override
public void run()
{
try
{
Assert.assertNotNull(customer.getName());
}
catch (Throwable e)
{
throwables[0] = e;
}
}
};
Thread t2 = new Thread()
{
@Override
public void run()
{
try
{
Assert.assertNotNull(customer.getName());
}
catch (Throwable e)
{
throwables[1] = e;
}
}
};
try
{
// prepare for race condition
MyTestDataSourcePoolListener.SLEEP_AFTER_BORROW = 2000;
t1.start();
t2.start();
t1.join();
t2.join();
}
finally
{
MyTestDataSourcePoolListener.SLEEP_AFTER_BORROW = 0;
}
Assert.assertFalse(Ebean.getBeanState(customer).isReference());
if (throwables[0] != null)
{
throw throwables[0];
}
if (throwables[1] != null)
{
throw throwables[1];
}
}
private final AtomicBoolean mutex = new AtomicBoolean(false);
private List<Order> orders;
private List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>());
private class FetchThread extends Thread
{
private int index;
private FetchThread(ThreadGroup tg, int index)
{
super(tg, "fetcher-" + index);
this.index = index;
}
@Override
public void run()
{
synchronized (mutex)
{
System.err.println("** WAIT **");
try
{
while (!mutex.get())
{
mutex.wait(100);
}
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
try
{
System.err.println("** DO LAZY FETCH **");
orders.get(index).getCustomer().getName();
}
catch (Throwable e)
{
exceptions.add(e);
}
}
}
public void testRaceCondition_Complex() throws Throwable
{
ResetBasicData.reset();
ThreadGroup tg = new ThreadGroup("fetchers");
new FetchThread(tg, 0).start();
new FetchThread(tg, 1).start();
new FetchThread(tg, 2).start();
new FetchThread(tg, 3).start();
new FetchThread(tg, 0).start();
new FetchThread(tg, 1).start();
new FetchThread(tg, 2).start();
new FetchThread(tg, 3).start();
orders = Ebean.find(Order.class)
.fetch("customer", new FetchConfig().lazy(100))
.findList();
assertTrue(orders.size() >= 4);
try
{
MyTestDataSourcePoolListener.SLEEP_AFTER_BORROW = 2000;
synchronized (mutex)
{
mutex.set(true);
mutex.notifyAll();
}
while(tg.activeCount() > 0)
{
Thread.sleep(100);
}
}
finally
{
MyTestDataSourcePoolListener.SLEEP_AFTER_BORROW = 0;
}
if (exceptions.size() > 0)
{
System.err.println("Seen Exceptions:");
for (Throwable exception : exceptions)
{
exception.printStackTrace();
}
Assert.fail();
}
}
package com.avaje.tests.batchload;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import junit.framework.TestCase;
import org.junit.Assert;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Expr;
import com.avaje.ebean.FetchConfig;
import com.avaje.ebean.Transaction;
import com.avaje.tests.basic.MyTestDataSourcePoolListener;
import com.avaje.tests.model.basic.Address;
import com.avaje.tests.model.basic.Contact;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestBasicLazy extends TestCase
{
public void testQueries()
{
ResetBasicData.reset();
Order order = Ebean.find(Order.class)
.select("totalAmount")
.setMaxRows(1)
.order("id")
.findUnique();
Assert.assertNotNull(order);
Customer customer = order.getCustomer();
Assert.assertNotNull(customer);
Assert.assertNotNull(customer.getName());
Address address = customer.getBillingAddress();
Assert.assertNotNull(address);
Assert.assertNotNull(address.getCity());
}
public void test_N1N()
{
ResetBasicData.reset();
// safety check to see if our customer we are going to use for the test has some contacts
Customer c = Ebean.find(Customer.class).setId(1).findUnique();
assertNotNull(c.getContacts());
assertTrue("no contacts on test customer 1", c.getContacts().size() > 0);
// start transaction so we have a "long running" persistence context
Transaction tx = Ebean.beginTransaction();
try
{
List<Order> order = Ebean.find(Order.class)
.where(Expr.eq("customer.id", 1))
.findList();
assertNotNull(order);
assertTrue(order.size() > 0);
Customer customer = order.get(0).getCustomer();
assertNotNull(customer);
assertEquals(1, customer.getId().intValue());
// this should lazily fetch the contacts
List<Contact> contacts = customer.getContacts();
assertNotNull(contacts);
assertTrue("contacts not lazily fetched", contacts.size() > 0);
}
finally
{
tx.commit();
}
}
public void testRaceCondition_Simple() throws Throwable
{
ResetBasicData.reset();
Order order = Ebean.find(Order.class)
.select("totalAmount")
.setMaxRows(1)
.order("id")
.findUnique();
Assert.assertNotNull(order);
final Customer customer = order.getCustomer();
Assert.assertNotNull(customer);
Assert.assertTrue(Ebean.getBeanState(customer).isReference());
final Throwable throwables[] = new Throwable[2];
Thread t1 = new Thread()
{
@Override
public void run()
{
try
{
Assert.assertNotNull(customer.getName());
}
catch (Throwable e)
{
throwables[0] = e;
}
}
};
Thread t2 = new Thread()
{
@Override
public void run()
{
try
{
Assert.assertNotNull(customer.getName());
}
catch (Throwable e)
{
throwables[1] = e;
}
}
};
try
{
// prepare for race condition
MyTestDataSourcePoolListener.SLEEP_AFTER_BORROW = 2000;
t1.start();
t2.start();
t1.join();
t2.join();
}
finally
{
MyTestDataSourcePoolListener.SLEEP_AFTER_BORROW = 0;
}
Assert.assertFalse(Ebean.getBeanState(customer).isReference());
if (throwables[0] != null)
{
throw throwables[0];
}
if (throwables[1] != null)
{
throw throwables[1];
}
}
private final AtomicBoolean mutex = new AtomicBoolean(false);
private List<Order> orders;
private List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>());
private class FetchThread extends Thread
{
private int index;
private FetchThread(ThreadGroup tg, int index)
{
super(tg, "fetcher-" + index);
this.index = index;
}
@Override
public void run()
{
synchronized (mutex)
{
System.err.println("** WAIT **");
try
{
while (!mutex.get())
{
mutex.wait(100);
}
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
try
{
System.err.println("** DO LAZY FETCH **");
orders.get(index).getCustomer().getName();
}
catch (Throwable e)
{
exceptions.add(e);
}
}
}
public void testRaceCondition_Complex() throws Throwable
{
ResetBasicData.reset();
ThreadGroup tg = new ThreadGroup("fetchers");
new FetchThread(tg, 0).start();
new FetchThread(tg, 1).start();
new FetchThread(tg, 2).start();
new FetchThread(tg, 3).start();
new FetchThread(tg, 0).start();
new FetchThread(tg, 1).start();
new FetchThread(tg, 2).start();
new FetchThread(tg, 3).start();
orders = Ebean.find(Order.class)
.fetch("customer", new FetchConfig().lazy(100))
.findList();
assertTrue(orders.size() >= 4);
try
{
MyTestDataSourcePoolListener.SLEEP_AFTER_BORROW = 2000;
synchronized (mutex)
{
mutex.set(true);
mutex.notifyAll();
}
while(tg.activeCount() > 0)
{
Thread.sleep(100);
}
}
finally
{
MyTestDataSourcePoolListener.SLEEP_AFTER_BORROW = 0;
}
if (exceptions.size() > 0)
{
System.err.println("Seen Exceptions:");
for (Throwable exception : exceptions)
{
exception.printStackTrace();
}
Assert.fail();
}
}
}
@@ -1,31 +1,31 @@
package com.avaje.tests.batchload;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
import com.avaje.tests.model.basic.Order.Status;
public class TestEmptyManyLazyLoad extends TestCase {
public void test() {
ResetBasicData.reset();
Customer c = Ebean.find(Customer.class)
.findList()
.get(0);
Order o = new Order();
o.setCustomer(c);
o.setStatus(Status.NEW);
Ebean.save(o);
Order o2 = Ebean.find(Order.class, o.getId());
o2.getDetails().size();
}
}
package com.avaje.tests.batchload;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.Order.Status;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestEmptyManyLazyLoad extends TestCase {
public void test() {
ResetBasicData.reset();
Customer c = Ebean.find(Customer.class)
.findList()
.get(0);
Order o = new Order();
o.setCustomer(c);
o.setStatus(Status.NEW);
Ebean.save(o);
Order o2 = Ebean.find(Order.class, o.getId());
o2.getDetails().size();
}
}
+144 -146
View File
@@ -1,146 +1,144 @@
package com.avaje.tests.cache;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.cache.ServerCache;
import com.avaje.ebean.cache.ServerCacheStatistics;
import com.avaje.tests.model.basic.Address;
import com.avaje.tests.model.basic.Country;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestCacheBasic extends TestCase {
public void test(){
ResetBasicData.reset();
Ebean.getServerCacheManager().clear(Country.class);
ServerCache countryCache = Ebean.getServerCacheManager().getBeanCache(Country.class);
Ebean.runCacheWarming(Country.class);
Assert.assertTrue(countryCache.size() > 0);
// reset the statistics
countryCache.getStatistics(true);
Country c0 = Ebean.getReference(Country.class, "NZ");
ServerCacheStatistics statistics = countryCache.getStatistics(false);
int hc = statistics.getHitCount();
Assert.assertEquals(1, hc);
// Country c1 = Ebean.getReference(Country.class, "NZ");
// Assert.assertEquals(2, countryCache.getStatistics(false).getHitCount());
// //Assert.assertEquals(100, countryCache.getStatistics(false).getHitRatio());
//
// // same instance as caching with readOnly=true
// Assert.assertTrue(c0 != c1);
//
// c0.getName();
// c1.getName();
//
// // reset the statistics
// Assert.assertEquals(2,countryCache.getStatistics(true).getHitCount());
// // now the count should be 0 again
// Assert.assertEquals(0, countryCache.getStatistics(false).getHitCount());
// // and hitRatio is 0 as well
// Assert.assertEquals(0, countryCache.getStatistics(false).getHitRatio());
//
// // hit the country cache automatically via join
//
// Customer custTest = ResetBasicData.createCustAndOrder("cacheBasic");
// Integer id = custTest.getId();
// Customer customer = Ebean.find(Customer.class, id);
//
// Address billingAddress = customer.getBillingAddress();
// Country c2 = billingAddress.getCountry();
// c2.getName();
//
// Assert.assertTrue(countryCache.getStatistics(false).getHitCount() > 0);
//
// //Country c3 = Ebean.getReference(Country.class, "NZ");
// //Country c4 = Ebean.find(Country.class, "NZ");
//
//
// // clear the cache
// Ebean.getServerCacheManager().clear(Country.class);
// // reset statistics
// countryCache.getStatistics(true);
//
// // try to hit the country cache automatically via join
// customer = Ebean.find(Customer.class, id);
// billingAddress = customer.getBillingAddress();
// Country c5 = billingAddress.getCountry();
// // but cache is empty so c5 is reference that will load cache
// // if it is lazy loaded
// Assert.assertEquals("empty cache",0,countryCache.getStatistics(false).getSize());
// //Assert.assertEquals("missCount 1",1,countryCache.getStatistics(false).getMissCount());
//
// // lazy load on c5 populates the cache
// c5.getName();
// Assert.assertEquals("cache populated via lazy load",1,countryCache.getStatistics(false).getSize());
//
// // now these get hits in the cache
// Country c6 = Ebean.find(Country.class, "NZ");
//
// Assert.assertTrue("different instance as cache cleared",c2 != c5);
// Assert.assertTrue("these 2 are different",c5 != c6);
//
// // by default readOnly based on deployment annotation
// Assert.assertTrue("read only",Ebean.getBeanState(c6).isReadOnly());
//
// try {
// // can't modify a readOnly bean
// c6.setName("Nu Zilund");
// Assert.assertFalse("Never get here",true);
// } catch (IllegalStateException e){
// Assert.assertTrue("This is readOnly",true);
// }
//
// Country c8 = Ebean.find(Country.class)
// .setId("NZ")
// .setReadOnly(false)
// .findUnique();
//
// // Explicitly NOT readOnly
// Assert.assertFalse("NOT read only",Ebean.getBeanState(c8).isReadOnly());
//
// Assert.assertEquals("1 countries in cache", 1, countryCache.size());
// c8.setName("Nu Zilund");
// // the update will remove the entry from the cache
// Ebean.save(c8);
//
// Assert.assertEquals("1 country in cache", 1, countryCache.size());
//
// Country c9 = Ebean.find(Country.class)
// .setReadOnly(false)
// .setId("NZ")
// .findUnique();
//
// // Find loads cache ...
// Assert.assertFalse(Ebean.getBeanState(c9).isReadOnly());
// Assert.assertTrue(countryCache.size() > 0);
//
// Country c10 = Ebean.find(Country.class,"NZ");
//
// Assert.assertTrue(Ebean.getBeanState(c10).isReadOnly());
// Assert.assertTrue(countryCache.size() > 0);
//
// Ebean.getServerCacheManager().clear(Country.class);
// Assert.assertEquals("0 country in cache", 0, countryCache.size());
//
// // reference doesn't load cache yet
// Country c11 = Ebean.getReference(Country.class, "NZ");
//
// // still 0 in cache
// Assert.assertEquals("0 country in cache", 0, countryCache.size());
//
// // will invoke lazy loading..
// c11.getName();
// Assert.assertTrue(countryCache.size() > 0);
}
}
package com.avaje.tests.cache;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.cache.ServerCache;
import com.avaje.ebean.cache.ServerCacheStatistics;
import com.avaje.tests.model.basic.Country;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestCacheBasic extends TestCase {
public void test(){
ResetBasicData.reset();
Ebean.getServerCacheManager().clear(Country.class);
ServerCache countryCache = Ebean.getServerCacheManager().getBeanCache(Country.class);
Ebean.runCacheWarming(Country.class);
Assert.assertTrue(countryCache.size() > 0);
// reset the statistics
countryCache.getStatistics(true);
Country c0 = Ebean.getReference(Country.class, "NZ");
ServerCacheStatistics statistics = countryCache.getStatistics(false);
int hc = statistics.getHitCount();
Assert.assertEquals(1, hc);
// Country c1 = Ebean.getReference(Country.class, "NZ");
// Assert.assertEquals(2, countryCache.getStatistics(false).getHitCount());
// //Assert.assertEquals(100, countryCache.getStatistics(false).getHitRatio());
//
// // same instance as caching with readOnly=true
// Assert.assertTrue(c0 != c1);
//
// c0.getName();
// c1.getName();
//
// // reset the statistics
// Assert.assertEquals(2,countryCache.getStatistics(true).getHitCount());
// // now the count should be 0 again
// Assert.assertEquals(0, countryCache.getStatistics(false).getHitCount());
// // and hitRatio is 0 as well
// Assert.assertEquals(0, countryCache.getStatistics(false).getHitRatio());
//
// // hit the country cache automatically via join
//
// Customer custTest = ResetBasicData.createCustAndOrder("cacheBasic");
// Integer id = custTest.getId();
// Customer customer = Ebean.find(Customer.class, id);
//
// Address billingAddress = customer.getBillingAddress();
// Country c2 = billingAddress.getCountry();
// c2.getName();
//
// Assert.assertTrue(countryCache.getStatistics(false).getHitCount() > 0);
//
// //Country c3 = Ebean.getReference(Country.class, "NZ");
// //Country c4 = Ebean.find(Country.class, "NZ");
//
//
// // clear the cache
// Ebean.getServerCacheManager().clear(Country.class);
// // reset statistics
// countryCache.getStatistics(true);
//
// // try to hit the country cache automatically via join
// customer = Ebean.find(Customer.class, id);
// billingAddress = customer.getBillingAddress();
// Country c5 = billingAddress.getCountry();
// // but cache is empty so c5 is reference that will load cache
// // if it is lazy loaded
// Assert.assertEquals("empty cache",0,countryCache.getStatistics(false).getSize());
// //Assert.assertEquals("missCount 1",1,countryCache.getStatistics(false).getMissCount());
//
// // lazy load on c5 populates the cache
// c5.getName();
// Assert.assertEquals("cache populated via lazy load",1,countryCache.getStatistics(false).getSize());
//
// // now these get hits in the cache
// Country c6 = Ebean.find(Country.class, "NZ");
//
// Assert.assertTrue("different instance as cache cleared",c2 != c5);
// Assert.assertTrue("these 2 are different",c5 != c6);
//
// // by default readOnly based on deployment annotation
// Assert.assertTrue("read only",Ebean.getBeanState(c6).isReadOnly());
//
// try {
// // can't modify a readOnly bean
// c6.setName("Nu Zilund");
// Assert.assertFalse("Never get here",true);
// } catch (IllegalStateException e){
// Assert.assertTrue("This is readOnly",true);
// }
//
// Country c8 = Ebean.find(Country.class)
// .setId("NZ")
// .setReadOnly(false)
// .findUnique();
//
// // Explicitly NOT readOnly
// Assert.assertFalse("NOT read only",Ebean.getBeanState(c8).isReadOnly());
//
// Assert.assertEquals("1 countries in cache", 1, countryCache.size());
// c8.setName("Nu Zilund");
// // the update will remove the entry from the cache
// Ebean.save(c8);
//
// Assert.assertEquals("1 country in cache", 1, countryCache.size());
//
// Country c9 = Ebean.find(Country.class)
// .setReadOnly(false)
// .setId("NZ")
// .findUnique();
//
// // Find loads cache ...
// Assert.assertFalse(Ebean.getBeanState(c9).isReadOnly());
// Assert.assertTrue(countryCache.size() > 0);
//
// Country c10 = Ebean.find(Country.class,"NZ");
//
// Assert.assertTrue(Ebean.getBeanState(c10).isReadOnly());
// Assert.assertTrue(countryCache.size() > 0);
//
// Ebean.getServerCacheManager().clear(Country.class);
// Assert.assertEquals("0 country in cache", 0, countryCache.size());
//
// // reference doesn't load cache yet
// Country c11 = Ebean.getReference(Country.class, "NZ");
//
// // still 0 in cache
// Assert.assertEquals("0 country in cache", 0, countryCache.size());
//
// // will invoke lazy loading..
// c11.getName();
// Assert.assertTrue(countryCache.size() > 0);
}
}
+68 -68
View File
@@ -1,68 +1,68 @@
package com.avaje.tests.cache;
import java.util.List;
import org.junit.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestQueryCache extends TestCase {
@SuppressWarnings("unchecked")
public void test(){
ResetBasicData.reset();
List<Customer> list = Ebean.find(Customer.class)
.setUseQueryCache(true)
.setReadOnly(true)
.where().ilike("name", "Rob")
.findList();
BeanCollection<Customer> bc = (BeanCollection<Customer>)list;
Assert.assertFalse(bc.isReadOnly());
Assert.assertFalse(bc.isEmpty());
Assert.assertTrue(list.size() > 0);
Assert.assertTrue(Ebean.getBeanState(list.get(0)).isReadOnly());
List<Customer> list2 = Ebean.find(Customer.class)
.setUseQueryCache(true)
.setReadOnly(true)
.where().ilike("name", "Rob")
.findList();
List<Customer> list2B = Ebean.find(Customer.class)
.setUseQueryCache(true)
//.setReadOnly(true)
.where().ilike("name", "Rob")
.findList();
// Assert.assertTrue("same instance",list != list2);
//
// // readOnly defaults to true for query cache
// Assert.assertTrue("same instance",list != list2B);
//
// List<Customer> list3 = Ebean.find(Customer.class)
// .setUseQueryCache(true)
// .setReadOnly(false)
// .where().ilike("name", "Rob")
// .findList();
//
// Assert.assertTrue("diff instance",list != list3);
// BeanCollection<Customer> bc3 = (BeanCollection<Customer>)list3;
// Assert.assertFalse(bc3.isReadOnly());
// Assert.assertFalse(bc3.isEmpty());
// Assert.assertTrue(list3.size() > 0);
// Assert.assertFalse(Ebean.getBeanState(list3.get(0)).isReadOnly());
}
}
package com.avaje.tests.cache;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Assert;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestQueryCache extends TestCase {
@SuppressWarnings("unchecked")
public void test(){
ResetBasicData.reset();
List<Customer> list = Ebean.find(Customer.class)
.setUseQueryCache(true)
.setReadOnly(true)
.where().ilike("name", "Rob")
.findList();
BeanCollection<Customer> bc = (BeanCollection<Customer>)list;
Assert.assertFalse(bc.isReadOnly());
Assert.assertFalse(bc.isEmpty());
Assert.assertTrue(list.size() > 0);
Assert.assertTrue(Ebean.getBeanState(list.get(0)).isReadOnly());
List<Customer> list2 = Ebean.find(Customer.class)
.setUseQueryCache(true)
.setReadOnly(true)
.where().ilike("name", "Rob")
.findList();
List<Customer> list2B = Ebean.find(Customer.class)
.setUseQueryCache(true)
//.setReadOnly(true)
.where().ilike("name", "Rob")
.findList();
// Assert.assertTrue("same instance",list != list2);
//
// // readOnly defaults to true for query cache
// Assert.assertTrue("same instance",list != list2B);
//
// List<Customer> list3 = Ebean.find(Customer.class)
// .setUseQueryCache(true)
// .setReadOnly(false)
// .where().ilike("name", "Rob")
// .findList();
//
// Assert.assertTrue("diff instance",list != list3);
// BeanCollection<Customer> bc3 = (BeanCollection<Customer>)list3;
// Assert.assertFalse(bc3.isReadOnly());
// Assert.assertFalse(bc3.isEmpty());
// Assert.assertTrue(list3.size() > 0);
// Assert.assertFalse(Ebean.getBeanState(list3.get(0)).isReadOnly());
}
}
@@ -1,59 +1,60 @@
package com.avaje.tests.compositekeys.db;
import javax.persistence.Embeddable;
import java.util.Date;
@Embeddable
public class AuditInfo
{
private Date lastUpdated;
private Date created;
private String updatedBy;
private String createdBy;
public AuditInfo()
{
created = new Date();
createdBy = "dummy";
}
public Date getLastUpdated()
{
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated)
{
this.lastUpdated = lastUpdated;
}
public Date getCreated()
{
return created;
}
public void setCreated(Date created)
{
this.created = created;
}
public String getUpdatedBy()
{
return updatedBy;
}
public void setUpdatedBy(String updatedBy)
{
this.updatedBy = updatedBy;
}
public String getCreatedBy()
{
return createdBy;
}
public void setCreatedBy(String createdBy)
{
this.createdBy = createdBy;
}
}
package com.avaje.tests.compositekeys.db;
import java.util.Date;
import javax.persistence.Embeddable;
@Embeddable
public class AuditInfo
{
private Date lastUpdated;
private Date created;
private String updatedBy;
private String createdBy;
public AuditInfo()
{
created = new Date();
createdBy = "dummy";
}
public Date getLastUpdated()
{
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated)
{
this.lastUpdated = lastUpdated;
}
public Date getCreated()
{
return created;
}
public void setCreated(Date created)
{
this.created = created;
}
public String getUpdatedBy()
{
return updatedBy;
}
public void setUpdatedBy(String updatedBy)
{
this.updatedBy = updatedBy;
}
public String getCreatedBy()
{
return createdBy;
}
public void setCreatedBy(String createdBy)
{
this.createdBy = createdBy;
}
}
@@ -1,118 +1,127 @@
package com.avaje.tests.compositekeys.db;
import javax.persistence.*;
@Entity
public class Item
{
@Id
private ItemKey key;
private String description;
private String units;
private int type;
private int region;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "lastUpdated", column = @Column(name = "DATE_MODIFIED")),
@AttributeOverride(name = "created", column = @Column(name = "DATE_CREATED")),
@AttributeOverride(name = "updatedBy", column = @Column(name = "MODIFIED_BY")),
@AttributeOverride(name = "createdBy", column = @Column(name = "CREATED_BY"))
})
private AuditInfo auditInfo = new AuditInfo();
@Version
private Long version;
@ManyToOne
@JoinColumns({
@JoinColumn(name = "customer", referencedColumnName = "customer", insertable = false, updatable = false),
@JoinColumn(name = "type", referencedColumnName = "type", insertable = false, updatable = false)
})
private Type eType;
@ManyToOne
@JoinColumns({
@JoinColumn(name = "customer", referencedColumnName = "customer", insertable = false, updatable = false),
@JoinColumn(name = "region", referencedColumnName = "type", insertable = false, updatable = false)
})
private Region eRegion;
public ItemKey getKey() {
return key;
}
public void setKey(ItemKey key) {
this.key = key;
}
public String getUnits()
{
return units;
}
public void setUnits(String units)
{
this.units = units;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getRegion() {
return region;
}
public void setRegion(int region) {
this.region = region;
}
public Long getVersion() {
return version;
}
public Type getEType() {
return eType;
}
public Region getERegion() {
return eRegion;
}
public void setVersion(Long version)
{
this.version = version;
}
public void setEType(Type eType)
{
this.eType = eType;
}
public void setERegion(Region eRegion)
{
this.eRegion = eRegion;
}
public AuditInfo getAuditInfo()
{
return auditInfo;
}
}
package com.avaje.tests.compositekeys.db;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.Version;
@Entity
public class Item
{
@Id
private ItemKey key;
private String description;
private String units;
private int type;
private int region;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "lastUpdated", column = @Column(name = "DATE_MODIFIED")),
@AttributeOverride(name = "created", column = @Column(name = "DATE_CREATED")),
@AttributeOverride(name = "updatedBy", column = @Column(name = "MODIFIED_BY")),
@AttributeOverride(name = "createdBy", column = @Column(name = "CREATED_BY"))
})
private AuditInfo auditInfo = new AuditInfo();
@Version
private Long version;
@ManyToOne
@JoinColumns({
@JoinColumn(name = "customer", referencedColumnName = "customer", insertable = false, updatable = false),
@JoinColumn(name = "type", referencedColumnName = "type", insertable = false, updatable = false)
})
private Type eType;
@ManyToOne
@JoinColumns({
@JoinColumn(name = "customer", referencedColumnName = "customer", insertable = false, updatable = false),
@JoinColumn(name = "region", referencedColumnName = "type", insertable = false, updatable = false)
})
private Region eRegion;
public ItemKey getKey() {
return key;
}
public void setKey(ItemKey key) {
this.key = key;
}
public String getUnits()
{
return units;
}
public void setUnits(String units)
{
this.units = units;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getRegion() {
return region;
}
public void setRegion(int region) {
this.region = region;
}
public Long getVersion() {
return version;
}
public Type getEType() {
return eType;
}
public Region getERegion() {
return eRegion;
}
public void setVersion(Long version)
{
this.version = version;
}
public void setEType(Type eType)
{
this.eType = eType;
}
public void setERegion(Region eRegion)
{
this.eRegion = eRegion;
}
public AuditInfo getAuditInfo()
{
return auditInfo;
}
}
@@ -1,63 +1,63 @@
package com.avaje.tests.compositekeys.db;
import javax.persistence.Embeddable;
import javax.persistence.Column;
@Embeddable
public class ItemKey
{
private int customer;
@Column(name = "itemNumber")
private String itemNumber;
public int getCustomer() {
return customer;
}
public void setCustomer(int customer) {
this.customer = customer;
}
public String getItemNumber() {
return itemNumber;
}
public void setItemNumber(String itemNumber) {
this.itemNumber = itemNumber;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (!(o instanceof ItemKey))
{
return false;
}
ItemKey itemKey = (ItemKey) o;
if (customer != itemKey.customer)
{
return false;
}
if (!itemNumber.equals(itemKey.itemNumber))
{
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = customer;
result = 31 * result + itemNumber.hashCode();
return result;
}
}
package com.avaje.tests.compositekeys.db;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class ItemKey
{
private int customer;
@Column(name = "itemNumber")
private String itemNumber;
public int getCustomer() {
return customer;
}
public void setCustomer(int customer) {
this.customer = customer;
}
public String getItemNumber() {
return itemNumber;
}
public void setItemNumber(String itemNumber) {
this.itemNumber = itemNumber;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (!(o instanceof ItemKey))
{
return false;
}
ItemKey itemKey = (ItemKey) o;
if (customer != itemKey.customer)
{
return false;
}
if (!itemNumber.equals(itemKey.itemNumber))
{
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = customer;
result = 31 * result + itemNumber.hashCode();
return result;
}
}
@@ -1,33 +1,35 @@
package com.avaje.tests.compositekeys.db;
import javax.persistence.*;
@Entity
public class Parcel
{
@Id
@Column(name="parcelId")
private Long parcelId;
private String description;
public Long getParcelId()
{
return parcelId;
}
public void setParcelId(Long parcelId)
{
this.parcelId = parcelId;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
package com.avaje.tests.compositekeys.db;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Parcel
{
@Id
@Column(name="parcelId")
private Long parcelId;
private String description;
public Long getParcelId()
{
return parcelId;
}
public void setParcelId(Long parcelId)
{
this.parcelId = parcelId;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
}
@@ -1,51 +1,57 @@
package com.avaje.tests.compositekeys.db;
import javax.persistence.*;
import java.util.List;
@Entity
public class Region
{
@Id
private RegionKey key;
private String description;
@Version
private Long version;
@OneToMany
@JoinColumns({
@JoinColumn(name = "customer", referencedColumnName = "customer", insertable = false, updatable = false),
@JoinColumn(name = "region", referencedColumnName = "type", insertable = false, updatable = false)
})
private List<Item> items;
public RegionKey getKey() {
return key;
}
public void setKey(RegionKey key) {
this.key = key;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public List<Item> getItems() {
return items;
}
package com.avaje.tests.compositekeys.db;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.OneToMany;
import javax.persistence.Version;
@Entity
public class Region
{
@Id
private RegionKey key;
private String description;
@Version
private Long version;
@OneToMany
@JoinColumns({
@JoinColumn(name = "customer", referencedColumnName = "customer", insertable = false, updatable = false),
@JoinColumn(name = "region", referencedColumnName = "type", insertable = false, updatable = false)
})
private List<Item> items;
public RegionKey getKey() {
return key;
}
public void setKey(RegionKey key) {
this.key = key;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public List<Item> getItems() {
return items;
}
}
@@ -1,62 +1,69 @@
package com.avaje.tests.compositekeys.db;
import javax.persistence.*;
import java.util.List;
@Entity
public class Type
{
@Id
private TypeKey key;
private String description;
@Version
private Long version;
@OneToMany
@JoinColumns({
@JoinColumn(name = "customer", referencedColumnName = "customer", insertable = false, updatable = false),
@JoinColumn(name = "type", referencedColumnName = "type", insertable = false, updatable = false)
})
private List<Item> items;
@ManyToOne
private SubType subType;
public TypeKey getKey() {
return key;
}
public void setKey(TypeKey key) {
this.key = key;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public List<Item> getItems() {
return items;
}
public SubType getSubType() {
return subType;
}
public void setSubType(SubType subType) {
this.subType = subType;
}
package com.avaje.tests.compositekeys.db;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Version;
@Entity
public class Type
{
@Id
private TypeKey key;
private String description;
@Version
private Long version;
@OneToMany
@JoinColumns({
@JoinColumn(name = "customer", referencedColumnName = "customer", insertable = false, updatable = false),
@JoinColumn(name = "type", referencedColumnName = "type", insertable = false, updatable = false)
})
private List<Item> items;
@ManyToOne
private SubType subType;
public TypeKey getKey() {
return key;
}
public void setKey(TypeKey key) {
this.key = key;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public List<Item> getItems() {
return items;
}
public SubType getSubType() {
return subType;
}
public void setSubType(SubType subType) {
this.subType = subType;
}
}
@@ -1,64 +1,64 @@
package com.avaje.tests.ddd.iud;
import java.util.Currency;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
import com.avaje.tests.model.ddd.DPerson;
import com.avaje.tests.model.ivo.CMoney;
import com.avaje.tests.model.ivo.Money;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestDPersonEl extends TestCase {
public void test() {
GlobalProperties.put("classes", DPerson.class.toString());
Currency NZD = Currency.getInstance("NZD");
DPerson p = new DPerson();
p.setFirstName("first");
p.setLastName("last");
p.setSalary(new Money("12200"));
p.setCmoney(new CMoney(new Money("12"), NZD));
SpiEbeanServer server = (SpiEbeanServer)Ebean.getServer(null);
BeanDescriptor<DPerson> descriptor = server.getBeanDescriptor(DPerson.class);
ElPropertyValue elCmoney = descriptor.getElGetValue("cmoney");
ElPropertyValue elCmoneyAmt = descriptor.getElGetValue("cmoney.amount");
ElPropertyValue elCmoneyCur = descriptor.getElGetValue("cmoney.currency");
Object cmoney = elCmoney.elGetValue(p);
Object amt = elCmoneyAmt.elGetValue(p);
Object cur = elCmoneyCur.elGetValue(p);
Assert.assertNotNull(cmoney);
Assert.assertEquals(new Money("12"), amt);
Assert.assertEquals(NZD, cur);
p.setCmoney(null);
Assert.assertNull(p.getCmoney());
// won't trigger CMoney build as not all properties
// have been set yet...
elCmoneyAmt.elSetValue(p, new Money("13"), true, false);
Assert.assertNull(p.getCmoney());
// will trigger the build and setting of CMoney
elCmoneyCur.elSetValue(p, NZD, true, false);
// this time not null as all required properties for
// the compound object have been collected
Assert.assertNotNull(p.getCmoney());
}
}
package com.avaje.tests.ddd.iud;
import java.util.Currency;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
import com.avaje.tests.model.ddd.DPerson;
import com.avaje.tests.model.ivo.CMoney;
import com.avaje.tests.model.ivo.Money;
public class TestDPersonEl extends TestCase {
public void test() {
GlobalProperties.put("classes", DPerson.class.toString());
Currency NZD = Currency.getInstance("NZD");
DPerson p = new DPerson();
p.setFirstName("first");
p.setLastName("last");
p.setSalary(new Money("12200"));
p.setCmoney(new CMoney(new Money("12"), NZD));
SpiEbeanServer server = (SpiEbeanServer)Ebean.getServer(null);
BeanDescriptor<DPerson> descriptor = server.getBeanDescriptor(DPerson.class);
ElPropertyValue elCmoney = descriptor.getElGetValue("cmoney");
ElPropertyValue elCmoneyAmt = descriptor.getElGetValue("cmoney.amount");
ElPropertyValue elCmoneyCur = descriptor.getElGetValue("cmoney.currency");
Object cmoney = elCmoney.elGetValue(p);
Object amt = elCmoneyAmt.elGetValue(p);
Object cur = elCmoneyCur.elGetValue(p);
Assert.assertNotNull(cmoney);
Assert.assertEquals(new Money("12"), amt);
Assert.assertEquals(NZD, cur);
p.setCmoney(null);
Assert.assertNull(p.getCmoney());
// won't trigger CMoney build as not all properties
// have been set yet...
elCmoneyAmt.elSetValue(p, new Money("13"), true, false);
Assert.assertNull(p.getCmoney());
// will trigger the build and setting of CMoney
elCmoneyCur.elSetValue(p, NZD, true, false);
// this time not null as all required properties for
// the compound object have been collected
Assert.assertNotNull(p.getCmoney());
}
}
@@ -1,34 +1,34 @@
package com.avaje.tests.genkey;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.tests.model.basic.TOne;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestSeqBatch extends TestCase {
public void test() {
EbeanServer server = Ebean.getServer(null);
SpiEbeanServer spiServer = (SpiEbeanServer)server;
boolean seqSupport = spiServer.getDatabasePlatform().getDbIdentity().isSupportsSequence();
if (seqSupport){
BeanDescriptor<TOne> d = spiServer.getBeanDescriptor(TOne.class);
Object id = d.nextId(null);
Assert.assertNotNull(id);
for (int i = 0; i < 16; i++) {
Object id2 = d.nextId(null);
Assert.assertNotNull(id2);
}
}
}
}
package com.avaje.tests.genkey;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.tests.model.basic.TOne;
public class TestSeqBatch extends TestCase {
public void test() {
EbeanServer server = Ebean.getServer(null);
SpiEbeanServer spiServer = (SpiEbeanServer)server;
boolean seqSupport = spiServer.getDatabasePlatform().getDbIdentity().isSupportsSequence();
if (seqSupport){
BeanDescriptor<TOne> d = spiServer.getBeanDescriptor(TOne.class);
Object id = d.nextId(null);
Assert.assertNotNull(id);
for (int i = 0; i < 16; i++) {
Object id2 = d.nextId(null);
Assert.assertNotNull(id2);
}
}
}
}
@@ -1,56 +1,54 @@
package com.avaje.tests.idkeys;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
//import com.avaje.ebean.LogLevel;
//import com.avaje.ebean.Transaction;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.tests.model.basic.ESimple;
public class TestSimpleIdInsert extends TestCase {
public void test() {
GlobalProperties.put("datasource.default", "h2");
GlobalProperties.put("ebean.classes", ESimple.class.getName());
ESimple e = new ESimple();
e.setName("name");
Ebean.save(e);
Assert.assertNotNull(e.getId());
}
// // This test fails with jdbc drivers that don't
// // support batch insert with getGeneratedKeys
// public void testJdbcBatch() {
//
// GlobalProperties.put("datasource.default", "hsqldb");
// GlobalProperties.put("ebean.classes", ESimple.class.getName());
//
// Transaction transaction = Ebean.beginTransaction();
// try {
// transaction.setBatchMode(true);
// transaction.setLogLevel(LogLevel.SQL);
// ESimple e = new ESimple();
// e.setName("name");
// Ebean.save(e);
//
// ESimple e2 = new ESimple();
// e2.setName("name2");
// Ebean.save(e2);
// transaction.commit();
//
// Assert.assertNotNull(e.getId());
// Assert.assertNotNull(e2.getId());
//
// } finally {
// Ebean.endTransaction();
// }
// }
}
package com.avaje.tests.idkeys;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.tests.model.basic.ESimple;
public class TestSimpleIdInsert extends TestCase {
public void test() {
GlobalProperties.put("datasource.default", "h2");
GlobalProperties.put("ebean.classes", ESimple.class.getName());
ESimple e = new ESimple();
e.setName("name");
Ebean.save(e);
Assert.assertNotNull(e.getId());
}
// // This test fails with jdbc drivers that don't
// // support batch insert with getGeneratedKeys
// public void testJdbcBatch() {
//
// GlobalProperties.put("datasource.default", "hsqldb");
// GlobalProperties.put("ebean.classes", ESimple.class.getName());
//
// Transaction transaction = Ebean.beginTransaction();
// try {
// transaction.setBatchMode(true);
// transaction.setLogLevel(LogLevel.SQL);
// ESimple e = new ESimple();
// e.setName("name");
// Ebean.save(e);
//
// ESimple e2 = new ESimple();
// e2.setName("name2");
// Ebean.save(e2);
// transaction.commit();
//
// Assert.assertNotNull(e.getId());
// Assert.assertNotNull(e2.getId());
//
// } finally {
// Ebean.endTransaction();
// }
// }
}
@@ -1,54 +1,54 @@
package com.avaje.tests.inheritance;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.TxRunnable;
import com.avaje.tests.model.basic.AttributeHolder;
import com.avaje.tests.model.basic.ListAttribute;
import com.avaje.tests.model.basic.ListAttributeValue;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestDuplcateKeyException extends TestCase {
/**
* Test query.
* <p>This test covers the BUG 276. Cascade was not propagating to the ListAttribute because
* it was considered safe to skip as it didn't take into account any derived classes
* into account with e.g. collections and Cascade options </p>
*/
public void testQuery()
{
// Setup the data first
final ListAttributeValue value1 = new ListAttributeValue();
Ebean.save(value1);
final ListAttribute listAttribute = new ListAttribute();
listAttribute.add(value1);
Ebean.save(listAttribute);
final AttributeHolder holder = new AttributeHolder();
holder.add(listAttribute);
try {
Ebean.execute(new TxRunnable() {
public void run() {
Ebean.currentTransaction().log("-- saving holder first time");
// Alternatively turn off cascade Persist for this transaction
//Ebean.currentTransaction().setPersistCascade(false);
Ebean.save(holder);
Ebean.currentTransaction().log("-- saving holder second time");
// we don't get this far before failing
//Ebean.save(holder);
}
});
} catch (Exception e){
Assert.assertEquals(e.getMessage(), "test rollback");
}
}
}
package com.avaje.tests.inheritance;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.TxRunnable;
import com.avaje.tests.model.basic.AttributeHolder;
import com.avaje.tests.model.basic.ListAttribute;
import com.avaje.tests.model.basic.ListAttributeValue;
public class TestDuplcateKeyException extends TestCase {
/**
* Test query.
* <p>This test covers the BUG 276. Cascade was not propagating to the ListAttribute because
* it was considered safe to skip as it didn't take into account any derived classes
* into account with e.g. collections and Cascade options </p>
*/
public void testQuery()
{
// Setup the data first
final ListAttributeValue value1 = new ListAttributeValue();
Ebean.save(value1);
final ListAttribute listAttribute = new ListAttribute();
listAttribute.add(value1);
Ebean.save(listAttribute);
final AttributeHolder holder = new AttributeHolder();
holder.add(listAttribute);
try {
Ebean.execute(new TxRunnable() {
public void run() {
Ebean.currentTransaction().log("-- saving holder first time");
// Alternatively turn off cascade Persist for this transaction
//Ebean.currentTransaction().setPersistCascade(false);
Ebean.save(holder);
Ebean.currentTransaction().log("-- saving holder second time");
// we don't get this far before failing
//Ebean.save(holder);
}
});
} catch (Exception e){
Assert.assertEquals(e.getMessage(), "test rollback");
}
}
}
@@ -1,45 +1,45 @@
package com.avaje.tests.inheritance;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.TIntChild;
import com.avaje.tests.model.basic.TIntRoot;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestIntInherit extends TestCase {
public void testMe() {
TIntRoot r = new TIntRoot();
r.setName("root1");
TIntRoot r2 = new TIntRoot();
r.setName("root2");
TIntChild c1 = new TIntChild();
c1.setName("child1");
c1.setChildProperty("cp1");
TIntChild c2 = new TIntChild();
c2.setName("child2");
c2.setChildProperty("cp2");
Ebean.save(r);
Ebean.save(r2);
Ebean.save(c1);
Ebean.save(c2);
TIntRoot result1 = Ebean.find(TIntRoot.class, r.getId());
Assert.assertTrue(result1 instanceof TIntRoot);
TIntRoot ref3 = Ebean.getReference(TIntRoot.class, c1.getId());
Assert.assertTrue(ref3 instanceof TIntChild);
TIntRoot result3 = Ebean.find(TIntRoot.class, c1.getId());
Assert.assertTrue(result3 instanceof TIntChild);
}
}
package com.avaje.tests.inheritance;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.TIntChild;
import com.avaje.tests.model.basic.TIntRoot;
public class TestIntInherit extends TestCase {
public void testMe() {
TIntRoot r = new TIntRoot();
r.setName("root1");
TIntRoot r2 = new TIntRoot();
r.setName("root2");
TIntChild c1 = new TIntChild();
c1.setName("child1");
c1.setChildProperty("cp1");
TIntChild c2 = new TIntChild();
c2.setName("child2");
c2.setChildProperty("cp2");
Ebean.save(r);
Ebean.save(r2);
Ebean.save(c1);
Ebean.save(c2);
TIntRoot result1 = Ebean.find(TIntRoot.class, r.getId());
Assert.assertTrue(result1 instanceof TIntRoot);
TIntRoot ref3 = Ebean.getReference(TIntRoot.class, c1.getId());
Assert.assertTrue(ref3 instanceof TIntChild);
TIntRoot result3 = Ebean.find(TIntRoot.class, c1.getId());
Assert.assertTrue(result3 instanceof TIntChild);
}
}
@@ -1,67 +1,67 @@
package com.avaje.tests.inheritance;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.AttributeHolder;
import com.avaje.tests.model.basic.ListAttribute;
import com.avaje.tests.model.basic.ListAttributeValue;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestSkippable extends TestCase {
/**
* Test query.
* <p>This test covers the BUG 276. Cascade was not propagating to the ListAttribute because
* it was considered safe to skip as it didn't take into account any derived classes
* into account with e.g. collections and Cascade options </p>
*/
public void testQuery()
{
// Setup the data first
final ListAttributeValue value1 = new ListAttributeValue();
final ListAttributeValue value2 = new ListAttributeValue();
Ebean.save(value1);
Ebean.save(value2);
final ListAttribute listAttribute = new ListAttribute();
listAttribute.add(value1);
Ebean.save(listAttribute);
final ListAttribute listAttributeDB = Ebean.find(ListAttribute.class, listAttribute.getId());
Assert.assertNotNull(listAttributeDB);
final ListAttributeValue value1_DB = listAttributeDB.getValues().iterator().next();
Assert.assertTrue(value1.getId().equals(value1_DB.getId()));
final AttributeHolder holder = new AttributeHolder();
holder.add(listAttributeDB);
Ebean.save(holder);
// Now change the M2M listAttribute.values and save the holder
// The save should cascade as follows
// holder.attributes..ListAttribute.values
listAttributeDB.getValues().clear();
listAttributeDB.add(value2);
// Save the holder - should cascade down to the listAtribute and save the values
Ebean.save(holder);
final ListAttribute listAttributeDB_2 = Ebean.find(ListAttribute.class, listAttributeDB.getId());
Assert.assertNotNull(listAttributeDB_2);
final ListAttributeValue value2_DB_2 = listAttributeDB_2.getValues().iterator().next();
Assert.assertTrue("Cascade failed", value2.getId().equals(value2_DB_2.getId()));
}
}
package com.avaje.tests.inheritance;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.AttributeHolder;
import com.avaje.tests.model.basic.ListAttribute;
import com.avaje.tests.model.basic.ListAttributeValue;
public class TestSkippable extends TestCase {
/**
* Test query.
* <p>This test covers the BUG 276. Cascade was not propagating to the ListAttribute because
* it was considered safe to skip as it didn't take into account any derived classes
* into account with e.g. collections and Cascade options </p>
*/
public void testQuery()
{
// Setup the data first
final ListAttributeValue value1 = new ListAttributeValue();
final ListAttributeValue value2 = new ListAttributeValue();
Ebean.save(value1);
Ebean.save(value2);
final ListAttribute listAttribute = new ListAttribute();
listAttribute.add(value1);
Ebean.save(listAttribute);
final ListAttribute listAttributeDB = Ebean.find(ListAttribute.class, listAttribute.getId());
Assert.assertNotNull(listAttributeDB);
final ListAttributeValue value1_DB = listAttributeDB.getValues().iterator().next();
Assert.assertTrue(value1.getId().equals(value1_DB.getId()));
final AttributeHolder holder = new AttributeHolder();
holder.add(listAttributeDB);
Ebean.save(holder);
// Now change the M2M listAttribute.values and save the holder
// The save should cascade as follows
// holder.attributes..ListAttribute.values
listAttributeDB.getValues().clear();
listAttributeDB.add(value2);
// Save the holder - should cascade down to the listAtribute and save the values
Ebean.save(holder);
final ListAttribute listAttributeDB_2 = Ebean.find(ListAttribute.class, listAttributeDB.getId());
Assert.assertNotNull(listAttributeDB_2);
final ListAttributeValue value2_DB_2 = listAttributeDB_2.getValues().iterator().next();
Assert.assertTrue("Cascade failed", value2.getId().equals(value2_DB_2.getId()));
}
}
@@ -1,68 +1,68 @@
package com.avaje.tests.ldap;
import java.util.Set;
import javax.naming.directory.Attribute;
import junit.framework.Assert;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.BeanPropertySimpleCollection;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor.EntityType;
import com.avaje.ebeaninternal.server.type.ScalarType;
import com.avaje.ebeaninternal.server.type.ScalarTypeLdapTimestamp;
import com.avaje.tests.model.ldap.LDPerson;
public class TestLDPersonDeploy extends BaseLdapTest {
public void test() {
boolean b = true;
if (b){
// turn this test off for the moment
return;
}
GlobalProperties.put("ebean.classes", LDPerson.class.toString());
EbeanServer server = createServer();
SpiEbeanServer spiServer = (SpiEbeanServer)server;
BeanDescriptor<LDPerson> descriptor = spiServer.getBeanDescriptor(LDPerson.class);
Assert.assertTrue(EntityType.LDAP.equals(descriptor.getEntityType()));
BeanProperty beanProperty = descriptor.getBeanProperty("modifiedTime");
Assert.assertEquals("modifiedTime", beanProperty.getName());
Assert.assertEquals("modifiedTime", beanProperty.getDbColumn());
ScalarType<?> scalarType = beanProperty.getScalarType();
Assert.assertTrue(scalarType instanceof ScalarTypeLdapTimestamp<?>);
BeanProperty accountsProp = descriptor.getBeanProperty("accounts");
Assert.assertTrue(accountsProp instanceof BeanPropertySimpleCollection<?>);
LDPerson person = new LDPerson();
person.addAccount(1001);
person.addAccount(1002);
person.addAccount(1003);
Attribute acctAttribute = accountsProp.createAttribute(person);
Assert.assertTrue(acctAttribute.size() == 3);
LDPerson newPerson = new LDPerson();
accountsProp.setAttributeValue(newPerson, acctAttribute);
Set<Long> accounts = newPerson.getAccounts();
Assert.assertTrue(accounts.size() == 3);
}
}
package com.avaje.tests.ldap;
import java.util.Set;
import javax.naming.directory.Attribute;
import junit.framework.Assert;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor.EntityType;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.BeanPropertySimpleCollection;
import com.avaje.ebeaninternal.server.type.ScalarType;
import com.avaje.ebeaninternal.server.type.ScalarTypeLdapTimestamp;
import com.avaje.tests.model.ldap.LDPerson;
public class TestLDPersonDeploy extends BaseLdapTest {
public void test() {
boolean b = true;
if (b){
// turn this test off for the moment
return;
}
GlobalProperties.put("ebean.classes", LDPerson.class.toString());
EbeanServer server = createServer();
SpiEbeanServer spiServer = (SpiEbeanServer)server;
BeanDescriptor<LDPerson> descriptor = spiServer.getBeanDescriptor(LDPerson.class);
Assert.assertTrue(EntityType.LDAP.equals(descriptor.getEntityType()));
BeanProperty beanProperty = descriptor.getBeanProperty("modifiedTime");
Assert.assertEquals("modifiedTime", beanProperty.getName());
Assert.assertEquals("modifiedTime", beanProperty.getDbColumn());
ScalarType<?> scalarType = beanProperty.getScalarType();
Assert.assertTrue(scalarType instanceof ScalarTypeLdapTimestamp<?>);
BeanProperty accountsProp = descriptor.getBeanProperty("accounts");
Assert.assertTrue(accountsProp instanceof BeanPropertySimpleCollection<?>);
LDPerson person = new LDPerson();
person.addAccount(1001);
person.addAccount(1002);
person.addAccount(1003);
Attribute acctAttribute = accountsProp.createAttribute(person);
Assert.assertTrue(acctAttribute.size() == 3);
LDPerson newPerson = new LDPerson();
accountsProp.setAttributeValue(newPerson, acctAttribute);
Set<Long> accounts = newPerson.getAccounts();
Assert.assertTrue(accounts.size() == 3);
}
}
@@ -1,48 +1,60 @@
package com.avaje.tests.model.basic.xtra;
import javax.persistence.*;
import java.util.List;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType=DiscriminatorType.STRING , name="parent_type")
@DiscriminatorValue("BASIC")
@Table(name="td_parent")
public class EdParent {
@Id
@Column(name="parent_id")
private int id;
@Column(name="parent_name")
private String name;
@OneToMany(fetch = FetchType.EAGER, mappedBy="parent", cascade=CascadeType.ALL)
List<EdChild> children;
public List<EdChild> getChildren() {
return children;
}
public void setChildren(List<EdChild> children) {
this.children = children;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.avaje.tests.model.basic.xtra;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType=DiscriminatorType.STRING , name="parent_type")
@DiscriminatorValue("BASIC")
@Table(name="td_parent")
public class EdParent {
@Id
@Column(name="parent_id")
private int id;
@Column(name="parent_name")
private String name;
@OneToMany(fetch = FetchType.EAGER, mappedBy="parent", cascade=CascadeType.ALL)
List<EdChild> children;
public List<EdChild> getChildren() {
return children;
}
public void setChildren(List<EdChild> children) {
this.children = children;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -1,83 +1,79 @@
package com.avaje.tests.query;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.AdminAutofetch;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.ebean.bean.ObjectGraphNode;
import com.avaje.ebean.bean.ObjectGraphOrigin;
import com.avaje.ebean.meta.MetaAutoFetchStatistic;
import com.avaje.ebean.meta.MetaAutoFetchStatistic.NodeUsageStats;
import com.avaje.ebean.meta.MetaAutoFetchStatistic.QueryStats;
import com.avaje.ebeaninternal.api.SpiQuery;
import com.avaje.ebeaninternal.server.querydefn.DefaultOrmQuery;
import com.avaje.tests.model.basic.Address;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestAutofetchTuneWithJoin extends TestCase {
public void test() {
runQuery();
collectUsage();
}
private void runQuery() {
ResetBasicData.reset();
Query<Order> q = Ebean.find(Order.class)
.setAutofetch(true)
.fetch("customer")
.fetch("customer.contacts")
.where().lt("id", 3)
.query();
List<Order> list = q.findList();
for (int i = 0; i < list.size(); i++) {
Order order = list.get(i);
order.getOrderDate();
order.getShipDate();
// order.setShipDate(new Date(System.currentTimeMillis()));
Customer customer = order.getCustomer();
customer.getName();
Address shippingAddress = customer.getShippingAddress();
if (shippingAddress != null) {
shippingAddress.getLine1();
shippingAddress.getCity();
}
// customer.getContacts()
}
SpiQuery<?> sq = (SpiQuery<?>) q;
ObjectGraphNode parentNode = sq.getParentNode();
ObjectGraphOrigin origin = parentNode.getOriginQueryPoint();
System.out.println("Origin:" + origin.getKey());
// MetaAutoFetchStatistic metaAutoFetchStatistic = ((DefaultOrmQuery<?>)q).getMetaAutoFetchStatistic();
// if (metaAutoFetchStatistic != null) {
// List<NodeUsageStats> nodeUsageStats = metaAutoFetchStatistic.getNodeUsageStats();
// System.out.println(nodeUsageStats);
// List<QueryStats> queryStats = metaAutoFetchStatistic.getQueryStats();
// System.out.println(queryStats);
// }
if (q.isAutofetchTuned()) {
System.out.println("TUNED...");
}
}
private static void collectUsage() {
AdminAutofetch adminAutofetch = Ebean.getServer(null).getAdminAutofetch();
adminAutofetch.collectUsageViaGC();
}
}
package com.avaje.tests.query;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.AdminAutofetch;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.ebean.bean.ObjectGraphNode;
import com.avaje.ebean.bean.ObjectGraphOrigin;
import com.avaje.ebeaninternal.api.SpiQuery;
import com.avaje.tests.model.basic.Address;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestAutofetchTuneWithJoin extends TestCase {
public void test() {
runQuery();
collectUsage();
}
private void runQuery() {
ResetBasicData.reset();
Query<Order> q = Ebean.find(Order.class)
.setAutofetch(true)
.fetch("customer")
.fetch("customer.contacts")
.where().lt("id", 3)
.query();
List<Order> list = q.findList();
for (int i = 0; i < list.size(); i++) {
Order order = list.get(i);
order.getOrderDate();
order.getShipDate();
// order.setShipDate(new Date(System.currentTimeMillis()));
Customer customer = order.getCustomer();
customer.getName();
Address shippingAddress = customer.getShippingAddress();
if (shippingAddress != null) {
shippingAddress.getLine1();
shippingAddress.getCity();
}
// customer.getContacts()
}
SpiQuery<?> sq = (SpiQuery<?>) q;
ObjectGraphNode parentNode = sq.getParentNode();
ObjectGraphOrigin origin = parentNode.getOriginQueryPoint();
System.out.println("Origin:" + origin.getKey());
// MetaAutoFetchStatistic metaAutoFetchStatistic = ((DefaultOrmQuery<?>)q).getMetaAutoFetchStatistic();
// if (metaAutoFetchStatistic != null) {
// List<NodeUsageStats> nodeUsageStats = metaAutoFetchStatistic.getNodeUsageStats();
// System.out.println(nodeUsageStats);
// List<QueryStats> queryStats = metaAutoFetchStatistic.getQueryStats();
// System.out.println(queryStats);
// }
if (q.isAutofetchTuned()) {
System.out.println("TUNED...");
}
}
private static void collectUsage() {
AdminAutofetch adminAutofetch = Ebean.getServer(null).getAdminAutofetch();
adminAutofetch.collectUsageViaGC();
}
}
@@ -1,31 +1,32 @@
package com.avaje.tests.query;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Expr;
import com.avaje.ebean.Junction;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
import junit.framework.TestCase;
import java.util.List;
public class TestLimitQuery extends TestCase {
public void testHasManyWithLimit()
{
ResetBasicData.reset();
Query<Customer> query = Ebean.find(Customer.class);
query.setAutofetch(false);
query.setFirstRow(0);
query.setMaxRows(10);
Junction<Customer> junc = Expr.disjunction(query);
junc.add(Expr.like("name", "%A%"));
query.where(junc);
List<Customer> customer = query.findList();
assertTrue(customer.size() > 0); // should at least find the "Cust NoAddress" customer
}
package com.avaje.tests.query;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Expr;
import com.avaje.ebean.Junction;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestLimitQuery extends TestCase {
public void testHasManyWithLimit()
{
ResetBasicData.reset();
Query<Customer> query = Ebean.find(Customer.class);
query.setAutofetch(false);
query.setFirstRow(0);
query.setMaxRows(10);
Junction<Customer> junc = Expr.disjunction(query);
junc.add(Expr.like("name", "%A%"));
query.where(junc);
List<Customer> customer = query.findList();
assertTrue(customer.size() > 0); // should at least find the "Cust NoAddress" customer
}
}
@@ -1,206 +1,207 @@
package com.avaje.tests.query;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.CKeyParent;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
import com.avaje.tests.model.basic.Vehicle;
import com.avaje.tests.model.basic.VehicleDriver;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.List;
public class TestSubQuery extends TestCase {
public void testId() {
ResetBasicData.reset();
List<Integer> productIds = new ArrayList<Integer>();
productIds.add(3);
Query<Order> sq = Ebean.createQuery(Order.class)
.select("id")
.where().in("details.product.id", productIds)
.query();
List<Order> list = Ebean.find(Order.class)
.where().in("id", sq)
.findList();
System.out.println(list);
// FIXME: need to clear out old orders..
//Assert.assertEquals(2,list.size());
String oq = " find order (id, status) where id in "
+"(select a.id from o_order a join o_order_detail ad on ad.order_id = a.id where ad.product_id in (:prods)) ";
List<Order> list2 = Ebean.createQuery(Order.class, oq)
.setParameter("prods", productIds)
.findList();
System.out.println(list2);
//Assert.assertEquals(2,list2.size());
}
public void testCompositeKey()
{
ResetBasicData.reset();
Query<CKeyParent> sq = Ebean.createQuery(CKeyParent.class)
.select("id.oneKey")
.setAutofetch(false)
.where()
.query();
Query<CKeyParent> pq = Ebean.find(CKeyParent.class)
.where().in("id.oneKey", sq)
.query();
pq.findList();
String sql = pq.getGeneratedSql();
String golden = "(t0.one_key) in (select t0.one_key from ckey_parent t0) ";
if (sql.indexOf(golden) < 0)
{
System.out.println("failed sql:"+sql);
fail("golden string not found");
}
}
/**
* show that ebean is not using the correct table name in the subquery (sq)
*
public void testInheritance1()
{
ResetBasicData.reset();
Query<Vehicle> sq = Ebean.createQuery(Vehicle.class)
.select("id")
.setAutofetch(false)
.where()
.query();
Query<VehicleDriver> pq = Ebean.find(VehicleDriver.class)
.where().in("vehicle.id", sq)
.query();
pq.findList();
String sql = pq.getGeneratedSql();
System.err.println(sql);
String golden = "(t0.vehicle_id) in (select t0.id from t0.vehicle t0)";
if (sql.indexOf(golden) < 0)
{
System.out.println("failed sql:"+sql);
fail("golden string not found");
}
}
*/
/**
* show that ebean is adding the discriminator to the list of columns in the subquery
*/
public void testInheritance2()
{
ResetBasicData.reset();
Query<VehicleDriver> sq = Ebean.createQuery(VehicleDriver.class)
.select("vehicle")
.setAutofetch(false)
.where()
.query();
Query<Vehicle> pq = Ebean.find(Vehicle.class)
.where().in("id", sq)
.query();
pq.findList();
String sql = pq.getGeneratedSql();
System.err.println(sql);
// TODO: If, after bugfixing, the system still join against vehicle I do not know now, in our case, it is not necessary if not
// using it in the where clause
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left outer join vehicle t1 on t1.id = t0.vehicle_id )";
if (sql.indexOf(golden) < 0)
{
System.out.println("failed sql:"+sql);
fail("golden string not found");
}
}
/**
* show that ebean is adding the discriminator to the list of columns in the subquery.
* Second test to make sure that joining is still possible after bugfixing testInheritance2.
*/
public void testInheritance3()
{
ResetBasicData.reset();
Query<VehicleDriver> sq = Ebean.createQuery(VehicleDriver.class)
.select("vehicle")
.setAutofetch(false)
.where()
.eq("vehicle.licenseNumber", "abc")
.query();
Query<Vehicle> pq = Ebean.find(Vehicle.class)
.where().in("id", sq)
.query();
pq.findList();
String sql = pq.getGeneratedSql();
System.err.println(sql);
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left outer join vehicle t1 on t1.id = t0.vehicle_id where t1.license_number = ? )";
if (sql.indexOf(golden) < 0)
{
System.out.println("failed sql:"+sql);
fail("golden string not found");
}
}
/**
* show that ebean is using the wrong column (from the vehicle_driver table instead of vehicle) for the selected column in the subquery.
* In contrast to testInheritance2+3 this test forces ebean to "drill down" to the key of the relation.
*/
public void testInheritance4()
{
ResetBasicData.reset();
Query<VehicleDriver> sq = Ebean.createQuery(VehicleDriver.class)
.select("vehicle.id")
.setAutofetch(false)
.where()
.query();
Query<Vehicle> pq = Ebean.find(Vehicle.class)
.where().in("id", sq)
.query();
pq.findList();
String sql = pq.getGeneratedSql();
System.err.println(sql);
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left outer join vehicle t1 on t1.id = t0.vehicle_id )";
// OR without join
// String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0)";
if (sql.indexOf(golden) < 0)
{
System.out.println("failed sql:"+sql);
fail("golden string not found");
}
}
}
package com.avaje.tests.query;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.CKeyParent;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.ResetBasicData;
import com.avaje.tests.model.basic.Vehicle;
import com.avaje.tests.model.basic.VehicleDriver;
public class TestSubQuery extends TestCase {
public void testId() {
ResetBasicData.reset();
List<Integer> productIds = new ArrayList<Integer>();
productIds.add(3);
Query<Order> sq = Ebean.createQuery(Order.class)
.select("id")
.where().in("details.product.id", productIds)
.query();
List<Order> list = Ebean.find(Order.class)
.where().in("id", sq)
.findList();
System.out.println(list);
// FIXME: need to clear out old orders..
//Assert.assertEquals(2,list.size());
String oq = " find order (id, status) where id in "
+"(select a.id from o_order a join o_order_detail ad on ad.order_id = a.id where ad.product_id in (:prods)) ";
List<Order> list2 = Ebean.createQuery(Order.class, oq)
.setParameter("prods", productIds)
.findList();
System.out.println(list2);
//Assert.assertEquals(2,list2.size());
}
public void testCompositeKey()
{
ResetBasicData.reset();
Query<CKeyParent> sq = Ebean.createQuery(CKeyParent.class)
.select("id.oneKey")
.setAutofetch(false)
.where()
.query();
Query<CKeyParent> pq = Ebean.find(CKeyParent.class)
.where().in("id.oneKey", sq)
.query();
pq.findList();
String sql = pq.getGeneratedSql();
String golden = "(t0.one_key) in (select t0.one_key from ckey_parent t0) ";
if (sql.indexOf(golden) < 0)
{
System.out.println("failed sql:"+sql);
fail("golden string not found");
}
}
/**
* show that ebean is not using the correct table name in the subquery (sq)
*
public void testInheritance1()
{
ResetBasicData.reset();
Query<Vehicle> sq = Ebean.createQuery(Vehicle.class)
.select("id")
.setAutofetch(false)
.where()
.query();
Query<VehicleDriver> pq = Ebean.find(VehicleDriver.class)
.where().in("vehicle.id", sq)
.query();
pq.findList();
String sql = pq.getGeneratedSql();
System.err.println(sql);
String golden = "(t0.vehicle_id) in (select t0.id from t0.vehicle t0)";
if (sql.indexOf(golden) < 0)
{
System.out.println("failed sql:"+sql);
fail("golden string not found");
}
}
*/
/**
* show that ebean is adding the discriminator to the list of columns in the subquery
*/
public void testInheritance2()
{
ResetBasicData.reset();
Query<VehicleDriver> sq = Ebean.createQuery(VehicleDriver.class)
.select("vehicle")
.setAutofetch(false)
.where()
.query();
Query<Vehicle> pq = Ebean.find(Vehicle.class)
.where().in("id", sq)
.query();
pq.findList();
String sql = pq.getGeneratedSql();
System.err.println(sql);
// TODO: If, after bugfixing, the system still join against vehicle I do not know now, in our case, it is not necessary if not
// using it in the where clause
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left outer join vehicle t1 on t1.id = t0.vehicle_id )";
if (sql.indexOf(golden) < 0)
{
System.out.println("failed sql:"+sql);
fail("golden string not found");
}
}
/**
* show that ebean is adding the discriminator to the list of columns in the subquery.
* Second test to make sure that joining is still possible after bugfixing testInheritance2.
*/
public void testInheritance3()
{
ResetBasicData.reset();
Query<VehicleDriver> sq = Ebean.createQuery(VehicleDriver.class)
.select("vehicle")
.setAutofetch(false)
.where()
.eq("vehicle.licenseNumber", "abc")
.query();
Query<Vehicle> pq = Ebean.find(Vehicle.class)
.where().in("id", sq)
.query();
pq.findList();
String sql = pq.getGeneratedSql();
System.err.println(sql);
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left outer join vehicle t1 on t1.id = t0.vehicle_id where t1.license_number = ? )";
if (sql.indexOf(golden) < 0)
{
System.out.println("failed sql:"+sql);
fail("golden string not found");
}
}
/**
* show that ebean is using the wrong column (from the vehicle_driver table instead of vehicle) for the selected column in the subquery.
* In contrast to testInheritance2+3 this test forces ebean to "drill down" to the key of the relation.
*/
public void testInheritance4()
{
ResetBasicData.reset();
Query<VehicleDriver> sq = Ebean.createQuery(VehicleDriver.class)
.select("vehicle.id")
.setAutofetch(false)
.where()
.query();
Query<Vehicle> pq = Ebean.find(Vehicle.class)
.where().in("id", sq)
.query();
pq.findList();
String sql = pq.getGeneratedSql();
System.err.println(sql);
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left outer join vehicle t1 on t1.id = t0.vehicle_id )";
// OR without join
// String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0)";
if (sql.indexOf(golden) < 0)
{
System.out.println("failed sql:"+sql);
fail("golden string not found");
}
}
}
@@ -1,24 +1,24 @@
package com.avaje.tests.query;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Expr;
import com.avaje.tests.model.basic.OrderDetail;
import com.avaje.tests.model.basic.ResetBasicData;
import junit.framework.TestCase;
public class TestWhereRawClause extends TestCase {
public void testRawClause() {
ResetBasicData.reset();
Ebean.find(OrderDetail.class)
.where()
.not(Expr.eq("id", 1))
.raw("orderQty < shipQty")
.findList();
}
}
package com.avaje.tests.query;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Expr;
import com.avaje.tests.model.basic.OrderDetail;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestWhereRawClause extends TestCase {
public void testRawClause() {
ResetBasicData.reset();
Ebean.find(OrderDetail.class)
.where()
.not(Expr.eq("id", 1))
.raw("orderQty < shipQty")
.findList();
}
}
@@ -1,24 +1,24 @@
package com.avaje.tests.rawsql;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.SqlUpdate;
import junit.framework.TestCase;
public class TestInsertSqlLogging extends TestCase {
public void test() {
//Ebean.getServer(null);
String sql = "insert into audit_log (id, description, modified_description) values (?,?,?)";
SqlUpdate sqlUpdate = Ebean.createSqlUpdate(sql);
sqlUpdate.setParameter(1, 10000);
sqlUpdate.setParameter(2, "hello");
sqlUpdate.setParameter(3, "rob");
sqlUpdate.execute();
}
}
package com.avaje.tests.rawsql;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.SqlUpdate;
public class TestInsertSqlLogging extends TestCase {
public void test() {
//Ebean.getServer(null);
String sql = "insert into audit_log (id, description, modified_description) values (?,?,?)";
SqlUpdate sqlUpdate = Ebean.createSqlUpdate(sql);
sqlUpdate.setParameter(1, 10000);
sqlUpdate.setParameter(2, "hello");
sqlUpdate.setParameter(3, "rob");
sqlUpdate.execute();
}
}
@@ -1,80 +1,80 @@
package com.avaje.tests.rawsql;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.OrderAggregate;
import com.avaje.tests.model.basic.ResetBasicData;
import com.avaje.tests.model.basic.Order.Status;
public class TestRawSqlOrmWrapper extends TestCase {
public void test() {
ResetBasicData.reset();
String sql
= " select order_id, o.status, c.id, c.name, sum(d.order_qty*d.unit_price) as totalAmount"
+ " from o_order o"
+ " join o_customer c on c.id = o.kcustomer_id "
+ " join o_order_detail d on d.order_id = o.id "
+ " group by order_id, o.status, c.id, c.name ";
RawSql rawSql =
RawSqlBuilder
.parse(sql)
.columnMapping("order_id", "order.id")
.columnMapping("o.status", "order.status")
.columnMapping("c.id", "order.customer.id")
.columnMapping("c.name", "order.customer.name")
//.columnMapping("sum(d.order_qty*d.unit_price)", "totalAmount")
.create();
Query<OrderAggregate> query = Ebean.find(OrderAggregate.class);
query.setRawSql(rawSql)
//.fetch("order.details", new FetchConfig().query())
.where().gt("order.id", 0)
.having().gt("totalAmount", 20);
List<OrderAggregate> list = query.findList();
assertNotNull(list);
output(list);
List<OrderAggregate> list2 = Ebean.find(OrderAggregate.class)
.setRawSql(rawSql)
//.fetch("order.details", new FetchConfig().query())
.where().gt("order.id", 2)
.having().gt("totalAmount", 10)
.findList();
output(list2);
}
private void output(List<OrderAggregate> list) {
for (OrderAggregate oa : list) {
Double totalAmount = oa.getTotalAmount();
Order order = oa.getOrder();
Integer id = order.getId();
Status status = order.getStatus();
System.out.println("Order: "+id+" "+status+" total:"+totalAmount);
Customer c = order.getCustomer();
System.out.println(" -> customer: "+c.getId()+" "+c.getName());
// invoke lazy loading as this property
// has not populated originally
//order.getOrderDate();
}
}
}
package com.avaje.tests.rawsql;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Query;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.Order.Status;
import com.avaje.tests.model.basic.OrderAggregate;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestRawSqlOrmWrapper extends TestCase {
public void test() {
ResetBasicData.reset();
String sql
= " select order_id, o.status, c.id, c.name, sum(d.order_qty*d.unit_price) as totalAmount"
+ " from o_order o"
+ " join o_customer c on c.id = o.kcustomer_id "
+ " join o_order_detail d on d.order_id = o.id "
+ " group by order_id, o.status, c.id, c.name ";
RawSql rawSql =
RawSqlBuilder
.parse(sql)
.columnMapping("order_id", "order.id")
.columnMapping("o.status", "order.status")
.columnMapping("c.id", "order.customer.id")
.columnMapping("c.name", "order.customer.name")
//.columnMapping("sum(d.order_qty*d.unit_price)", "totalAmount")
.create();
Query<OrderAggregate> query = Ebean.find(OrderAggregate.class);
query.setRawSql(rawSql)
//.fetch("order.details", new FetchConfig().query())
.where().gt("order.id", 0)
.having().gt("totalAmount", 20);
List<OrderAggregate> list = query.findList();
assertNotNull(list);
output(list);
List<OrderAggregate> list2 = Ebean.find(OrderAggregate.class)
.setRawSql(rawSql)
//.fetch("order.details", new FetchConfig().query())
.where().gt("order.id", 2)
.having().gt("totalAmount", 10)
.findList();
output(list2);
}
private void output(List<OrderAggregate> list) {
for (OrderAggregate oa : list) {
Double totalAmount = oa.getTotalAmount();
Order order = oa.getOrder();
Integer id = order.getId();
Status status = order.getStatus();
System.out.println("Order: "+id+" "+status+" total:"+totalAmount);
Customer c = order.getCustomer();
System.out.println(" -> customer: "+c.getId()+" "+c.getName());
// invoke lazy loading as this property
// has not populated originally
//order.getOrderDate();
}
}
}
@@ -1,71 +1,71 @@
package com.avaje.tests.rawsql;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.FetchConfig;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.OrderAggregate;
import com.avaje.tests.model.basic.ResetBasicData;
import com.avaje.tests.model.basic.Order.Status;
public class TestRawSqlOrmWrapper3 extends TestCase {
public void test() {
ResetBasicData.reset();
String sql
= " select order_id, o.status, c.id, c.name, sum(d.order_qty*d.unit_price) as totalAmount"
+ " from o_order o"
+ " join o_customer c on c.id = o.kcustomer_id "
+ " join o_order_detail d on d.order_id = o.id "
+ " group by order_id, o.status, c.id, c.name ";
RawSql rawSql =
RawSqlBuilder
.parse(sql)
.columnMapping("order_id", "order.id")
.columnMapping("o.status", "order.status")
.columnMapping("c.id", "order.customer.id")
.columnMapping("c.name", "order.customer.name")
//.columnMapping("sum(d.order_qty*d.unit_price)", "totalAmount")
.create();
List<OrderAggregate> list2 = Ebean.find(OrderAggregate.class)
.setRawSql(rawSql)
.fetch("order", new FetchConfig().query())
.fetch("order.details", new FetchConfig().query())
.where().gt("order.id", 2)
.having().gt("totalAmount", 10)
.filterMany("order.details").gt("unitPrice", 2d)
.findList();
output(list2);
}
private void output(List<OrderAggregate> list) {
for (OrderAggregate oa : list) {
Double totalAmount = oa.getTotalAmount();
Order order = oa.getOrder();
Integer id = order.getId();
Status status = order.getStatus();
System.out.println("Order: "+id+" "+status+" total:"+totalAmount);
Customer c = order.getCustomer();
System.out.println(" -> customer: "+c.getId()+" "+c.getName());
// invoke lazy loading as this property
// has not populated originally
//order.getOrderDate();
}
}
}
package com.avaje.tests.rawsql;
import java.util.List;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.FetchConfig;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.Order.Status;
import com.avaje.tests.model.basic.OrderAggregate;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestRawSqlOrmWrapper3 extends TestCase {
public void test() {
ResetBasicData.reset();
String sql
= " select order_id, o.status, c.id, c.name, sum(d.order_qty*d.unit_price) as totalAmount"
+ " from o_order o"
+ " join o_customer c on c.id = o.kcustomer_id "
+ " join o_order_detail d on d.order_id = o.id "
+ " group by order_id, o.status, c.id, c.name ";
RawSql rawSql =
RawSqlBuilder
.parse(sql)
.columnMapping("order_id", "order.id")
.columnMapping("o.status", "order.status")
.columnMapping("c.id", "order.customer.id")
.columnMapping("c.name", "order.customer.name")
//.columnMapping("sum(d.order_qty*d.unit_price)", "totalAmount")
.create();
List<OrderAggregate> list2 = Ebean.find(OrderAggregate.class)
.setRawSql(rawSql)
.fetch("order", new FetchConfig().query())
.fetch("order.details", new FetchConfig().query())
.where().gt("order.id", 2)
.having().gt("totalAmount", 10)
.filterMany("order.details").gt("unitPrice", 2d)
.findList();
output(list2);
}
private void output(List<OrderAggregate> list) {
for (OrderAggregate oa : list) {
Double totalAmount = oa.getTotalAmount();
Order order = oa.getOrder();
Integer id = order.getId();
Status status = order.getStatus();
System.out.println("Order: "+id+" "+status+" total:"+totalAmount);
Customer c = order.getCustomer();
System.out.println(" -> customer: "+c.getId()+" "+c.getName());
// invoke lazy loading as this property
// has not populated originally
//order.getOrderDate();
}
}
}
@@ -1,23 +1,23 @@
package com.avaje.tests.rawsql.named;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.FetchConfig;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.OrderAggregate;
import com.avaje.tests.model.basic.ResetBasicData;
import junit.framework.TestCase;
public class TestRawSqlNamedQuery extends TestCase {
public void test(){
ResetBasicData.reset();
Query<OrderAggregate> q = Ebean.createNamedQuery(OrderAggregate.class, "total.amount");
q.fetch("order", new FetchConfig().query());
q.findList();
}
}
package com.avaje.tests.rawsql.named;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.FetchConfig;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.OrderAggregate;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestRawSqlNamedQuery extends TestCase {
public void test(){
ResetBasicData.reset();
Query<OrderAggregate> q = Ebean.createNamedQuery(OrderAggregate.class, "total.amount");
q.fetch("order", new FetchConfig().query());
q.findList();
}
}
@@ -1,39 +1,40 @@
package com.avaje.tests.singleTableInheritance;
import com.avaje.ebean.Ebean;
import com.avaje.tests.singleTableInheritance.model.PalletLocation;
import com.avaje.tests.singleTableInheritance.model.PalletLocationExternal;
import com.avaje.tests.singleTableInheritance.model.Zone;
import com.avaje.tests.singleTableInheritance.model.ZoneExternal;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.util.List;
public class TestInheritQuery extends TestCase {
public void test() {
ZoneExternal zone = new ZoneExternal();
zone.setAttribute("ABC");
Ebean.save(zone);
PalletLocationExternal location = new PalletLocationExternal();
location.setZone(zone);
location.setAttribute("123");
Ebean.save(location);
// This line should work too:
List<PalletLocation> locations = Ebean.find(PalletLocation.class).where().eq("zone", zone).findList();
// List<PalletLocation> locations = Ebean.find(PalletLocation.class).where().eq("zone.id", zone.getId()).findList();
Assert.assertNotNull(locations);
Assert.assertEquals(1, locations.size());
PalletLocation rereadLoc = locations.get(0);
Assert.assertTrue(rereadLoc instanceof PalletLocation);
Zone rereadZone = rereadLoc.getZone();
Assert.assertNotNull(rereadZone);
Assert.assertTrue(rereadZone instanceof ZoneExternal);
}
package com.avaje.tests.singleTableInheritance;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.singleTableInheritance.model.PalletLocation;
import com.avaje.tests.singleTableInheritance.model.PalletLocationExternal;
import com.avaje.tests.singleTableInheritance.model.Zone;
import com.avaje.tests.singleTableInheritance.model.ZoneExternal;
public class TestInheritQuery extends TestCase {
public void test() {
ZoneExternal zone = new ZoneExternal();
zone.setAttribute("ABC");
Ebean.save(zone);
PalletLocationExternal location = new PalletLocationExternal();
location.setZone(zone);
location.setAttribute("123");
Ebean.save(location);
// This line should work too:
List<PalletLocation> locations = Ebean.find(PalletLocation.class).where().eq("zone", zone).findList();
// List<PalletLocation> locations = Ebean.find(PalletLocation.class).where().eq("zone.id", zone.getId()).findList();
Assert.assertNotNull(locations);
Assert.assertEquals(1, locations.size());
PalletLocation rereadLoc = locations.get(0);
Assert.assertTrue(rereadLoc instanceof PalletLocation);
Zone rereadZone = rereadLoc.getZone();
Assert.assertNotNull(rereadZone);
Assert.assertTrue(rereadZone instanceof ZoneExternal);
}
}
@@ -1,21 +1,21 @@
package com.avaje.tests.singleTableInheritance.model;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
@Entity
@DiscriminatorValue("EXT")
public class PalletLocationExternal extends PalletLocation
{
private String attribute;
public String getAttribute()
{
return attribute;
}
public void setAttribute(String attribute)
{
this.attribute = attribute;
}
}
package com.avaje.tests.singleTableInheritance.model;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("EXT")
public class PalletLocationExternal extends PalletLocation
{
private String attribute;
public String getAttribute()
{
return attribute;
}
public void setAttribute(String attribute)
{
this.attribute = attribute;
}
}
@@ -3,13 +3,13 @@ package com.avaje.tests.sp;
import java.util.LinkedList;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.sp.model.car.Car;
import com.avaje.tests.sp.model.car.Wheel;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestManyToManySaveTwice extends TestCase {
public void testNothing() {
@@ -4,8 +4,8 @@ import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@@ -1,47 +1,48 @@
package com.avaje.tests.text.csv;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.text.csv.CsvReader;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
import junit.framework.TestCase;
import java.io.File;
import java.io.FileReader;
import java.util.Locale;
public class TestCsvReader extends TestCase {
public void test() {
ResetBasicData.reset();
try {
File f = new File("src/test/resources/test1.csv");
FileReader reader = new FileReader(f);
CsvReader<Customer> csvReader = Ebean.createCsvReader(Customer.class);
csvReader.setPersistBatchSize(2);
csvReader.addIgnore();
//csvReader.addProperty("id");
csvReader.addProperty("status");
csvReader.addProperty("name");
csvReader.addDateTime("anniversary", "dd-MMM-yyyy", Locale.GERMAN);
csvReader.addProperty("billingAddress.line1");
csvReader.addProperty("billingAddress.city");
csvReader.addReference("billingAddress.country.code");
csvReader.process(reader);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package com.avaje.tests.text.csv;
import java.io.File;
import java.io.FileReader;
import java.util.Locale;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.text.csv.CsvReader;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestCsvReader extends TestCase {
public void test() {
ResetBasicData.reset();
try {
File f = new File("src/test/resources/test1.csv");
FileReader reader = new FileReader(f);
CsvReader<Customer> csvReader = Ebean.createCsvReader(Customer.class);
csvReader.setPersistBatchSize(2);
csvReader.addIgnore();
//csvReader.addProperty("id");
csvReader.addProperty("status");
csvReader.addProperty("name");
csvReader.addDateTime("anniversary", "dd-MMM-yyyy", Locale.GERMAN);
csvReader.addProperty("billingAddress.line1");
csvReader.addProperty("billingAddress.city");
csvReader.addReference("billingAddress.country.code");
csvReader.process(reader);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -1,66 +1,66 @@
package com.avaje.tests.text.json;
import java.sql.Date;
import java.sql.Timestamp;
import org.junit.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebean.text.json.JsonContext;
import com.avaje.ebean.text.json.JsonValueAdapter;
import com.avaje.ebean.text.json.JsonWriteOptions;
import com.avaje.ebeaninternal.server.text.json.DefaultJsonValueAdapter;
import com.avaje.tests.model.basic.Car;
import com.avaje.tests.model.basic.Vehicle;
public class TestTextJsonUtilDateFormat extends TestCase {
public void test() {
GlobalProperties.put("ebean.ddl.generate", "false");
GlobalProperties.put("ebean.ddl.run", "false");
Vehicle v = new Car();
v.setId(100);
v.setRegistrationDate(new java.util.Date());
v.setUpdtime(new Timestamp(System.currentTimeMillis()));
JsonContext context = Ebean.createJsonContext();
JsonWriteOptions o = new JsonWriteOptions();
o.setValueAdapter(new CustomDateFormatAdapter());
String jsonString = context.toJsonString(v, true, o);
System.out.println(jsonString);
Assert.assertTrue(jsonString.contains("\"registrationDate\":'"));
}
class CustomDateFormatAdapter implements JsonValueAdapter {
DefaultJsonValueAdapter defaultImplementation = new DefaultJsonValueAdapter();
public String jsonFromDate(Date date) {
// TODO
return null;
}
public String jsonFromTimestamp(Timestamp date) {
// add some single quotes around the timestamp value
return "'"+defaultImplementation.jsonFromTimestamp(date)+"'";
}
public Date jsonToDate(String jsonDate) {
// TODO
return null;
}
public Timestamp jsonToTimestamp(String jsonDateTime) {
// TODO
return null;
}
}
}
package com.avaje.tests.text.json;
import java.sql.Date;
import java.sql.Timestamp;
import junit.framework.TestCase;
import org.junit.Assert;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.config.GlobalProperties;
import com.avaje.ebean.text.json.JsonContext;
import com.avaje.ebean.text.json.JsonValueAdapter;
import com.avaje.ebean.text.json.JsonWriteOptions;
import com.avaje.ebeaninternal.server.text.json.DefaultJsonValueAdapter;
import com.avaje.tests.model.basic.Car;
import com.avaje.tests.model.basic.Vehicle;
public class TestTextJsonUtilDateFormat extends TestCase {
public void test() {
GlobalProperties.put("ebean.ddl.generate", "false");
GlobalProperties.put("ebean.ddl.run", "false");
Vehicle v = new Car();
v.setId(100);
v.setRegistrationDate(new java.util.Date());
v.setUpdtime(new Timestamp(System.currentTimeMillis()));
JsonContext context = Ebean.createJsonContext();
JsonWriteOptions o = new JsonWriteOptions();
o.setValueAdapter(new CustomDateFormatAdapter());
String jsonString = context.toJsonString(v, true, o);
System.out.println(jsonString);
Assert.assertTrue(jsonString.contains("\"registrationDate\":'"));
}
class CustomDateFormatAdapter implements JsonValueAdapter {
DefaultJsonValueAdapter defaultImplementation = new DefaultJsonValueAdapter();
public String jsonFromDate(Date date) {
// TODO
return null;
}
public String jsonFromTimestamp(Timestamp date) {
// add some single quotes around the timestamp value
return "'"+defaultImplementation.jsonFromTimestamp(date)+"'";
}
public Date jsonToDate(String jsonDate) {
// TODO
return null;
}
public Timestamp jsonToTimestamp(String jsonDateTime) {
// TODO
return null;
}
}
}
@@ -1,28 +1,28 @@
package com.avaje.tests.unitinternal;
import com.avaje.ebean.config.GlobalProperties;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestGlobalPropsEval extends TestCase {
public void test() {
GlobalProperties.put("unitevaltest.1", "one");
Assert.assertEquals("one", GlobalProperties.get("unitevaltest.1",""));
GlobalProperties.put("unitevaltest.2", "a${unitevaltest.1}b");
Assert.assertEquals("aoneb", GlobalProperties.get("unitevaltest.2",""));
GlobalProperties.put("unitevaltest.3", "a${unitevaltest.4}b");
Assert.assertEquals("a${unitevaltest.4}b", GlobalProperties.get("unitevaltest.3",""));
GlobalProperties.put("unitevaltest.4", "four");
Assert.assertEquals("four", GlobalProperties.get("unitevaltest.4",""));
Assert.assertEquals("a${unitevaltest.4}b", GlobalProperties.get("unitevaltest.3",""));
GlobalProperties.evaluateExpressions();
Assert.assertEquals("afourb", GlobalProperties.get("unitevaltest.3",""));
}
}
package com.avaje.tests.unitinternal;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebean.config.GlobalProperties;
public class TestGlobalPropsEval extends TestCase {
public void test() {
GlobalProperties.put("unitevaltest.1", "one");
Assert.assertEquals("one", GlobalProperties.get("unitevaltest.1",""));
GlobalProperties.put("unitevaltest.2", "a${unitevaltest.1}b");
Assert.assertEquals("aoneb", GlobalProperties.get("unitevaltest.2",""));
GlobalProperties.put("unitevaltest.3", "a${unitevaltest.4}b");
Assert.assertEquals("a${unitevaltest.4}b", GlobalProperties.get("unitevaltest.3",""));
GlobalProperties.put("unitevaltest.4", "four");
Assert.assertEquals("four", GlobalProperties.get("unitevaltest.4",""));
Assert.assertEquals("a${unitevaltest.4}b", GlobalProperties.get("unitevaltest.3",""));
GlobalProperties.evaluateExpressions();
Assert.assertEquals("afourb", GlobalProperties.get("unitevaltest.3",""));
}
}
@@ -1,50 +1,50 @@
package com.avaje.tests.unitinternal;
import java.util.Locale;
import com.avaje.ebeaninternal.server.type.ScalarTypeLocale;
import junit.framework.Assert;
import junit.framework.TestCase;
public class TestLocaleParse extends TestCase {
public void test() {
//Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC"
Locale l = parse("en");
Assert.assertEquals("en", l.getLanguage());
l = parse("de_DE");
Assert.assertEquals("de", l.getLanguage());
Assert.assertEquals("DE", l.getCountry());
l = parse("en_US_WIN");
Assert.assertEquals("en", l.getLanguage());
Assert.assertEquals("US", l.getCountry());
Assert.assertEquals("WIN", l.getVariant());
l = parse("_GB");
Assert.assertEquals("", l.getLanguage());
Assert.assertEquals("GB", l.getCountry());
Assert.assertEquals("", l.getVariant());
l = parse("fr__MAC");
Assert.assertEquals("fr", l.getLanguage());
Assert.assertEquals("", l.getCountry());
Assert.assertEquals("MAC", l.getVariant());
l = parse("de__POSIX");
Assert.assertEquals("de", l.getLanguage());
Assert.assertEquals("", l.getCountry());
Assert.assertEquals("POSIX", l.getVariant());
}
private Locale parse(String value){
ScalarTypeLocale st = new ScalarTypeLocale();
return (Locale)st.parse(value);
}
}
package com.avaje.tests.unitinternal;
import java.util.Locale;
import junit.framework.Assert;
import junit.framework.TestCase;
import com.avaje.ebeaninternal.server.type.ScalarTypeLocale;
public class TestLocaleParse extends TestCase {
public void test() {
//Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC"
Locale l = parse("en");
Assert.assertEquals("en", l.getLanguage());
l = parse("de_DE");
Assert.assertEquals("de", l.getLanguage());
Assert.assertEquals("DE", l.getCountry());
l = parse("en_US_WIN");
Assert.assertEquals("en", l.getLanguage());
Assert.assertEquals("US", l.getCountry());
Assert.assertEquals("WIN", l.getVariant());
l = parse("_GB");
Assert.assertEquals("", l.getLanguage());
Assert.assertEquals("GB", l.getCountry());
Assert.assertEquals("", l.getVariant());
l = parse("fr__MAC");
Assert.assertEquals("fr", l.getLanguage());
Assert.assertEquals("", l.getCountry());
Assert.assertEquals("MAC", l.getVariant());
l = parse("de__POSIX");
Assert.assertEquals("de", l.getLanguage());
Assert.assertEquals("", l.getCountry());
Assert.assertEquals("POSIX", l.getVariant());
}
private Locale parse(String value){
ScalarTypeLocale st = new ScalarTypeLocale();
return (Locale)st.parse(value);
}
}
@@ -6,11 +6,11 @@ import java.util.List;
import java.util.Map;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor.EntityType;
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssoc;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocOne;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor.EntityType;
import com.avaje.ebeaninternal.server.el.ElPropertyValue;
import com.avaje.tests.xml.oxm.OxmNode;
import com.avaje.tests.xml.runtime.XoiAttribute;