Compare commits

..
Author SHA1 Message Date
Robin Bygrave 998d8ed6f2 [maven-release-plugin] prepare release avaje-ebeanorm-6.16.3 2016-02-02 13:37:46 +13:00
Robin Bygrave a8da472872 #550 - ENH: Add generated file warning to DB migration XML files 2016-02-02 13:33:46 +13:00
Robin Bygrave a9cdf9736a Bump maven plugin version to 4.9.1 2016-02-02 13:23:46 +13:00
Robin Bygrave c930a1dd6b #549 - Regression: ArrayIndexOutOfBoundsException when lazy loading on bean with inheritance - tidy up 2016-02-02 11:29:38 +13:00
Robin Bygrave 67ce6ef58e #549 - Regression: ArrayIndexOutOfBoundsException when lazy loading on bean with inheritance 2016-02-02 11:24:46 +13:00
Robin Bygrave c4f28efc45 Testing CI - .travis - git depth + skip mvn install 2016-01-28 10:54:16 +13:00
Robin Bygrave afa4bc06d9 Testing CI - .travis - try setup_database 2016-01-28 10:44:14 +13:00
Robin Bygrave 828c9ce128 Testing CI - .travis - try sudo required 2016-01-28 09:31:18 +13:00
Robin Bygrave 6f37a0bd72 Testing CI - .travis - print surefire reports + setup_database script 2016-01-28 09:20:27 +13:00
Robin Bygrave 036086af02 Testing CI - .travis - print surefire reports on failure 2016-01-28 09:00:44 +13:00
Robin Bygrave f34b5e52e0 [maven-release-plugin] prepare for next development iteration 2016-01-28 08:36:40 +13:00
Robin Bygrave a70e289b00 [maven-release-plugin] prepare release avaje-ebeanorm-6.16.2 2016-01-28 08:36:18 +13:00
Robin Bygrave 4ad0e06aab Testing CI - TestEncrypt change to only run against H2 for now 2016-01-27 22:53:06 +13:00
Robin Bygrave 86de7e845e Testing CI - add sql logging for TestEncrypt run on CI server 2016-01-27 22:39:03 +13:00
Robin Bygrave 38501ca372 Modify .travis.yml - add postgres pgcrypto extension 2016-01-27 22:15:39 +13:00
Robin Bygrave 4790c83fa1 Modify .travis.yml - cache .m2 directory 2016-01-27 21:56:00 +13:00
Robin Bygrave b410c83492 Modify .travis.yml for postgres - add hstore and postgis extensions 2016-01-27 21:50:43 +13:00
Robin Bygrave b19145f16f Modify .travis.yml for postgres - add hstore and postgis extensions 2016-01-27 21:46:30 +13:00
Robin Bygrave c28cff2f40 Modify .travis.yml for h2 and postgres runs using EBEAN_DB environment variable 2016-01-27 21:37:57 +13:00
Robin Bygrave 0c8cf78ecc Modify .travis.yml for h2 and postgres runs using EBEAN_DB environment variable 2016-01-27 21:21:01 +13:00
Robin Bygrave df112815ff #545 - ENH: Read environment variable "EBEAN_DB" to set default datasource - typically for CI builds 2016-01-27 21:20:13 +13:00
Robin Bygrave 85522ed8bc Modify .travis.yml for h2 and postgres runs 2016-01-27 20:39:53 +13:00
Robin Bygrave cf88f2375b #544 - Postgres @History DB trigger using current_timestamp (transaction) and should instead use statement_timestamp() 2016-01-27 20:34:51 +13:00
Robin Bygrave 24151f11fd #543 - Tidy up test logging - adjust test LoggedSqlCollector - remove logging noise when running tests 2016-01-27 20:12:36 +13:00
Robin Bygrave 424a83fa0a #543 - Tidy up test logging - adjust test LoggedSqlCollector - remove logging noise when running tests 2016-01-27 19:10:52 +13:00
Robin Bygrave 53dd91416c #543 - Tidy up test logging - adjust test LoggedSqlCollector - remove logging noise when running tests 2016-01-27 19:05:19 +13:00
Robin Bygrave 5a463c5071 #543 - Tidy up test logging - adjust test LoggedSqlCollector - remove trace level logging when running tests 2016-01-27 18:25:54 +13:00
Robin Bygrave bc3cf1348a #543 - Tidy up test logging - adjust test LoggedSqlCollector 2016-01-27 18:25:16 +13:00
Robin Bygrave f3b1024283 Fix for test asserts to run against Postgres with escape clause on LIKE expression 2016-01-27 17:22:55 +13:00
Robin Bygrave 7ba35d7a62 Update .travis - postgres service 2016-01-27 16:17:45 +13:00
Robin Bygrave 990ca2980b Add initial .travis.yml 2016-01-27 16:05:33 +13:00
Robin Bygrave 38dd3d82fc #536 - @ManyToOne with @JoinColumn throw error - Update tests 2016-01-26 16:41:15 +13:00
Robin Bygrave 6be26aaff2 #537 - Change PersistenceException: Mapping limitation on @JoinColumn such that it includes the bean type 2016-01-26 15:30:57 +13:00
Robin Bygrave d1462b032a #535 - Bean lazy loading can execute an extra query when one of the lazy loaded beans has been deleted 2016-01-21 20:51:45 +13:00
Robin Bygrave 6ab974a330 #535 - Bean lazy loading can execute an extra query when one of the lazy loaded beans has been deleted 2016-01-21 20:51:32 +13:00
Robin Bygrave 64618da6a7 #534 - REFACTOR: Internals for lazy loading specifically improving errors/logging in cases of lazy load errors due to deletes - Update debug logging for LoadManyRequest when empty collection found (expected frequently) 2016-01-21 17:52:23 +13:00
Robin Bygrave d242ff7351 #534 - REFACTOR: Internals for lazy loading specifically improving errors/logging in cases of lazy load errors due to deletes - Initial refactor for LoadManyRequest 2016-01-21 17:30:49 +13:00
Robin Bygrave 7d54aaa9a7 #534 - REFACTOR: Internals for lazy loading specifically improving errors/logging in cases of lazy load errors due to deletes - Initial refactor 2016-01-21 16:50:51 +13:00
Robin Bygrave 0e46184656 No effective change - Rename test class 2016-01-21 16:03:51 +13:00
Robin Bygrave c9e1a6edbd Bump agent to 4.9.1 2016-01-20 15:13:11 +13:00
Robin Bygrave 3c0cffd146 [maven-release-plugin] prepare for next development iteration 2016-01-19 19:49:31 +13:00
94 changed files with 633 additions and 494 deletions
+32
View File
@@ -0,0 +1,32 @@
sudo: required
language: java
jdk:
- oraclejdk8
git:
depth: 3
addons:
postgresql: "9.4"
services:
- postgresql
before_script:
- ./.travis/setup_database
env:
- EBEAN_DB=h2
- EBEAN_DB=pg
install: true
script:
- mvn clean test
after_failure:
- ./.travis/print_surefire_reports
cache:
directories:
- $HOME/.m2
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
echo "\n=== SUREFIRE REPORTS ===\n"
for file in target/surefire-reports/*.txt
do
echo ${file}
cat ${file}
echo
done
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
echo "\n=== SETUP DATABASE ===\n"
#set -e
#set -x
# Setup postgres' users and databases
sudo -u postgres psql -c "CREATE USER unit WITH PASSWORD 'unit';"
sudo -u postgres psql -c 'CREATE DATABASE unit WITH OWNER unit;'
sudo -u postgres psql unit -c 'CREATE EXTENSION hstore;'
sudo -u postgres psql unit -c 'CREATE EXTENSION pgcrypto;'
#sudo -u postgres psql test2 -c 'CREATE EXTENSION postgis;'
+3 -3
View File
@@ -9,7 +9,7 @@
<groupId>org.avaje.ebeanorm</groupId>
<artifactId>avaje-ebeanorm</artifactId>
<version>6.16.1</version>
<version>6.16.3</version>
<packaging>jar</packaging>
<name>avaje-ebeanorm</name>
@@ -152,7 +152,7 @@
<dependency>
<groupId>org.avaje.ebeanorm</groupId>
<artifactId>avaje-ebeanorm-agent</artifactId>
<version>4.8.1</version>
<version>4.9.1</version>
<scope>test</scope>
</dependency>
@@ -219,7 +219,7 @@
<plugin>
<groupId>org.avaje.ebeanorm</groupId>
<artifactId>avaje-ebeanorm-mavenenhancer</artifactId>
<version>4.8.1</version>
<version>4.9.1</version>
<executions>
<!-- Not going to enhance Model bean -->
<execution>
@@ -58,15 +58,18 @@ class PrimaryServer {
*/
private static String determineDefaultServerName() {
String defaultServerName = System.getProperty("datasource.default");
String defaultServerName = System.getenv("EBEAN_DB");
if (isEmpty(defaultServerName)) {
defaultServerName = System.getProperty("ebean.default.datasource");
}
if (isEmpty(defaultServerName)) {
defaultServerName = globalProperties.getProperty("datasource.default");
}
if (isEmpty(defaultServerName)) {
defaultServerName = globalProperties.getProperty("ebean.default.datasource");
defaultServerName = System.getProperty("datasource.default");
if (isEmpty(defaultServerName)) {
defaultServerName = System.getProperty("ebean.default.datasource");
if (isEmpty(defaultServerName)) {
defaultServerName = globalProperties.getProperty("datasource.default");
if (isEmpty(defaultServerName)) {
defaultServerName = globalProperties.getProperty("ebean.default.datasource");
}
}
}
}
return defaultServerName;
}
@@ -1,5 +1,10 @@
package com.avaje.ebean.bean;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.ValuePair;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
@@ -11,12 +16,6 @@ import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceException;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.ValuePair;
/**
* This is the object added to every entity bean using byte code enhancement.
* <p>
@@ -92,6 +91,8 @@ public final class EntityBeanIntercept implements Serializable {
private int lazyLoadProperty = -1;
private Object ownerId;
/**
* Create a intercept with a given entity.
* <p>
@@ -342,18 +343,11 @@ public final class EntityBeanIntercept implements Serializable {
}
/**
* Check if the lazy load succeeded. If not then mark this bean as having
* failed lazy loading due to the underlying row being deleted.
* <p>
* We mark the bean this way rather than immediately fail as we might be batch
* lazy loading and this bean might not be used by the client code at all.
* Instead we will fail as soon as the client code tries to use this bean.
* </p>
* Set lazy load failure flag.
*/
public void checkLazyLoadFailure() {
if (lazyLoadProperty != -1) {
this.lazyLoadFailure = true;
}
public void setLazyLoadFailure(Object ownerId) {
this.lazyLoadFailure = true;
this.ownerId = ownerId;
}
/**
@@ -748,7 +742,7 @@ public final class EntityBeanIntercept implements Serializable {
if (lazyLoadFailure) {
// failed when batch lazy loaded by another bean in the batch
throw new EntityNotFoundException("Bean has been deleted - lazy loading failed");
throw new EntityNotFoundException("Lazy loading failed on type:" + owner.getClass().getName() + " id:" + ownerId + " - Bean has been deleted");
}
if (lazyLoadProperty == -1) {
@@ -763,7 +757,7 @@ public final class EntityBeanIntercept implements Serializable {
if (lazyLoadFailure) {
// failed when lazy loading this bean
throw new EntityNotFoundException("Bean has been deleted - lazy loading failed");
throw new EntityNotFoundException("Lazy loading failed on type:" + owner.getClass().getName() + " id:" + ownerId + " - Bean has been deleted.");
}
// bean should be loaded and intercepting now. setLoaded() has
@@ -88,6 +88,8 @@ public class DbMigrationConfig {
protected String modelSuffix = ".model.xml";
protected boolean includeGeneratedFileComment;
/**
* Return the DB platform to generate migration DDL for.
*
@@ -236,6 +238,20 @@ public class DbMigrationConfig {
this.rollbackSuffix = rollbackSuffix;
}
/**
* Return true if the generated file comment should be included.
*/
public boolean isIncludeGeneratedFileComment() {
return includeGeneratedFileComment;
}
/**
* Set to true if the generated file comment should be included.
*/
public void setIncludeGeneratedFileComment(boolean includeGeneratedFileComment) {
this.includeGeneratedFileComment = includeGeneratedFileComment;
}
/**
* Set the migration version.
* <p>
@@ -281,6 +297,7 @@ public class DbMigrationConfig {
dropSuffix = properties.get("migration.dropSuffix", dropSuffix);
rollbackSuffix = properties.get("migration.rollbackSuffix", rollbackSuffix);
modelSuffix = properties.get("migration.modelSuffix", modelSuffix);
includeGeneratedFileComment = properties.getBoolean("migration.includeGeneratedFileComment", includeGeneratedFileComment);
platform = properties.getEnum(DbPlatformName.class, "migration.platform", platform);
suppressRollback = properties.getBoolean("migration.suppressRollback", suppressRollback);
@@ -59,6 +59,8 @@ public class DbMigration {
private static final String initialVersion = "1.0";
private static final String GENERATED_COMMENT = "THIS IS A GENERATED FILE - DO NOT MODIFY";
/**
* Set to true if DbMigration run with online EbeanServer instance.
*/
@@ -304,7 +306,8 @@ public class DbMigration {
if (file.exists()) {
return false;
}
MigrationXmlWriter xmlWriter = new MigrationXmlWriter();
String comment = migrationConfig.isIncludeGeneratedFileComment() ? GENERATED_COMMENT : null;
MigrationXmlWriter xmlWriter = new MigrationXmlWriter(comment);
xmlWriter.write(dbMigration, file);
return true;
}
@@ -14,7 +14,7 @@ public class PostgresHistoryDdl extends DbTriggerBasedHistoryDdl {
public PostgresHistoryDdl() {
this.currentTimestamp = "current_timestamp";
this.currentTimestamp = "statement_timestamp()";
}
/**
@@ -80,7 +80,7 @@ public class PostgresHistoryDdl extends DbTriggerBasedHistoryDdl {
.append(" if (TG_OP = 'UPDATE') then").newLine();
appendInsertIntoHistory(apply, historyTable, includedColumns);
apply
.append(" NEW.").append(sysPeriod).append(" = tstzrange(CURRENT_TIMESTAMP,null);").newLine()
.append(" NEW.").append(sysPeriod).append(" = tstzrange(").append(currentTimestamp).append(",null);").newLine()
.append(" return new;").newLine();
apply
.append(" elsif (TG_OP = 'DELETE') then").newLine();
@@ -137,7 +137,7 @@ public class PostgresHistoryDdl extends DbTriggerBasedHistoryDdl {
buffer.append(" insert into ").append(historyTable).append(" (").append(sysPeriod).append(",");
appendColumnNames(buffer, columns, "");
buffer.append(") values (tstzrange(lower(OLD.").append(sysPeriod).append("), current_timestamp), ");
buffer.append(") values (tstzrange(lower(OLD.").append(sysPeriod).append("), ").append(currentTimestamp).append("), ");
appendColumnNames(buffer, columns, "OLD.");
buffer.append(");").newLine();
}
@@ -7,22 +7,46 @@ import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* Simple writer for output of the Migration/ChangeSet as an XML document.
*/
public class MigrationXmlWriter {
private final String comment;
public MigrationXmlWriter(String comment) {
this.comment = comment;
}
/**
* Write a Migration to a file as an xml document to the file.
*/
public void write(Migration migration, File file) {
try {
FileWriter writer = new FileWriter(file);
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
if (comment != null) {
writer.write("<!-- ");
writer.write(comment);
writer.write(" -->\n");
}
JAXBContext jaxbContext = JAXBContext.newInstance(Migration.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(migration, file);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.marshal(migration, writer);
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (JAXBException e) {
throw new RuntimeException(e);
@@ -1,18 +1,27 @@
package com.avaje.ebeaninternal.api;
import java.util.List;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Request for loading ManyToOne and OneToOne relationships.
*/
public class LoadBeanRequest extends LoadRequest {
private static final Logger logger = LoggerFactory.getLogger(LoadBeanRequest.class);
private final List<EntityBeanIntercept> batch;
private final LoadBeanBuffer LoadBuffer;
private final LoadBeanBuffer loadBuffer;
private final String lazyLoadProperty;
@@ -32,20 +41,28 @@ public class LoadBeanRequest extends LoadRequest {
this(LoadBuffer, parentRequest, false, null, false);
}
private LoadBeanRequest(LoadBeanBuffer LoadBuffer, OrmQueryRequest<?> parentRequest, boolean lazy, String lazyLoadProperty, boolean loadCache) {
private LoadBeanRequest(LoadBeanBuffer loadBuffer, OrmQueryRequest<?> parentRequest, boolean lazy,
String lazyLoadProperty, boolean loadCache) {
super(parentRequest, lazy);
this.LoadBuffer = LoadBuffer;
this.batch = LoadBuffer.getBatch();
this.loadBuffer = loadBuffer;
this.batch = loadBuffer.getBatch();
this.lazyLoadProperty = lazyLoadProperty;
this.loadCache = loadCache;
}
@Override
public Class<?> getBeanType() {
return loadBuffer.getBeanDescriptor().getBeanType();
}
public boolean isLoadCache() {
return loadCache;
}
public String getDescription() {
return "path:" + LoadBuffer.getFullPath() + " batch:" + batch.size();
return "path:" + loadBuffer.getFullPath() + " batch:" + batch.size();
}
/**
@@ -59,7 +76,7 @@ public class LoadBeanRequest extends LoadRequest {
* Return the load context.
*/
public LoadBeanBuffer getLoadContext() {
return LoadBuffer;
return loadBuffer;
}
/**
@@ -72,4 +89,90 @@ public class LoadBeanRequest extends LoadRequest {
public int getBatchSize() {
return getLoadContext().getBatchSize();
}
/**
* Return the list of Id values for the beans in the lazy load buffer.
*/
public List<Object> getIdList(int batchSize) {
List<Object> idList = new ArrayList<Object>(batchSize);
BeanDescriptor<?> desc = loadBuffer.getBeanDescriptor();
for (int i = 0; i < batch.size(); i++) {
EntityBeanIntercept ebi = batch.get(i);
EntityBean bean = ebi.getOwner();
idList.add(desc.getId(bean));
}
if (!idList.isEmpty()) {
int extraIds = batchSize - batch.size();
if (extraIds > 0) {
// for performance make up the Id's to the batch size
// so we get the same query (for Ebean and the db)
Object firstId = idList.get(0);
for (int i = 0; i < extraIds; i++) {
// just add the first Id again
idList.add(firstId);
}
}
}
return idList;
}
/**
* Configure the query for lazy loading execution.
*/
public void configureQuery(SpiQuery<?> query, List<Object> idList) {
query.setMode(SpiQuery.Mode.LAZYLOAD_BEAN);
query.setPersistenceContext(loadBuffer.getPersistenceContext());
String mode = isLazy() ? "+lazy" : "+query";
query.setLoadDescription(mode, getDescription());
if (isLazy()) {
// cascade the batch size (if set) for further lazy loading
query.setLazyLoadBatchSize(getBatchSize());
}
loadBuffer.configureQuery(query, lazyLoadProperty);
if (idList.size() == 1) {
query.where().idEq(idList.get(0));
} else {
query.where().idIn(idList);
}
}
/**
* Load the beans into the L2 cache if that is requested and check for load failures due to deletes.
*/
public void postLoad(List<?> list) {
Set<Object> loadedIds = new HashSet<Object>();
BeanDescriptor<?> desc = loadBuffer.getBeanDescriptor();
// collect Ids and maybe load bean cache
for (int i = 0; i < list.size(); i++) {
EntityBean loadedBean = (EntityBean) list.get(i);
loadedIds.add(desc.getId(loadedBean));
if (isLoadCache()) {
desc.cacheBeanPutData(loadedBean);
}
}
if (lazyLoadProperty != null) {
for (int i = 0; i < batch.size(); i++) {
// check if the underlying row in DB was deleted. Mark the bean as 'failed' if
// necessary but allow processing to continue until it is accessed by client code
EntityBeanIntercept ebi = batch.get(i);
Object id = desc.getId(ebi.getOwner());
if (!loadedIds.contains(id)) {
logger.info("Lazy loading unsuccessful for type:" + desc.getName() + " id:" + id + " - expecting when bean has been deleted");
ebi.setLazyLoadFailure(id);
}
}
}
}
}
@@ -1,15 +1,25 @@
package com.avaje.ebeaninternal.api;
import java.util.List;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebeaninternal.server.core.OrmQueryRequest;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Request for loading Associated Many Beans.
*/
public class LoadManyRequest extends LoadRequest {
private static final Logger logger = LoggerFactory.getLogger(LoadManyRequest.class);
private final List<BeanCollection<?>> batch;
private final LoadManyBuffer loadContext;
@@ -40,6 +50,11 @@ public class LoadManyRequest extends LoadRequest {
this.loadCache = loadCache;
}
@Override
public Class<?> getBeanType() {
return loadContext.getBeanDescriptor().getBeanType();
}
public String getDescription() {
return "path:" + loadContext.getFullPath() + " size:" + batch.size();
}
@@ -83,4 +98,98 @@ public class LoadManyRequest extends LoadRequest {
public int getBatchSize() {
return loadContext.getBatchSize();
}
private List<Object> getParentIdList(int batchSize) {
ArrayList<Object> idList = new ArrayList<Object>(batchSize);
BeanPropertyAssocMany<?> many = getMany();
for (int i = 0; i < batch.size(); i++) {
BeanCollection<?> bc = batch.get(i);
idList.add(many.getParentId(bc.getOwnerBean()));
}
int extraIds = batchSize - batch.size();
if (extraIds > 0) {
Object firstId = idList.get(0);
for (int i = 0; i < extraIds; i++) {
idList.add(firstId);
}
}
return idList;
}
private BeanPropertyAssocMany<?> getMany() {
return loadContext.getBeanProperty();
}
public SpiQuery<?> createQuery(EbeanServer server, int batchSize) {
BeanPropertyAssocMany<?> many = getMany();
SpiQuery<?> query = (SpiQuery<?>) server.createQuery(many.getTargetType());
String orderBy = many.getLazyFetchOrderBy();
if (orderBy != null) {
query.orderBy(orderBy);
}
String extraWhere = many.getExtraWhere();
if (extraWhere != null) {
// replace special ${ta} placeholder with the base table alias
// which is always t0 and add the extra where clause
String ew = StringHelper.replaceString(extraWhere, "${ta}", "t0");
query.where().raw(ew);
}
query.setLazyLoadForParents(many);
List<Object> idList = getParentIdList(batchSize);
many.addWhereParentIdIn(query, idList);
query.setPersistenceContext(loadContext.getPersistenceContext());
String mode = isLazy() ? "+lazy" : "+query";
query.setLoadDescription(mode, getDescription());
if (isLazy()) {
// cascade the batch size (if set) for further lazy loading
query.setLazyLoadBatchSize(getBatchSize());
}
// potentially changes the joins and selected properties
loadContext.configureQuery(query);
if (isOnlyIds()) {
// override to just select the Id values
query.select(many.getTargetIdProperty());
}
return query;
}
/**
* After the query execution check for empty collections and load L2 cache if desired.
*/
public void postLoad() {
BeanDescriptor<?> desc = loadContext.getBeanDescriptor();
BeanPropertyAssocMany<?> many = getMany();
// check for BeanCollection's that where never processed
// in the +query or +lazy load due to no rows (predicates)
for (int i = 0; i < batch.size(); i++) {
BeanCollection<?> bc = batch.get(i);
if (bc.checkEmptyLazyLoad()) {
if (logger.isDebugEnabled()) {
EntityBean ownerBean = bc.getOwnerBean();
Object parentId = desc.getId(ownerBean);
logger.debug("BeanCollection after lazy load was empty. type:" + ownerBean.getClass().getName() + " id:" + parentId + " owner:" + ownerBean);
}
} else if (isLoadCache()) {
Object parentId = desc.getId(bc.getOwnerBean());
desc.cacheManyPropPut(many, bc, parentId);
}
}
}
}
@@ -21,6 +21,11 @@ public abstract class LoadRequest {
this.lazy = lazy;
}
/**
* Return the associated bean type for this load request.
*/
public abstract Class<?> getBeanType();
/**
* Log the just executed secondary query with the 'root' query if 'logSecondaryQuery' is set to
* true. This is for testing purposes to confirm the secondary query executes etc.
@@ -6,23 +6,20 @@ import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebean.bean.PersistenceContext;
import com.avaje.ebeaninternal.api.LoadBeanBuffer;
import com.avaje.ebeaninternal.api.LoadBeanRequest;
import com.avaje.ebeaninternal.api.LoadManyBuffer;
import com.avaje.ebeaninternal.api.LoadManyRequest;
import com.avaje.ebeaninternal.api.LoadRequest;
import com.avaje.ebeaninternal.api.SpiQuery;
import com.avaje.ebeaninternal.api.SpiQuery.Mode;
import com.avaje.ebeaninternal.api.SpiTransaction;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor.EntityType;
import com.avaje.ebeaninternal.server.deploy.BeanPropertyAssocMany;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
import com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityNotFoundException;
import java.util.ArrayList;
import java.util.List;
/**
@@ -86,89 +83,11 @@ public class DefaultBeanLoader {
int batchSize = getBatchSize(batch.size());
LoadManyBuffer ctx = loadRequest.getLoadContext();
BeanPropertyAssocMany<?> many = ctx.getBeanProperty();
SpiQuery<?> query = loadRequest.createQuery(server, batchSize);
PersistenceContext pc = ctx.getPersistenceContext();
executeQuery(loadRequest, query);
ArrayList<Object> idList = new ArrayList<Object>(batchSize);
for (int i = 0; i < batch.size(); i++) {
BeanCollection<?> bc = batch.get(i);
EntityBean ownerBean = bc.getOwnerBean();
Object id = many.getParentId(ownerBean);
idList.add(id);
}
int extraIds = batchSize - batch.size();
if (extraIds > 0) {
Object firstId = idList.get(0);
for (int i = 0; i < extraIds; i++) {
idList.add(firstId);
}
}
BeanDescriptor<?> desc = ctx.getBeanDescriptor();
SpiQuery<?> query = (SpiQuery<?>) server.createQuery(many.getTargetType());
String orderBy = many.getLazyFetchOrderBy();
if (orderBy != null) {
query.orderBy(orderBy);
}
String extraWhere = many.getExtraWhere();
if (extraWhere != null) {
// replace special ${ta} placeholder with the base table alias
// which is always t0 and add the extra where clause
String ew = StringHelper.replaceString(extraWhere, "${ta}", "t0");
query.where().raw(ew);
}
query.setLazyLoadForParents(many);
many.addWhereParentIdIn(query, idList);
query.setPersistenceContext(pc);
String mode = loadRequest.isLazy() ? "+lazy" : "+query";
query.setLoadDescription(mode, loadRequest.getDescription());
if (loadRequest.isLazy()) {
// cascade the batch size (if set) for further lazy loading
query.setLazyLoadBatchSize(loadRequest.getBatchSize());
}
// potentially changes the joins and selected properties
ctx.configureQuery(query);
if (loadRequest.isOnlyIds()) {
// override to just select the Id values
query.select(many.getTargetIdProperty());
}
if (onIterateUseExtraTxn && loadRequest.isParentFindIterate()) {
// MySql - we need a different transaction to execute the secondary query
SpiTransaction extraTxn = server.createQueryTransaction();
try {
server.findList(query, extraTxn);
} finally {
extraTxn.end();
}
} else {
server.findList(query, loadRequest.getTransaction());
}
// check for BeanCollection's that where never processed
// in the +query or +lazy load due to no rows (predicates)
for (int i = 0; i < batch.size(); i++) {
BeanCollection<?> bc = batch.get(i);
if (bc.checkEmptyLazyLoad()) {
if (logger.isDebugEnabled()) {
logger.debug("BeanCollection after load was empty. Owner:" + batch.get(i).getOwnerBean());
}
} else if (loadRequest.isLoadCache()) {
Object parentId = desc.getId(bc.getOwnerBean());
desc.cacheManyPropPut(many, bc, parentId);
}
}
loadRequest.postLoad();
// log the query (for testing secondary queries)
loadRequest.logSecondaryQuery(query);
@@ -274,96 +193,43 @@ public class DefaultBeanLoader {
public void loadBean(LoadBeanRequest loadRequest) {
List<EntityBeanIntercept> batch = loadRequest.getBatch();
if (batch.isEmpty()) {
throw new RuntimeException("Nothing in batch?");
}
int batchSize = getBatchSize(batch.size());
LoadBeanBuffer ctx = loadRequest.getLoadContext();
BeanDescriptor<?> desc = ctx.getBeanDescriptor();
Class<?> beanType = desc.getBeanType();
EntityBeanIntercept[] ebis = batch.toArray(new EntityBeanIntercept[batch.size()]);
ArrayList<Object> idList = new ArrayList<Object>(batchSize);
for (int i = 0; i < batch.size(); i++) {
EntityBeanIntercept ebi = batch.get(i);
EntityBean bean = ebi.getOwner();
Object id = desc.getId(bean);
idList.add(id);
}
List<Object> idList = loadRequest.getIdList(batchSize);
if (idList.isEmpty()) {
// everything was loaded from cache
return;
}
int extraIds = batchSize - batch.size();
if (extraIds > 0) {
// for performance make up the Id's to the batch size
// so we get the same query (for Ebean and the db)
Object firstId = idList.get(0);
for (int i = 0; i < extraIds; i++) {
// just add the first Id again
idList.add(firstId);
}
}
SpiQuery<?> query = (SpiQuery<?>) server.createQuery(loadRequest.getBeanType());
loadRequest.configureQuery(query, idList);
PersistenceContext persistenceContext = ctx.getPersistenceContext();
List<?> list = executeQuery(loadRequest, query);
loadRequest.postLoad(list);
SpiQuery<?> query = (SpiQuery<?>) server.createQuery(beanType);
// log the query (for testing secondary queries)
loadRequest.logSecondaryQuery(query);
}
query.setMode(Mode.LAZYLOAD_BEAN);
query.setPersistenceContext(persistenceContext);
String mode = loadRequest.isLazy() ? "+lazy" : "+query";
query.setLoadDescription(mode, loadRequest.getDescription());
if (loadRequest.isLazy()) {
// cascade the batch size (if set) for further lazy loading
query.setLazyLoadBatchSize(loadRequest.getBatchSize());
}
ctx.configureQuery(query, loadRequest.getLazyLoadProperty());
// make sure the query doesn't use the cache
// query.setUseCache(false);
if (idList.size() == 1) {
query.where().idEq(idList.get(0));
} else {
query.where().idIn(idList);
}
List<?> list;
/**
* Execute the lazy load query taking into account MySql transaction oddness.
*/
private List<?> executeQuery(LoadRequest loadRequest, SpiQuery<?> query) {
if (onIterateUseExtraTxn && loadRequest.isParentFindIterate()) {
// MySql - we need a different transaction to execute the secondary query
SpiTransaction extraTxn = server.createQueryTransaction();
try {
list = server.findList(query, extraTxn);
return server.findList(query, extraTxn);
} finally {
extraTxn.end();
}
} else {
list = server.findList(query, loadRequest.getTransaction());
return server.findList(query, loadRequest.getTransaction());
}
if (loadRequest.isLoadCache()) {
for (int i = 0; i < list.size(); i++) {
desc.cacheBeanPutData((EntityBean) list.get(i));
}
}
for (int i = 0; i < ebis.length; i++) {
// Check if the underlying row in DB was deleted. Mark this bean as 'failed' if
// necessary but allow processing to continue until it is accessed by client code
ebis[i].checkLazyLoadFailure();
}
// log the query (for testing secondary queries)
loadRequest.logSecondaryQuery(query);
}
public void refresh(EntityBean bean) {
@@ -107,7 +107,7 @@ public class BeanPropertyAssocOne<T> extends BeanPropertyAssoc<T> {
String foreignJoinColumn = columns[0].getForeignDbColumn();
String foreignIdColumn = targetDescriptor.getIdProperty().getDbColumn();
if (!foreignJoinColumn.equalsIgnoreCase(foreignIdColumn)) {
throw new PersistenceException("Mapping limitation - @OneToOne @JoinColumn needs to map to a primary key as per Issue #529 "
throw new PersistenceException("Mapping limitation - @JoinColumn on " + getFullBeanName() + " needs to map to a primary key as per Issue #529 "
+ " - joining to " + foreignJoinColumn + " and not " + foreignIdColumn);
}
}
@@ -24,4 +24,9 @@ public class BaseTestCase {
SpiEbeanServer spi = (SpiEbeanServer)Ebean.getDefaultServer();
return spi.getDatabasePlatform().getName().startsWith("mssqlserver");
}
public boolean isH2() {
SpiEbeanServer spi = (SpiEbeanServer)Ebean.getDefaultServer();
return spi.getDatabasePlatform().getName().equals("h2");
}
}
@@ -30,7 +30,6 @@ public class PrimaryServerTest {
public void testLoadProperties() throws Exception {
Properties properties = PrimaryServer.getProperties();
System.out.println(properties);
assertTrue(properties.size() > 0);
}
}
@@ -2,25 +2,33 @@ package com.avaje.ebean.dbmigration.migrationreader;
import com.avaje.ebean.dbmigration.migration.Migration;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class MigrationXmlWriterTest {
import static org.assertj.core.api.Assertions.assertThat;
Logger logger = LoggerFactory.getLogger(MigrationXmlWriterTest.class);
public class MigrationXmlWriterTest {
@Test
public void testReadWrite() throws Exception {
Migration migration = MigrationXmlReader.read("/container/test-create-table.xml");
assertThat(migration.getChangeSet()).hasSize(1);
assertThat(migration.getChangeSet().get(0).getChangeSetChildren()).hasSize(3);
File temp = File.createTempFile("migrationWrite",".xml");
MigrationXmlWriter writer = new MigrationXmlWriter();
writer.write(migration, temp);
new MigrationXmlWriter("THIS IS A GENERATED FILE - DO NOT MODIFY").write(migration, temp);
logger.info("wrote migration file: "+temp.getAbsolutePath());
Migration migrationRead = MigrationXmlReader.read(temp);
assertThat(migrationRead.getChangeSet()).hasSize(1);
assertThat(migrationRead.getChangeSet().get(0).getChangeSetChildren()).hasSize(3);
temp = File.createTempFile("migrationWrite",".xml");
new MigrationXmlWriter(null).write(migration, temp);
Migration migrationRead2 = MigrationXmlReader.read(temp);
assertThat(migrationRead2.getChangeSet()).hasSize(1);
assertThat(migrationRead.getChangeSet().get(0).getChangeSetChildren()).hasSize(3);
}
}
@@ -61,11 +61,8 @@ public class TestBasicPush extends BaseTestCase {
generator.close();
String json = writer.toString();
System.out.println(json);
String response = post("http://localhost:9200/_bulk", json);
System.out.println(response);
post("http://localhost:9200/_bulk", json);
//curl -s -XPOST localhost:9200/_bulk
@@ -30,7 +30,7 @@ public class ChangeJsonBuilderTest extends BaseTestCase {
for (int i = 0; i < changes.size(); i++) {
StringWriter buffer = new StringWriter();
builder.writeBeanJson(buffer, changes.get(i), changeSet, i);
System.out.println(buffer.toString());
assertThat(buffer.toString()).contains("\"source\"");
assertThat(buffer.toString()).contains("\"userId\"");
assertThat(buffer.toString()).contains("\"userIpAddress\"");
@@ -19,8 +19,6 @@ public class DeployPropertyParserMapTests {
DeployPropertyParserMap parser = new DeployPropertyParserMap(map);
String output = parser.parse("(lower(customer.name) like ? escape'' or id > ?)");
System.out.println(output);
Assert.assertEquals("(lower(t1.name) like ? escape'' or t0.id > ?)", output);
}
@@ -61,7 +61,8 @@ public class DefaultExampleExpressionTest extends BaseTestCase {
query1.findList();
assertThat(query1.getGeneratedSql()).contains("(t0.name like ? and t1.city like ? )");
assertThat(query1.getGeneratedSql()).contains("(t0.name like ? ");
assertThat(query1.getGeneratedSql()).contains(" and t1.city like ? ");
}
@@ -49,8 +49,6 @@ public class TestDataSourceMax extends BaseTestCase {
bg.execute(new ConnRunner(pool, 4000, i));
}
System.out.println("main thread sleep ... " + pool.getStatus(false));
Thread.sleep(10000);
pool.getStatistics(true);
@@ -81,9 +79,7 @@ public class TestDataSourceMax extends BaseTestCase {
private void waitSomeTime(long count) {
try {
System.out.println(position+" sleep " + sleepMillis+" count:"+count);
Thread.sleep(sleepMillis);
System.out.println(position+" sleep done");
} catch (InterruptedException e){
throw new RuntimeException(e);
}
@@ -30,9 +30,6 @@ public class TestDataSourceMaxWithEntity extends BaseTestCase {
bg.execute(new ConnRunner(server, 4000, i));
}
System.out.println("main thread sleep ... ");
Thread.sleep(30000);
server.shutdown(true, false);
@@ -24,7 +24,6 @@ public class TestRawSqlParsing extends TestCase {
Sql rs = rawSql.getSql();
String s = rs.toString();
System.out.println(s);
assertTrue(s, s.contains("[order_id, sum"));
}
@@ -42,7 +42,6 @@ public class TestJsonWriteVisitor extends BaseTestCase {
options.setPathVisitor("contacts", new ContactVisitor());
String jsonContent = json.toJson(list, options);
System.out.println(jsonContent);
assertThat(jsonContent).contains("customerExtra");
assertThat(jsonContent).contains("contactExtra");
@@ -42,14 +42,11 @@ public class TestTextJsonBeanReadVisitor extends BaseTestCase {
options.addVisitor("shippingAddress", new ASVisitor());
String s = json.toJson(list);
System.out.println(s);
List<Customer> mList = json.toList(Customer.class, s, options);
System.out.println("VIA STRING: " + mList);
StringReader reader = new StringReader(s);
List<Customer> mList2 = json.toList(Customer.class, reader);
System.out.println("VIA READER: " + mList2);
assertEquals(mList.size(), mList2.size());
}
@@ -58,28 +55,28 @@ public class TestTextJsonBeanReadVisitor extends BaseTestCase {
@Override
public void visit(Customer bean, Map<String, Object> unmapped) {
System.out.println("visit customer: " + bean);
bean.getId();
}
}
private static class AVisitor implements JsonReadBeanVisitor<Address> {
public void visit(Address bean, Map<String, Object> unmapped) {
System.out.println("visit billing address: " + bean);
bean.getId();
}
}
private static class ASVisitor implements JsonReadBeanVisitor<Address> {
public void visit(Address bean, Map<String, Object> unmapped) {
System.out.println("visit shipping address: " + bean);
bean.getId();
}
}
private static class ContactVisitor implements JsonReadBeanVisitor<Contact> {
public void visit(Contact bean, Map<String, Object> unmapped) {
System.out.println("visit contact: " + bean);
bean.getId();
}
}
}
@@ -17,8 +17,6 @@ public class ScalarTypeLocalDateTest {
LocalDate date = LocalDate.of(2014, 5, 20);
long millis = type.convertToMillis(date);
System.out.println(date);
LocalDate parseDate = type.convertFromMillis(millis);
assertEquals(date, parseDate);
}
@@ -27,7 +27,8 @@ public class MainAutoQueryTune1 {
.findList();
for (Order order : list) {
System.out.println(order.getId() + " " + order.getOrderDate());
order.getId();
order.getOrderDate();
}
}
}
@@ -16,8 +16,7 @@ public class TestBatchLazyMany extends BaseTestCase {
Order order2 = Ebean.getReference(Order.class, 1);
order2.getOrderDate();
System.out.println("done");
// List<Order> list = Ebean.find(Order.class)
// //.join("details")
// //.join("details", "+fetchquery")
@@ -47,8 +47,6 @@ public class TestBeanReferenceRefresh extends BaseTestCase {
Status statusRefresh = order.getStatus();
Assert.assertEquals(status,statusRefresh);
System.out.println("done");
}
@@ -24,7 +24,6 @@ public class TestDeleteImportedPartial extends BaseTestCase {
// 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);
@@ -26,7 +26,6 @@ public class TestDeleteOneToOneMultiple extends BaseTestCase {
// should delete file and fileContent
Ebean.delete(PFile.class, id);
System.out.println("finished delete");
PFile file1 = Ebean.find(PFile.class, id);
PFileContent content1 = Ebean.find(PFileContent.class, contentId);
@@ -36,14 +36,11 @@ public class TestFetchId extends BaseTestCase {
List<Object> partial = futureIds.getPartialIds();
// this is likely 0 or a small number
System.out.println("partial: " + partial.size());
// wait for all the id's to be fetched
List<Object> idList = futureIds.get();
Assert.assertTrue("same instance", partial == idList);
Assert.assertTrue("sz > 0", ids.size() > 0);
System.out.println("ids: " + partial);
}
}
@@ -19,13 +19,7 @@ public class TestM2MCascadeOne extends BaseTestCase {
MUser u = new MUser();
u.setUserName("testM2M");
List<MRole> roles = u.getRoles();
if (roles != null) {
if (roles instanceof BeanList<?>) {
System.out.println("enhancement checkNullManyFields=true successful");
}
}
u.getRoles();
Ebean.save(u);
MRole r0 = new MRole();
@@ -20,14 +20,13 @@ public class TestOrderTotalAmountReportBean extends BaseTestCase {
List<OrderAggregate> l0 = Ebean.find(OrderAggregate.class).findList();
for (OrderAggregate r0 : l0) {
System.out.println(r0);
r0.toString();
}
List<OrderAggregate> list = Ebean.createNamedQuery(OrderAggregate.class, "total.amount")
.where().gt("order.id", 0).having().gt("totalAmount", 50).findList();
for (OrderAggregate r1 : list) {
System.out.println(r1);
Assert.assertTrue(r1.getTotalAmount() > 20.50);
// partial object query without totalItems
// ... no lazy loading invoked on this type of bean
@@ -38,7 +37,6 @@ public class TestOrderTotalAmountReportBean extends BaseTestCase {
.having().lt("totalItems", 3).gt("totalAmount", 50).findList();
for (OrderAggregate r2 : l2) {
// System.out.println(r2);
Assert.assertTrue(r2.getTotalItems() < 3);
}
@@ -25,6 +25,11 @@ public class TestEncrypt extends BaseTestCase {
@Test
public void testQueryBind() {
if (!isH2()) {
// only run this on H2 - PGCrypto not happy on CI server
return;
}
LoggedSqlCollector.start();
Ebean.find(EBasicEncrypt.class)
.where().startsWith("description", "Rob")
@@ -67,14 +72,12 @@ public class TestEncrypt extends BaseTestCase {
q.setParameter("id", e.getId());
SqlRow row = q.findUnique();
String name = row.getString("name");
Object desc = row.get("description");
System.out.println("SqlRow: " + name + " " + desc);
row.getString("name");
row.get("description");
EBasicEncrypt e1 = Ebean.find(EBasicEncrypt.class, e.getId());
String desc1 = e1.getDescription();
System.out.println("Decrypted: " + desc1 + " " + e1.getDob());
e1.getDescription();
e1.setName("testmod");
e1.setDescription("moddesc");
@@ -83,8 +86,7 @@ public class TestEncrypt extends BaseTestCase {
EBasicEncrypt e2 = Ebean.find(EBasicEncrypt.class, e.getId());
String desc2 = e2.getDescription();
System.out.println("moddesc=" + desc2);
e2.getDescription();
SpiEbeanServer server = (SpiEbeanServer) Ebean.getServer(null);
DbEncrypt dbEncrypt = server.getDatabasePlatform().getDbEncrypt();
@@ -29,18 +29,16 @@ public class TestEncryptBinary extends BaseTestCase {
q.setParameter("id", e.getId());
SqlRow row = q.findUnique();
String name = row.getString("name");
Object data = row.get("data");
Object someTimeData = row.get("some_time");
System.out.println("SqlRow name:" + name + " data:" + data + " someTime:" + someTimeData);
row.getString("name");
row.get("data");
row.get("some_time");
EBasicEncryptBinary e1 = Ebean.find(EBasicEncryptBinary.class, e.getId());
Timestamp t1 = e1.getSomeTime();
byte[] data1 = e1.getData();
String s = new String(data1);
String desc1 = e1.getDescription();
System.out.println("Decrypted data:" + s + " desc:" + desc1);
e1.getData();
e1.getDescription();
Assert.assertEquals(t0, t1);
@@ -50,9 +48,7 @@ public class TestEncryptBinary extends BaseTestCase {
Ebean.save(e1);
EBasicEncryptBinary e2 = Ebean.find(EBasicEncryptBinary.class, e.getId());
String desc2 = e2.getDescription();
System.out.println("moddesc=" + desc2);
e2.getDescription();
}
}
@@ -27,9 +27,6 @@ public class TestSecondaryJoin extends BaseTestCase {
o0.setStatus(Status.APPROVED);
Ebean.save(o0);
System.out.println("done");
}
}
@@ -23,10 +23,6 @@ public class TestByteOnly extends BaseTestCase {
e2.setContent(content2);
Ebean.save(e2);
// Ebean.getServer(null).getAutoTune().collectProfiling();
// Ebean.getServer(null).getAutoTune().updateTunedQueryInfo();
System.out.println("done");
}
}
@@ -1,8 +1,7 @@
package com.avaje.tests.basic.one2one;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@@ -12,6 +11,7 @@ import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Version;
import java.util.List;
@Entity
@Table(name = "drel_booking")
@@ -19,9 +19,16 @@ public class Booking {
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Column(unique = true)
Long bookingUid;
@Version
private int version;
public Booking(Long bookingUid) {
this.bookingUid = bookingUid;
}
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "agent_invoice")
@@ -31,7 +38,7 @@ public class Booking {
@JoinColumn(name = "client_invoice")
private Invoice clientInvoice;
@OneToMany(mappedBy = "booking")//, cascade = CascadeType.ALL)
@OneToMany(mappedBy = "booking")
private List<Invoice> invoices;
public Long getId() {
@@ -41,8 +48,16 @@ public class Booking {
public void setId(Long id) {
this.id = id;
}
public int getVersion() {
public Long getBookingUid() {
return bookingUid;
}
public void setBookingUid(Long bookingUid) {
this.bookingUid = bookingUid;
}
public int getVersion() {
return version;
}
@@ -69,7 +84,7 @@ public class Booking {
public List<Invoice> getInvoices() {
return invoices;
}
public void setInvoices(List<Invoice> invoices) {
this.invoices= invoices;
}
@@ -21,7 +21,7 @@ public class Invoice {
private int version;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "booking")
@JoinColumn(name = "booking")//_xid", referencedColumnName = "booking_uid")
private Booking booking;
public Long getId() {
@@ -10,7 +10,9 @@ public class TestOne2OneBookingInvoice extends BaseTestCase {
@Test
public void test() {
Booking b = new Booking();
Booking b = new Booking(3000L);
Ebean.save(b);
Invoice ai = new Invoice();
Invoice ci = new Invoice();
@@ -23,6 +25,9 @@ public class TestOne2OneBookingInvoice extends BaseTestCase {
Ebean.save(b);
Invoice invoice = Ebean.find(Invoice.class, ai.getId());
Assert.assertEquals(b.getId(), invoice.getBooking().getId());
Booking b1 = Ebean.find(Booking.class, b.getId());
Invoice ai1 = b1.getAgentInvoice();
@@ -68,7 +68,7 @@ public class TestBatchLazyWithCacheHits extends BaseTestCase {
.findList();
for (UUOne uuOne : list) {
System.out.println(uuOne.getName());
uuOne.getName();
}
list.get(0).getName();
@@ -77,7 +77,7 @@ public class TestBatchLazyWithDeleted extends BaseTestCase {
list.get(2).getMaster().getName();
Assert.assertTrue(false);
} catch (EntityNotFoundException e) {
// this bean was deleted and lazy loading failed
// this bean was deleted and lazy loading failed
Assert.assertTrue(true);
}
@@ -34,8 +34,6 @@ public class TestLazyLoadEmptyCollection extends BaseTestCase {
for (Contact contact : contacts) {
contact.getNotes();
}
System.out.println(customer);
System.out.println(contacts);
}
}
@@ -0,0 +1,31 @@
package com.avaje.tests.batchload;
import java.util.UUID;
import javax.persistence.EntityNotFoundException;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.UUOne;
public class TestLazyLoadNonExistentBean extends BaseTestCase {
@Test
public void testSimple() {
UUID uuid = UUID.randomUUID();
UUOne one = Ebean.getReference(UUOne.class, uuid);
try {
// invoke lazy loading
one.getName();
Assert.assertTrue(false);
} catch (EntityNotFoundException e) {
// expecting this
Assert.assertTrue(true);
}
}
}
@@ -71,10 +71,6 @@ public class TestCacheCollectionIds extends BaseTestCase {
int currentNumContacts2 = fetchCustomer(customer.getId());
Assert.assertEquals(currentNumContacts + 1, currentNumContacts2);
System.out.println("custCache:" + custCache.getStatistics(false));
System.out.println("contactCache:" + contactCache.getStatistics(false));
System.out.println("custManyIdsCache:" + custManyIdsCache.getStatistics(false));
}
private int fetchCustomer(Integer id) {
@@ -102,9 +102,6 @@ public class TestChangeLog extends BaseTestCase {
this.changes = changes;
try {
String json = objectMapper.writeValueAsString(changes);
logger.info(json);
ChangeSet changes1 = objectMapper.readValue(json, ChangeSet.class);
assertEquals(changes.getTxnId(), changes1.getTxnId());
@@ -0,0 +1,41 @@
package com.avaje.tests.inheritance;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Car;
import com.avaje.tests.model.basic.Truck;
import com.avaje.tests.model.basic.Vehicle;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class TestInheritanceBatchLazyLoad {
@Test
public void lazyLoadProperty_when_propertyNotOnAllInheritanceTypes() {
Car c = new Car();
c.setLicenseNumber("VZVZ1");
c.setDriver("CarDriver");
Ebean.save(c);
Truck t = new Truck();
t.setLicenseNumber("VZVZ2");
t.setCapacity(20D);
Ebean.save(t);
List<Vehicle> list = Ebean.find(Vehicle.class)
.select("licenseNumber")
.where().startsWith("licenseNumber","VZVZ")
.order().asc("licenseNumber")
.findList();
assertThat(list).hasSize(2);
Car car = (Car)list.get(0);
car.getNotes();
}
}
@@ -19,12 +19,14 @@ public class Car extends Vehicle {
private String driver;
@ManyToOne
TruckRef carRef;
private TruckRef carRef;
@OneToMany(mappedBy = "car")
@OrderBy("fuse.locationCode")
private Set<CarAccessory> accessories = new HashSet<CarAccessory>();
private String notes;
public String getDriver() {
return driver;
}
@@ -33,6 +35,14 @@ public class Car extends Vehicle {
this.driver = driver;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public TruckRef getCarRef() {
return carRef;
}
@@ -53,8 +53,6 @@ public class TestAutofetchTuneWithJoin extends BaseTestCase {
ObjectGraphNode parentNode = sq.getParentNode();
ObjectGraphOrigin origin = parentNode.getOriginQueryPoint();
System.out.println("Origin:" + origin.getKey());
// MetaAutoFetchStatistic metaAutoFetchStatistic =
// ((DefaultOrmQuery<?>)q).getMetaAutoFetchStatistic();
// if (metaAutoFetchStatistic != null) {
@@ -65,9 +63,6 @@ public class TestAutofetchTuneWithJoin extends BaseTestCase {
// System.out.println(queryStats);
// }
if (q.isAutoTuned()) {
System.out.println("TUNED...");
}
}
private static void collectUsage() {
@@ -51,8 +51,7 @@ public class TestManyWhereJoinM2M extends BaseTestCase {
// of a fetch join (if there is a fetch join)
.where().eq("roles.roleName", "role2special").query();
List<MUser> list = query.findList();
System.out.println(list);
query.findList();
String sql = query.getGeneratedSql();
Assert.assertTrue(sql.contains("select distinct"));
@@ -30,9 +30,8 @@ public class TestOneToManyCorrectGrouping extends BaseTestCase {
int count = 0;
while (customerQueryIterator.hasNext()) {
Customer customer = customerQueryIterator.next();
System.out.println(String.format("Customer id %s", customer.getId()));
for (Order order : customer.getOrders()) {
System.out.println(String.format("--> Order id %s", order.getId()));
order.getId();
}
count++;
}
@@ -32,10 +32,9 @@ public class TestQueryFetchSkipPath extends BaseTestCase {
Customer customer = order.getCustomer();
List<Contact> contacts = customer.getContacts();
for (Contact contact : contacts) {
System.out.println("contact:" + contact);
List<ContactNote> notes = contact.getNotes();
for (ContactNote contactNote : notes) {
System.out.println("note:" + contactNote.getTitle());
contactNote.getTitle();
}
}
}
@@ -30,9 +30,7 @@ public class TestQueryFilterManySimple extends BaseTestCase {
.filterMany("orders").eq("status", Order.Status.NEW).gt("orderDate", lastWeek)
.filterMany("contacts").isNotNull("firstName").findList();
System.out.println(list);
// invoke lazy loading
list.get(0).getOrders().size();
System.out.println(list.get(0).getOrders());
}
}
@@ -61,7 +61,10 @@ public class TestQueryFindIterate extends BaseTestCase {
Order order = queryIterator.next();
Customer customer = order.getCustomer();
// invoke lazy loading on customer, order details and order shipments
System.out.println("order: " + order.getId() + " customerName:" + customer.getName()+" details:"+order.getDetails().size()+" shipments:"+order.getShipments().size());
order.getId();
customer.getName();
order.getDetails().size();
order.getShipments().size();
}
} finally {
@@ -89,7 +92,9 @@ public class TestQueryFindIterate extends BaseTestCase {
while (queryIterator.hasNext()) {
Order order = queryIterator.next();
Customer customer = order.getCustomer();
System.out.println("order: " + order.getId() + " customerName:" + customer.getName()+" details:"+order.getDetails().size()+" shipments:"+order.getShipments().size());
customer.getName();
order.getDetails().size();
order.getShipments().size();
}
} finally {
@@ -132,7 +137,10 @@ public class TestQueryFindIterate extends BaseTestCase {
while (queryIterator.hasNext()) {
Order order = queryIterator.next();
Customer customer = order.getCustomer();
System.out.println("order: " + order.getId() + " customerName:" + customer.getName()+" details:"+order.getDetails().size()+" shipments:"+order.getShipments().size());
order.getId();
customer.getName();
order.getDetails().size();
order.getShipments().size();
}
} finally {
@@ -22,7 +22,6 @@ public class TestQueryJoinMulipleMany extends BaseTestCase {
.gt("id", 0).findList();
Assert.assertNotNull(list);
System.out.println(list);
for (Order order : list) {
List<Contact> contacts = order.getCustomer().getContacts();
@@ -22,10 +22,8 @@ public class TestRowCount extends BaseTestCase {
.gt("details.id", 1).order("id desc");
int rc = query.findRowCount();
System.out.println("rc:" + rc);
List<Object> ids = query.findIds();
System.out.println("ids:" + ids);
List<Order> list = query.findList();
System.out.println(list);
@@ -15,6 +15,8 @@ import com.avaje.tests.model.basic.ResetBasicData;
import com.avaje.tests.model.basic.Vehicle;
import com.avaje.tests.model.basic.VehicleDriver;
import static org.assertj.core.api.StrictAssertions.assertThat;
public class TestSubQuery extends BaseTestCase {
@Test
@@ -30,18 +32,15 @@ public class TestSubQuery extends BaseTestCase {
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)
Ebean.createQuery(Order.class, oq).setParameter("prods", productIds)
.findList();
System.out.println(list2);
// Assert.assertEquals(2,list2.size());
}
@@ -59,10 +58,7 @@ public class TestSubQuery extends BaseTestCase {
String golden = "(t0.one_key) in (select t0.one_key from ckey_parent t0) ";
if (!sql.contains(golden)) {
System.out.println("failed sql:" + sql);
Assert.fail("golden string not found");
}
assertThat(sql).contains(golden);
}
/**
@@ -102,16 +98,12 @@ public class TestSubQuery extends BaseTestCase {
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.contains(golden)) {
System.out.println("failed sql:" + sql);
Assert.fail("golden string not found");
}
assertThat(sql).contains(golden);
}
@@ -131,13 +123,8 @@ public class TestSubQuery extends BaseTestCase {
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.contains(golden)) {
System.out.println("failed sql:" + sql);
Assert.fail("golden string not found");
}
assertThat(sql).contains(golden);
}
/**
@@ -157,15 +144,8 @@ public class TestSubQuery extends BaseTestCase {
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.contains(golden)) {
System.out.println("failed sql:" + sql);
Assert.fail("golden string not found");
}
assertThat(sql).contains(golden);
}
}
@@ -21,28 +21,20 @@ public class TestAutoTuneProfiling extends BaseTestCase {
ResetBasicData.reset();
System.out.println("Start .......");
for (int i = 0; i < 1; i++) {
execute();
}
collectUsage();
System.out.println("Sleeping ...");
sortOfBusy();
System.out.println("Run after collection");
for (int i = 0; i < 10; i++) {
execute();
}
collectUsage();
System.out.println("Sleeping ...");
sortOfBusy();
System.out.println("Run after collection");
for (int i = 0; i < 1; i++) {
execute();
}
@@ -104,9 +104,9 @@ public class TestQueryDefaultBatchSize extends BaseTestCase {
private void doStuff(Order order) {
// invoke lazy loading
Customer customer = order.getCustomer();
System.out.println("do stuff: order:"+order.getId());
System.out.println("... customer:"+customer.getName());
System.out.println("... contacts: "+customer.getContacts().size()+" details:"+order.getDetails().size());
order.getId();
customer.getName();
customer.getContacts().size();
order.getDetails().size();
}
}
@@ -16,7 +16,6 @@ public class TestOrderByWithDistinctTake2 extends BaseTestCase {
String test = "helloasc asc ASC desc DESC boodesc desc ASC";
test = test.replaceAll("(?i)\\b asc\\b|\\b desc\\b", "");
System.out.println(test);
Assert.assertEquals("helloasc boodesc", test);
}
@@ -39,9 +39,8 @@ public class TestFindPartialWithConstructorSetFields extends BaseTestCase {
assertTrue(!loadedProps.contains("orderDate"));
// invoke lazy loading
Status status = order0.getStatus();
Date orderDate = order0.getOrderDate();
System.out.println("-- order - "+order0.getId()+" status:"+status+" date:"+orderDate);
order0.getStatus();
order0.getOrderDate();
// assert that these beans are fully loaded
for (int i = 1; i < list.size(); i++) {
@@ -20,7 +20,7 @@ public class TestManyToManyLazyLoading extends BaseTestCase {
for (MUser user : users) {
List<MRole> roles = user.getRoles();
System.out.println(""+roles.size());
roles.size();
}
}
@@ -28,7 +28,6 @@ public class TestObjectGraphNodeStatsCollection extends BaseTestCase {
MetaInfoManager infoManager = server.getMetaInfoManager();
server.find(Order.class).findRowCount();
infoManager.collectNodeStatistics(true);
@@ -37,26 +36,16 @@ public class TestObjectGraphNodeStatsCollection extends BaseTestCase {
runFindOrderQuery(server);
runFindCustomerQuery(server);
System.out.println("============================================================");
List<MetaObjectGraphNodeStats> nodeStatistics = infoManager.collectNodeStatistics(true);
for (MetaObjectGraphNodeStats stat : nodeStatistics) {
System.out.println("-----------");
System.out.println(stat);
stat.toString();
}
System.out.println("============================================================");
List<MetaQueryPlanStatistic> planStatistics = infoManager.collectQueryPlanStatistics(true);
for (MetaQueryPlanStatistic planStatistic : planStatistics) {
System.out.println("------------");
System.out.println(planStatistic);
System.out.println(planStatistic.getSql());
planStatistic.getSql();
}
System.out.println("============================================================");
}
private void runFindCustomerQuery(EbeanServer server) {
@@ -47,7 +47,7 @@ public class TestSelfParent extends BaseTestCase {
}
public static void printNode(SelfParent o) {
System.out.println(o.getName());
//System.out.println(o.getName());
for (SelfParent c : o.getChildren()) {
printNode(c);
}
@@ -17,11 +17,9 @@ public class TestWhereLikeWithSlash extends BaseTestCase {
basic.setName("slash\\monkey");
Ebean.save(basic);
Query<EBasic> query = Ebean.find(EBasic.class).where().like("name", "slash\\mon%").query();
List<EBasic> list = query.findList();
query.findList();
// This doesn't work in the latest version of H2 so disable for now.
// Still good on Postgres which was the original issue
@@ -155,16 +155,15 @@ public class TestRawSqlMasterDetail extends BaseTestCase {
}
private void printOrders(List<Order> orders, String heading) {
System.out.println("-------------- "+heading);
for (Order order : orders) {
List<OrderDetail> details = order.getDetails();
System.out.println("order: "+order.getId()+" "+order.getCustomer().getName());
order.getCustomer().getName();
for (OrderDetail detail : details) {
System.out.println("detailId:" + detail.getId() + " productId:" + detail.getProduct().getId() + " qty:" +
detail.getOrderQty());
detail.getProduct().getId();
detail.getOrderQty();
}
}
System.out.println("-------------- "+heading+" complete");
}
}
@@ -56,14 +56,15 @@ public class TestRawSqlOrmWrapper extends BaseTestCase {
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);
order.getId();
order.getStatus();
oa.getTotalAmount();
Customer c = order.getCustomer();
System.out.println(" -> customer: " + c.getId() + " " + c.getName());
c.getId();
c.getName();
// invoke lazy loading as this property
// has not populated originally
@@ -40,10 +40,9 @@ public class TestRawSqlOrmWrapper2 extends BaseTestCase {
Assert.assertNotNull(list);
for (OrderAggregate oa : list) {
Double totalAmount = oa.getTotalAmount();
oa.getTotalAmount();
Order order = oa.getOrder();
Integer id = order.getId();
System.out.println("Order: " + id + " total:" + totalAmount);
order.getId();
}
}
@@ -49,14 +49,14 @@ public class TestRawSqlOrmWrapper3 extends BaseTestCase {
private void output(List<OrderAggregate> list) {
for (OrderAggregate oa : list) {
Double totalAmount = oa.getTotalAmount();
oa.getTotalAmount();
Order order = oa.getOrder();
Integer id = order.getId();
Status status = order.getStatus();
System.out.println("Order: " + id + " " + status + " total:" + totalAmount);
order.getId();
order.getStatus();
Customer c = order.getCustomer();
System.out.println(" -> customer: " + c.getId() + " " + c.getName());
c.getId();
c.getName();
// invoke lazy loading as this property
// has not populated originally
@@ -43,7 +43,9 @@ public class TestRawSqlWithResultSet extends BaseTestCase {
.findList();
for (Customer customer : list) {
System.out.println("id:"+customer.getId()+" name:"+customer.getName()+" billingAddress:"+customer.getBillingAddress());
customer.getId();
customer.getName();
customer.getBillingAddress();
}
} finally {
@@ -37,9 +37,7 @@ public class TestRefreshWithMany extends BaseTestCase {
assertEquals(1, rc);
assertEquals(3, rc2);
System.out.println("-------------------------- prior");
Ebean.refresh(customer);
System.out.println("-------------------------- after");
assertEquals("ref-modified", customer.getName());
assertEquals(3, customer.getContacts().size());
@@ -65,22 +63,22 @@ public class TestRefreshWithMany extends BaseTestCase {
List<SqlRow> sqlRows = Ebean.createSqlQuery("select id, first_name, last_name from contact").findList();
for (SqlRow sqlRow : sqlRows) {
System.out.println("row: "+sqlRow.get("id")+" "+sqlRow.get("first_name")+" "+sqlRow.get("last_name"));
sqlRow.get("id");
sqlRow.get("first_name");
sqlRow.get("last_name");
}
assertEquals(1, rcb1);
assertEquals(3, rcb2);
System.out.println("-------------------------- prior2");
Ebean.refresh(customer1);
System.out.println("-------------------------- after2");
assertEquals("ref-modified-again", customer1.getName());
System.out.println("-------------------------- after2a");
assertEquals(3, customer1.getContacts().size());
System.out.println("-------------------------- after2b");
for (Contact contact : customer1.getContacts()) {
System.out.println("hello "+contact.getId()+" "+contact.getFirstName()+" "+contact.getLastName());
contact.getId();
contact.getFirstName();
contact.getLastName();
}
assertEquals(true, customer1.getContacts().get(0).getFirstName().endsWith("-alt"));
@@ -49,8 +49,6 @@ public class TestCsvReaderWithCallback extends BaseTestCase {
@Override
public void processBean(int row, String[] lineContent, Customer cust) {
System.out.println(row + "> " + cust + " " + cust.getBillingAddress());
server.save(cust.getBillingAddress(), transaction);
server.save(cust, transaction);
}
@@ -1,27 +1,23 @@
package com.avaje.tests.text.json;
import java.io.IOException;
import java.util.TimeZone;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.text.json.JsonContext;
import com.avaje.tests.model.basic.BeanWithTimeZone;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.TimeZone;
public class TestJsonBeanWithTimeZone extends BaseTestCase {
//private static final Logger logger = LoggerFactory.getLogger(TestJsonBeanWithTimeZone.class);
@Test
public void testSimple() throws IOException {
TimeZone defaultTimeZone = TimeZone.getDefault();
String[] ids = TimeZone.getAvailableIDs(defaultTimeZone.getRawOffset());
System.out.println(ids);
TimeZone.getAvailableIDs(defaultTimeZone.getRawOffset());
String id = defaultTimeZone.getID();
TimeZone timeZone = TimeZone.getTimeZone(id);
@@ -43,10 +39,6 @@ public class TestJsonBeanWithTimeZone extends BaseTestCase {
Assert.assertEquals(bean.getTimezone(), bean3.getTimezone());
// EbeanServer server = Ebean.getServer(null);
// server.shutdown();
// logger.info("shudown server manually, JVM shutdown hook fires next");
}
}
@@ -46,13 +46,11 @@ public class TestJsonMap extends BaseTestCase {
JsonContext jsonContext = Ebean.json();
JsonWriteOptions options = JsonWriteOptions.parsePath("(id,status,name)");
String jsonString = jsonContext.toJson(map, options);
System.out.println(jsonString);
jsonContext.toJson(map, options);
options = JsonWriteOptions.parsePath("(id,status,name,shippingAddress(id,line1,city),billingAddress(*),contacts(*))");
jsonString = jsonContext.toJson(map, options);
System.out.println(jsonString);
jsonContext.toJson(map, options);
// Assert.assertTrue(jsonString.indexOf("{\"1\":") > -1);
// Assert.assertTrue(jsonString.indexOf("{\"id\":1,\"status\":\"NEW\",\"name\":\"Rob\"},")
@@ -72,9 +70,7 @@ public class TestJsonMap extends BaseTestCase {
.apply(pathProperties)
.findList();
String jsonString = Ebean.json().toJson(customers, pathProperties);
System.out.println(jsonString);
Ebean.json().toJson(customers, pathProperties);
// Assert.assertTrue(jsonString.indexOf("{\"1\":") > -1);
// Assert.assertTrue(jsonString.indexOf("{\"id\":1,\"status\":\"NEW\",\"name\":\"Rob\"},")
@@ -38,7 +38,6 @@ public class TestJsonSimple extends BaseTestCase {
String jsonText = sb.toString();
Object el = EJson.parse(jsonText);
System.out.println("Got " + el);
Map<String,Object> e2 = EJson.parseObject("{\"a\":12, \"name\":{\"first\":\"rob\", \"last\":\"byg\"}}");
@@ -50,8 +49,7 @@ public class TestJsonSimple extends BaseTestCase {
m.put("test", "me");
JsonContext jsonContext = Ebean.json();
String jsonString = jsonContext.toJson(m);
System.out.println(jsonString);
jsonContext.toJson(m);
String s = "{\"parishId\":\"18\",\"contentId\":null,\"contentStatus\":null,\"contentType\":\"pg-hello\",\"content\":\"asd\"}";
@@ -31,14 +31,11 @@ public class TestTextJsonBeanReadVisitor extends BaseTestCase {
String s = json.toJson(list);
System.out.println(s);
List<Customer> mList = json.toList(Customer.class, s);
System.out.println("VIA STRING: " + mList);
StringReader reader = new StringReader(s);
List<Customer> mList2 = json.toList(Customer.class, reader);
System.out.println("VIA READER: " + mList2);
Assert.assertEquals(mList.size(), mList2.size());
}
@@ -30,7 +30,6 @@ public class TestTextJsonInheritance extends BaseTestCase {
JsonContext jsonContext = Ebean.json();
String jsonString = jsonContext.toJson(list);
System.out.println(jsonString);
List<Vehicle> rebuiltList = jsonContext.toList(Vehicle.class, jsonString);
@@ -24,9 +24,6 @@ public class TestTextJsonInvokeLazy extends BaseTestCase {
JsonWriteOptions opt = JsonWriteOptions.parsePath("name, status");
JsonContext jsonContext = Ebean.json();
String jsonString = jsonContext.toJson(list, opt);
System.out.println(jsonString);
jsonContext.toJson(list, opt);
}
}
@@ -31,9 +31,7 @@ public class TestTextJsonReadManyLazyLoad extends BaseTestCase {
JsonWriteOptions o = new JsonWriteOptions();
o.setPathProperties(pp);
System.out.println("Expect lazy loading of Customer beans and customer contacts");
String s = json.toJson(list, o);
System.out.println(s);
Assert.assertTrue(s.contains("\"contacts\""));
Assert.assertTrue(s.contains("\"name\""));
@@ -54,9 +52,7 @@ public class TestTextJsonReadManyLazyLoad extends BaseTestCase {
JsonWriteOptions o = new JsonWriteOptions();
o.setPathProperties(pp);
System.out.println("expecting lazy load of Customer beans to fetch customer name");
String s = json.toJson(list, o);
System.out.println(s);
Assert.assertTrue(s.contains("\"contacts\""));
Assert.assertTrue(s.contains("\"name\""));
@@ -78,9 +74,7 @@ public class TestTextJsonReadManyLazyLoad extends BaseTestCase {
JsonWriteOptions o = new JsonWriteOptions();
o.setPathProperties(pp);
System.out.println("expecting lazy load of Customer contacts ");
String s = json.toJson(list, o);
System.out.println(s);
Assert.assertTrue(s.contains("\"contacts\""));
Assert.assertTrue(s.contains("\"name\""));
@@ -39,7 +39,6 @@ public class TestTextJsonReferenceBean extends BaseTestCase {
} else {
String jsonString = jsonContext.toJson(product);
System.out.println(jsonString);
Product refProd = jsonContext.toBean(Product.class, jsonString);
@@ -71,7 +70,6 @@ public class TestTextJsonReferenceBean extends BaseTestCase {
JsonWriteOptions options = JsonWriteOptions.parsePath("*,details(id,orderQty,product(id))");
String jsonOrder = jsonContext.toJson(order, options);
System.out.println(jsonOrder);
Order o2 = jsonContext.toBean(Order.class, jsonOrder);
Customer customer = o2.getCustomer();
@@ -71,7 +71,6 @@ public class TestTextJsonSimple extends BaseTestCase {
JsonContext json = server.json();
String jsonOutput = json.toJson(list);
System.out.println(jsonOutput);
// check that transient fields are included by default in the JSON output
Assert.assertTrue(jsonOutput.contains("\"selected\":"));
@@ -109,7 +108,6 @@ public class TestTextJsonSimple extends BaseTestCase {
// not using pathProperties - includes transient fields by default
String jsonOutput = json.toJson(list);
System.out.println(jsonOutput);
// check that transient fields are included by default in the JSON output
Assert.assertTrue(jsonOutput.contains("\"selected\":"));
@@ -133,14 +131,12 @@ public class TestTextJsonSimple extends BaseTestCase {
PathProperties pathProperties = PathProperties.parse("(id,name,selected)");
String jsonOutput = json.toJson(list, pathProperties);
System.out.println(jsonOutput);
// check that transient fields are included by explicit pathProperties
Assert.assertTrue(jsonOutput.contains("\"selected\":"));
pathProperties = PathProperties.parse("(id,name)");
jsonOutput = json.toJson(list, pathProperties);
System.out.println(jsonOutput);
// check that transient fields are NOT included when explicitly excluded by pathProperties
Assert.assertFalse(jsonOutput.contains("\"selected\":"));
@@ -31,7 +31,6 @@ public class TestTextJsonSuperSimple extends BaseTestCase {
Customer customer = list.get(0);
String s = json.toJson(customer);
System.out.println(s);
int statusPos = s.indexOf("status");
Assert.assertEquals(-1, statusPos);
}
@@ -59,7 +59,6 @@ public class TestTextJsonUpdateCascade extends BaseTestCase {
JsonContext jsonContext = server.json();
String jsonString = jsonContext.toJson(order);
System.out.println(jsonString);
Order updOrder = jsonContext.toBean(Order.class, jsonString);
@@ -85,9 +84,7 @@ public class TestTextJsonUpdateCascade extends BaseTestCase {
Ebean.save(u0);
String jsonUser = jsonContext.toJson(u0);
System.out.println(jsonUser);
jsonContext.toJson(u0);
String s = "{\"userid\":" + u0.getUserid()
+ ",\"userName\":\"userj1\", \"roles\":[{\"roleid\":" + r2.getRoleid() + "},{\"roleid\":"
@@ -28,8 +28,6 @@ public class TestPersistContextClear extends BaseTestCase {
SpiTransaction spiTxn = (SpiTransaction) t;
PersistenceContext pc = spiTxn.getPersistenceContext();
System.out.println("pc0:" + pc.toString());
// no orders or customers in the PC
Assert.assertEquals(0, pc.size(Order.class));
Assert.assertEquals(0, pc.size(Customer.class));
@@ -46,7 +44,6 @@ public class TestPersistContextClear extends BaseTestCase {
// keep a hold of one of them
order0 = list.get(0);
System.out.println("pc1:" + pc.toString());
Assert.assertEquals(orderSize, pc.size(Order.class));
System.gc();
@@ -67,7 +64,6 @@ public class TestPersistContextClear extends BaseTestCase {
}
System.gc();
System.out.println("pc4:" + pc.toString());
// we still have the order
Assert.assertNotNull(order0);
@@ -43,8 +43,6 @@ public class TestFileType extends BaseTestCase {
assertEquals("afile", bean2.getName());
assertNotNull(bean2.getContent());
System.out.println("test_insertNullFile: bean2: "+bean2.getContent());
Ebean.delete(bean1);
}
@@ -68,7 +66,6 @@ public class TestFileType extends BaseTestCase {
assertEquals("afile", bean1.getName());
assertNotNull(bean1.getContent());
assertEquals(file.length(), bean1.getContent().length());
System.out.println("t2 bean1: " + bean1.getContent().getAbsoluteFile());
bean1.setName("mod-file");
bean1.setContent(file2);
@@ -82,7 +79,6 @@ public class TestFileType extends BaseTestCase {
.findUnique();
assertEquals(file2.length(), bean2.getContent().length());
System.out.println("t2 bean3: " + bean2.getContent().getAbsoluteFile());
// update to null
bean2.setContent(null);
@@ -95,7 +91,6 @@ public class TestFileType extends BaseTestCase {
.findUnique();
assertNull(bean3.getContent());
System.out.println("t2 bean3: " + bean3.getContent());
bean3.setName("changeOnlyName");
Ebean.save(bean3);
@@ -82,7 +82,6 @@ public class TestNewTypes extends BaseTestCase {
assertEquals(bean.getInstant(), fetched.getInstant());
String asJson = Ebean.json().toJson(fetched);
System.out.println(asJson);
SomeNewTypesBean toBean = Ebean.json().toBean(SomeNewTypesBean.class, asJson);
@@ -51,7 +51,6 @@ public class HelloMain {
long id = 1;
TOne data = eServer.find(TOne.class, id);
if (data == null) {
System.out.println("This is the first run, saving data..");
TOne tone = new TOne();
tone.setName("banan");
eServer.save(tone);// new TOne()id, "Hello World!"));
@@ -1,15 +1,13 @@
package com.avaje.tests.unitinternal;
import java.sql.Timestamp;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.config.EncryptKey;
import com.avaje.ebeaninternal.server.type.SimpleAesEncryptor;
import com.avaje.tests.basic.encrypt.BasicEncryptKey;
import org.junit.Assert;
import org.junit.Test;
import java.sql.Timestamp;
public class TestSimpleEncryptor extends BaseTestCase {
@@ -23,17 +21,11 @@ public class TestSimpleEncryptor extends BaseTestCase {
byte[] data = "test123".getBytes();
byte[] ecData = e.encrypt(data, key);
System.out.println(Arrays.toString(ecData));
byte[] deData = e.decrypt(ecData, key);
String s = new String(deData);
System.out.println(s);
Timestamp t = new Timestamp(System.currentTimeMillis());
byte[] ecTimestamp = e.encryptString(t.toString(), key);
System.out.println(t + " encrypted -> " + Arrays.toString(ecTimestamp));
String tsFormat = e.decryptString(ecTimestamp, key);
Timestamp t1 = Timestamp.valueOf(tsFormat);
@@ -35,7 +35,6 @@ public class TestJsonStatelessUpdate extends BaseTestCase {
JsonWriteOptions writeOptions = JsonWriteOptions.parsePath("(id,name,master(*))");
String jsonString = jsonContext.toJson(twoX, writeOptions);
System.out.println(jsonString);
jsonString = jsonString.replace("twoName", "twoNameModified");
jsonString = jsonString.replace("oneName", "oneNameModified");
@@ -21,6 +21,8 @@ import ch.qos.logback.core.UnsynchronizedAppenderBase;
*/
public class LoggedSqlCollector {
static Logger logger = (Logger) LoggerFactory.getLogger("org.avaje.ebean.SQL");
private static BasicAppender basicAppender = new BasicAppender();
static {
@@ -28,11 +30,12 @@ public class LoggedSqlCollector {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
basicAppender.setContext(lc);
Logger logger = (Logger) LoggerFactory.getLogger("org.avaje.ebean.SQL");
Level level = logger.getEffectiveLevel();
if (level.isGreaterOrEqual(Level.INFO)) {
logger.setAdditive(false);
}
logger.addAppender(basicAppender);
logger.setLevel(Level.TRACE);
logger.setAdditive(true);
}
/**
+10 -9
View File
@@ -72,20 +72,21 @@
<appender-ref ref="STDOUT"/>
</root>
<logger name="com.avaje.ebeaninternal.server.autotune" level="TRACE"/>
<!--<logger name="com.avaje.ebeaninternal.server.autotune" level="TRACE"/>-->
<logger name="com.avaje.ebean" level="INFO"/>
<logger name="org.avaje.ebean" level="INFO"/>
<logger name="org.avaje.ebean.SQL" level="TRACE"/>
<logger name="org.avaje.ebean.TXN" level="TRACE"/>
<logger name="org.avaje.ebean.SUM" level="TRACE"/>
<logger name="org.avaje.ebean.cache.QUERY" level="TRACE"/>
<logger name="org.avaje.ebean.cache.BEAN" level="TRACE"/>
<logger name="org.avaje.ebean.cache.COLL" level="TRACE"/>
<logger name="org.avaje.ebean.cache.NATKEY" level="TRACE"/>
<!--<logger name="org.avaje.ebean.SQL" level="TRACE"/>-->
<!--<logger name="org.avaje.ebean.TXN" level="TRACE"/>-->
<!--<logger name="org.avaje.ebean.SUM" level="TRACE"/>-->
<logger name="com.avaje.tests" level="DEBUG"/>
<!--<logger name="org.avaje.ebean.cache.QUERY" level="TRACE"/>-->
<!--<logger name="org.avaje.ebean.cache.BEAN" level="TRACE"/>-->
<!--<logger name="org.avaje.ebean.cache.COLL" level="TRACE"/>-->
<!--<logger name="org.avaje.ebean.cache.NATKEY" level="TRACE"/>-->
<!--<logger name="com.avaje.tests" level="DEBUG"/>-->
<!--<logger name="com.avaje.ebean.config.dbplatform.H2HistoryTrigger" level="DEBUG"/>-->
</configuration>