Compare commits

...
17 Commits
Author SHA1 Message Date
Rob Bygrave 861a8a4ee5 [maven-release-plugin] prepare release ebean-8.6.1 2016-10-25 22:23:04 +13:00
Rob Bygrave abe2f76d5c Bump pom to 8.6.1-SNAPSHOT 2016-10-25 22:22:16 +13:00
Rob Bygrave d0f75a940c #239 - Support Geometric types of Postgres, Also adding LineString, MultiLineString and MultiPoint 2016-10-25 22:19:33 +13:00
Rob Bygrave 44ad78b5e0 #239 - Support Geometric types of Postgres 2016-10-21 02:45:06 +13:00
Rob Bygrave 967b4de784 #239 - Support Geometric types of Postgres 2016-10-21 02:42:25 +13:00
Rob Bygrave ea45201905 [maven-release-plugin] prepare for next development iteration 2016-10-17 20:58:19 +13:00
Rob Bygrave 938f4ec9c2 [maven-release-plugin] prepare release ebean-8.5.1 2016-10-17 20:58:10 +13:00
Rob Bygrave 99bd2972d0 Bump pom version to 8.5.1-SNAPSHOT 2016-10-17 20:57:26 +13:00
Rob Bygrave deac291951 #835 - A query that includes a fetch() of a many that is @SoftDelete where all the rows are soft deleted returns incorrect results 2016-10-17 20:52:18 +13:00
Rob Bygrave 3161e24677 #835 - Tests for - A query that includes a fetch() of a many that is @SoftDelete where all the rows are soft deleted returns incorrect results 2016-10-17 20:51:22 +13:00
Rob Bygrave 37804bd083 Modify tests to avoid MySql keyword (mod) for column names 2016-10-17 20:50:48 +13:00
Rob Bygrave 0a2a987695 Modify tests to avoid Oracle keywords for column names 2016-10-15 17:03:32 +13:00
Rob Bygrave 4a085cb819 #834 - Oracle DDL for drop index and drop constraints incorrectly includes "if exits" 2016-10-15 17:02:44 +13:00
Rob Bygrave 67469ef4d3 No effective change - change Line endings to CR (from CRLF) 2016-10-15 14:39:20 +13:00
Rob Bygrave c3f43d503f #832 - Refactor: Change generated SQL to use "left join" rather than "left outer join" - change tests 2016-10-15 14:37:36 +13:00
Rob Bygrave 9158f46bb3 #832 - Refactor: Change generated SQL to use "left join" rather than "left outer join" 2016-10-15 14:36:11 +13:00
Rob Bygrave b3bfa88eb5 [maven-release-plugin] prepare for next development iteration 2016-10-15 01:14:29 +13:00
109 changed files with 3915 additions and 3715 deletions
+2 -2
View File
@@ -9,7 +9,7 @@
<groupId>org.avaje.ebean</groupId>
<artifactId>ebean</artifactId>
<version>8.4.2</version>
<version>8.6.1</version>
<packaging>jar</packaging>
<name>ebean</name>
@@ -37,7 +37,7 @@
<scm>
<developerConnection>scm:git:https://github.com/ebean-orm/ebean.git</developerConnection>
<tag>ebean-8.4.2</tag>
<tag>ebean-8.6.1</tag>
</scm>
<dependencies>
@@ -57,7 +57,7 @@ package com.avaje.ebean;
* where id in (
* select t0.id c0
* from o_customer t0
* left outer join o_address t1 on t1.id = t0.billing_address_id
* left join o_address t1 on t1.id = t0.billing_address_id
* where t0.status = ?
* and t1.country_code = ?
* and t0.id > ? )
@@ -82,7 +82,7 @@ public @interface Formula {
* as count, sum etc.
* </p>
* <p>
* The join string should start with either "left outer join" or "join".
* The join string should start with either "left join" or "join".
* </p>
*
* <p>
@@ -91,7 +91,7 @@ public class ClassLoadConfig {
/**
* Return true if the given class is present.
*/
protected boolean isPresent(String className) {
public boolean isPresent(String className) {
try {
forName(className);
return true;
@@ -112,6 +112,11 @@ public class ServerConfig {
*/
private boolean disableClasspathSearch;
/**
* The Geometry SRID value (default 4326).
*/
private int geometrySRID = 4326;
/**
* List of interesting classes such as entities, embedded, ScalarTypes,
* Listeners, Finders, Controllers etc.
@@ -876,6 +881,20 @@ public class ServerConfig {
this.migrationConfig = migrationConfig;
}
/**
* Return the Geometry SRID.
*/
public int getGeometrySRID() {
return geometrySRID;
}
/**
* Set the Geometry SRID.
*/
public void setGeometrySRID(int geometrySRID) {
this.geometrySRID = geometrySRID;
}
/**
* Return the time zone to use when reading/writing Timestamps via JDBC.
* <p>
@@ -2363,6 +2382,7 @@ public class ServerConfig {
}
loadDocStoreSettings(p);
geometrySRID = p.getInt("geometrySRID", geometrySRID);
disableL2Cache = p.getBoolean("disableL2Cache", disableL2Cache);
explicitTransactionBeginMode = p.getBoolean("explicitTransactionBeginMode", explicitTransactionBeginMode);
autoCommitMode = p.getBoolean("autoCommitMode", autoCommitMode);
@@ -19,6 +19,13 @@ public class DbPlatformTypeMapping {
private static final DbPlatformType JSON_BLOB_PLACEHOLDER = new DbPlatformType("jsonBlobPlaceholder");
private static final DbPlatformType JSON_VARCHAR_PLACEHOLDER = new DbPlatformType("jsonVarcharPlaceholder");
private static final DbPlatformType POINT = new DbPlatformType("point");
private static final DbPlatformType POLYGON = new DbPlatformType("polygon");
private static final DbPlatformType LINESTRING = new DbPlatformType("linestring");
private static final DbPlatformType MULTIPOINT = new DbPlatformType("multipoint");
private static final DbPlatformType MULTILINESTRING = new DbPlatformType("multilinestring");
private static final DbPlatformType MULTIPOLYGON = new DbPlatformType("multipolygon");
private final Map<DbType, DbPlatformType> typeMap = new HashMap<DbType, DbPlatformType>();
/**
@@ -62,6 +69,13 @@ public class DbPlatformTypeMapping {
// most commonly real maps to db float
put(DbType.REAL, new DbPlatformType("float"));
put(DbType.POINT, POINT);
put(DbType.POLYGON, POLYGON);
put(DbType.LINESTRING, LINESTRING);
put(DbType.MULTIPOINT, MULTIPOINT);
put(DbType.MULTILINESTRING, MULTILINESTRING);
put(DbType.MULTIPOLYGON, MULTIPOLYGON);
if (logicalTypes) {
// keep it logical for 2 layer DDL generation
put(DbType.VARCHAR, new DbPlatformType("varchar"));
@@ -36,6 +36,13 @@ public enum DbType {
UUID(ExtraDbTypes.UUID),
POINT(ExtraDbTypes.POINT),
POLYGON(ExtraDbTypes.POLYGON),
LINESTRING(ExtraDbTypes.LINESTRING),
MULTIPOINT(ExtraDbTypes.MULTIPOINT),
MULTILINESTRING(ExtraDbTypes.MULTILINESTRING),
MULTIPOLYGON(ExtraDbTypes.MULTIPOLYGON),
HSTORE(ExtraDbTypes.HSTORE),
JSON(ExtraDbTypes.JSON),
JSONB(ExtraDbTypes.JSONB),
@@ -40,4 +40,34 @@ public interface ExtraDbTypes {
*/
int JSONBlob = 5005;
/**
* Geo Point
*/
int POINT = 6000;
/**
* Geo Polygon
*/
int POLYGON = 6001;
/**
* Geo Point
*/
int LINESTRING = 6002;
/**
* Geo MultiPolygon
*/
int MULTIPOINT = 6005;
/**
* Geo MultiPolygon
*/
int MULTIPOLYGON = 6006;
/**
* Geo MultiPolygon
*/
int MULTILINESTRING = 6007;
}
@@ -74,6 +74,20 @@ public class PostgresPlatform extends DatabasePlatform {
dbTypeMap.put(DbType.TIMESTAMP, new DbPlatformType(tsType));
}
}
addGeoTypes(serverConfig.getGeometrySRID());
}
private void addGeoTypes(int srid) {
dbTypeMap.put(DbType.POINT, geoType("point",srid));
dbTypeMap.put(DbType.POLYGON, geoType("polygon",srid));
dbTypeMap.put(DbType.LINESTRING, geoType("linestring",srid));
dbTypeMap.put(DbType.MULTIPOINT, geoType("multipoint",srid));
dbTypeMap.put(DbType.MULTILINESTRING, geoType("multilinestring",srid));
dbTypeMap.put(DbType.MULTIPOLYGON, geoType("multipolygon",srid));
}
private DbPlatformType geoType(String type, int srid) {
return new DbPlatformType("geometry("+type+","+srid+")");
}
/**
@@ -11,6 +11,8 @@ public class Oracle10Ddl extends PlatformDdl {
super(platform);
this.dropTableIfExists = "drop table ";
this.dropSequenceIfExists = "drop sequence ";
this.dropConstraintIfExists = "drop constraint";
this.dropIndexIfExists = "drop index ";
this.dropTableCascade = " cascade constraints purge";
this.foreignKeyRestrict = "";
this.alterColumn = "modify";
@@ -0,0 +1,17 @@
package com.avaje.ebean.plugin;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebeaninternal.server.type.ScalarType;
import java.util.List;
/**
* A factory that provides extra types to Ebean.
*/
public interface ExtraTypeFactory {
/**
* Provide extra types to Ebean.
*/
List<? extends ScalarType> createTypes(ServerConfig config, Object objectMapper);
}
@@ -120,7 +120,7 @@ public final class TableJoin {
}
/**
* Return the type of join. LEFT OUTER JOIN etc.
* Return the type of join. LEFT JOIN etc.
*/
public SqlJoinType getType() {
return type;
@@ -21,7 +21,7 @@ public class DeployTableJoin {
private String table;
/**
* The type of join. LEFT OUTER etc.
* The type of join. LEFT JOIN etc.
*/
private SqlJoinType type = SqlJoinType.INNER;
@@ -222,8 +222,8 @@ public class DefaultDbSqlContext implements DbSqlContext {
sb.append(" ");
if (joinType == SqlJoinType.OUTER) {
if ("join".equals(sqlFormulaJoin.substring(0, 4).toLowerCase())) {
// prepend left outer as we are in the 'many' part
append(" left outer ");
// prepend left as we are in the 'many' part
append(" left ");
}
}
@@ -13,7 +13,7 @@ public enum SqlJoinType {
/**
* It is an outer join.
*/
OUTER("left outer join"),
OUTER("left join"),
/**
* It is automatically determined based on cardinality and optionality.
@@ -494,9 +494,6 @@ public class SqlTreeNodeBean implements SqlTreeNode {
if (desc.isSoftDelete()) {
query.addSoftDeletePredicate(desc.getSoftDeletePredicate(baseTableAlias));
}
for (int i = 0; i < children.length; i++) {
children[i].addSoftDeletePredicate(query);
}
}
public void addAsOfTableAlias(SpiQuery<?> query) {
@@ -522,6 +519,16 @@ public class SqlTreeNodeBean implements SqlTreeNode {
*/
public SqlJoinType appendFromBaseTable(DbSqlContext ctx, SqlJoinType joinType) {
SqlJoinType sqlJoinType = appendFromAsJoin(ctx, joinType);
if (desc.isSoftDelete()) {
// add the soft delete predicate to the join clause
ctx.append("and ").append(desc.getSoftDeletePredicate(ctx.getTableAlias(prefix))).append(" ");
}
return sqlJoinType;
}
private SqlJoinType appendFromAsJoin(DbSqlContext ctx, SqlJoinType joinType) {
if (nodeBeanProp instanceof BeanPropertyAssocMany<?>) {
BeanPropertyAssocMany<?> manyProp = (BeanPropertyAssocMany<?>) nodeBeanProp;
if (manyProp.isManyToMany()) {
@@ -105,7 +105,7 @@ public class SqlTreeNodeExtraJoin implements SqlTreeNode {
}
if (pathContainsMany) {
// "promote" to left outer as the path contains a many
// "promote" to left join as the path contains a many
joinType = SqlJoinType.OUTER;
}
if (!manyToMany) {
@@ -12,6 +12,7 @@ import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
import com.avaje.ebean.config.dbplatform.DbPlatformType;
import com.avaje.ebean.dbmigration.DbOffline;
import com.avaje.ebean.plugin.ExtraTypeFactory;
import com.avaje.ebeaninternal.server.core.bootup.BootupClasses;
import com.avaje.ebeaninternal.server.type.reflect.CheckImmutable;
import com.avaje.ebeaninternal.server.type.reflect.CheckImmutableResponse;
@@ -65,9 +66,11 @@ import java.util.Arrays;
import java.util.Calendar;
import java.util.Currency;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
@@ -208,6 +211,8 @@ public final class DefaultTypeManager implements TypeManager, KnownImmutable {
initialiseJodaTypes(jsonDateTime, config);
initialiseJacksonTypes(config);
loadTypesFromProviders(config, objectMapper);
if (bootupClasses != null) {
initialiseCustomScalarTypes(jsonDateTime, bootupClasses);
initialiseScalarConverters(bootupClasses);
@@ -215,6 +220,24 @@ public final class DefaultTypeManager implements TypeManager, KnownImmutable {
}
}
/**
* Load custom scalar types registered via ExtraTypeFactory and ServiceLoader.
*/
private void loadTypesFromProviders(ServerConfig config, Object objectMapper) {
ServiceLoader<ExtraTypeFactory> factories = ServiceLoader.load(ExtraTypeFactory.class);
Iterator<ExtraTypeFactory> iterator = factories.iterator();
if (iterator.hasNext()) {
// use the cacheFactory (via classpath service loader)
ExtraTypeFactory plugin = iterator.next();
List<? extends ScalarType> types = plugin.createTypes(config, objectMapper);
for (ScalarType type : types) {
logger.debug("adding ScalarType {}", type.getClass());
addCustomType(type);
}
}
}
private boolean isPostgres(DatabasePlatform databasePlatform) {
return databasePlatform.getName().toLowerCase().startsWith("postgre");
}
@@ -707,8 +730,7 @@ public final class DefaultTypeManager implements TypeManager, KnownImmutable {
}
}
add(scalarType);
customScalarTypes.add(scalarType);
addCustomType(scalarType);
} catch (Exception e) {
String msg = "Error loading ScalarType [" + cls.getName() + "]";
@@ -717,6 +739,11 @@ public final class DefaultTypeManager implements TypeManager, KnownImmutable {
}
}
private void addCustomType(ScalarType<?> scalarType) {
add(scalarType);
customScalarTypes.add(scalarType);
}
private Object initObjectMapper(ServerConfig serverConfig) {
Object objectMapper = serverConfig.getObjectMapper();
@@ -103,7 +103,7 @@ public class EbeanServer_eqlTest extends BaseTestCase {
query.setUseCache(false);
query.findUnique();
assertThat(query.getGeneratedSql()).contains("from o_customer t0 left outer join contact t1 on t1.customer_id = t0.id ");
assertThat(query.getGeneratedSql()).contains("from o_customer t0 left join contact t1 on t1.customer_id = t0.id ");
}
@Test
@@ -118,6 +118,6 @@ public class EbeanServer_eqlTest extends BaseTestCase {
query.setUseCache(false);
query.findUnique();
assertThat(query.getGeneratedSql()).contains("from o_customer t0 left outer join contact t1 on t1.customer_id = t0.id ");
assertThat(query.getGeneratedSql()).contains("from o_customer t0 left join contact t1 on t1.customer_id = t0.id ");
}
}
@@ -1,22 +1,22 @@
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());
}
}
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,164 +1,164 @@
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("a0");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0",c.getPropertyName());
c = mapping.get("b1");
assertEquals("b",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1",c.getPropertyName());
c = mapping.get("c2");
assertEquals("c",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c2",c.getPropertyName());
c = mapping.get("d3");
assertEquals("d",c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3",c.getPropertyName());
c = mapping.get("e4");
assertEquals("e",c.getDbColumn());
assertEquals(4, c.getIndexPos());
assertEquals("e4",c.getPropertyName());
}
public void test_withDatabaseFunction() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a a0,b b1, MONTH(MAKEDATE(2015, 241)) m2 , d d3 , e e4 ");
Map<String, Column> mapping = columnMapping.mapping();
assertEquals(5, mapping.size());
Column c = mapping.get("a0");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0",c.getPropertyName());
c = mapping.get("b1");
assertEquals("b",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1",c.getPropertyName());
c = mapping.get("m2");
assertEquals("MONTH(MAKEDATE(2015, 241))",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("m2",c.getPropertyName());
c = mapping.get("d3");
assertEquals("d",c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3",c.getPropertyName());
c = mapping.get("e4");
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("a0");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0",c.getPropertyName());
c = mapping.get("b1");
assertEquals("'b'",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1",c.getPropertyName());
c = mapping.get("c2");
assertEquals("\"c(blah)\"",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c2",c.getPropertyName());
c = mapping.get("d3");
assertEquals("d",c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3",c.getPropertyName());
c = mapping.get("e4");
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("a0");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0",c.getPropertyName());
c = mapping.get("b1");
assertEquals("b",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1",c.getPropertyName());
c = mapping.get("c2");
assertEquals("c",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c2",c.getPropertyName());
c = mapping.get("d3");
assertEquals("d",c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3",c.getPropertyName());
c = mapping.get("e4");
assertEquals("e",c.getDbColumn());
assertEquals(4, c.getIndexPos());
assertEquals("e4",c.getPropertyName());
}
public void test_withDatabaseFunction() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a a0,b b1, MONTH(MAKEDATE(2015, 241)) m2 , d d3 , e e4 ");
Map<String, Column> mapping = columnMapping.mapping();
assertEquals(5, mapping.size());
Column c = mapping.get("a0");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0",c.getPropertyName());
c = mapping.get("b1");
assertEquals("b",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1",c.getPropertyName());
c = mapping.get("m2");
assertEquals("MONTH(MAKEDATE(2015, 241))",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("m2",c.getPropertyName());
c = mapping.get("d3");
assertEquals("d",c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3",c.getPropertyName());
c = mapping.get("e4");
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("a0");
assertEquals("a",c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0",c.getPropertyName());
c = mapping.get("b1");
assertEquals("'b'",c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1",c.getPropertyName());
c = mapping.get("c2");
assertEquals("\"c(blah)\"",c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c2",c.getPropertyName());
c = mapping.get("d3");
assertEquals("d",c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3",c.getPropertyName());
c = mapping.get("e4");
assertEquals("e",c.getDbColumn());
assertEquals(4, c.getIndexPos());
assertEquals("e4",c.getPropertyName());
}
}
@@ -53,7 +53,7 @@ public class UpdateQueryTest extends BaseTestCase {
query.update();
assertThat(sqlOf(query)).contains("update o_customer set status=?, updtime=? where id in (select t0.id from o_customer t0 left outer join o_address t1 on t1.id = t0.billing_address_id where t0.status = ? and t1.country_code = ? and t0.id > ? )");
assertThat(sqlOf(query)).contains("update o_customer set status=?, updtime=? where id in (select t0.id from o_customer t0 left join o_address t1 on t1.id = t0.billing_address_id where t0.status = ? and t1.country_code = ? and t0.id > ? )");
}
@Test
@@ -1,101 +1,101 @@
package com.avaje.ebean.server.type;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebean.config.dbplatform.H2Platform;
import com.avaje.ebeaninternal.server.core.bootup.BootupClasses;
import com.avaje.ebeaninternal.server.type.CtCompoundType;
import com.avaje.ebeaninternal.server.type.DefaultTypeManager;
import com.avaje.ebeaninternal.server.type.RsetDataReader;
import com.avaje.ebeaninternal.server.type.ScalarDataReader;
import com.avaje.ebeaninternal.server.type.ScalarType;
import com.avaje.ebeaninternal.server.type.reflect.CheckImmutableResponse;
import com.avaje.tests.model.ivo.CMoney;
import com.avaje.tests.model.ivo.ExhangeCMoneyRate;
import com.avaje.tests.model.ivo.Money;
import org.junit.Assert;
import org.junit.Test;
import java.sql.SQLException;
import java.sql.Types;
import static org.assertj.core.api.Assertions.assertThat;
public class TestTypeManager extends BaseTestCase {
@Test
public void testEnumWithChar() throws SQLException {
DefaultTypeManager typeManager = createTypeManager();
ScalarType<?> dayOfWeekType = typeManager.createEnumScalarType(MyDayOfWeek.class);
Object val = dayOfWeekType.read(new DummyDataReader("MONDAY "));
assertThat(val).isEqualTo(MyDayOfWeek.MONDAY);
val = dayOfWeekType.read(new DummyDataReader("TUESDAY "));
assertThat(val).isEqualTo(MyDayOfWeek.TUESDAY);
val = dayOfWeekType.read(new DummyDataReader("WEDNESDAY"));
assertThat(val).isEqualTo(MyDayOfWeek.WEDNESDAY);
val = dayOfWeekType.read(new DummyDataReader("THURSDAY "));
assertThat(val).isEqualTo(MyDayOfWeek.THURSDAY);
val = dayOfWeekType.read(new DummyDataReader("FRIDAY "));
assertThat(val).isEqualTo(MyDayOfWeek.FRIDAY);
}
@Test
public void test() {
DefaultTypeManager typeManager = createTypeManager();
CheckImmutableResponse checkImmutable = typeManager.checkImmutable(Money.class);
Assert.assertTrue(checkImmutable.isImmutable());
checkImmutable = typeManager.checkImmutable(CMoney.class);
Assert.assertTrue(checkImmutable.isImmutable());
ScalarDataReader<?> dataReader = typeManager
.recursiveCreateScalarDataReader(ExhangeCMoneyRate.class);
Assert.assertTrue(dataReader instanceof CtCompoundType<?>);
dataReader = typeManager.recursiveCreateScalarDataReader(CMoney.class);
Assert.assertTrue(dataReader instanceof CtCompoundType<?>);
ScalarType<?> scalarType = typeManager.recursiveCreateScalarTypes(Money.class);
Assert.assertTrue(scalarType.getJdbcType() == Types.DECIMAL);
Assert.assertTrue(!scalarType.isJdbcNative());
Assert.assertEquals(Money.class, scalarType.getType());
}
private DefaultTypeManager createTypeManager() {
ServerConfig serverConfig = new ServerConfig();
serverConfig.setDatabasePlatform(new H2Platform());
BootupClasses bootupClasses = new BootupClasses();
return new DefaultTypeManager(serverConfig, bootupClasses);
}
/**
* Test double DataReader implementation.
*/
private static class DummyDataReader extends RsetDataReader {
String val;
public DummyDataReader(String val) {
super(null, null);
this.val = val;
}
@Override
public String getString() throws SQLException {
return val;
}
}
}
package com.avaje.ebean.server.type;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebean.config.dbplatform.H2Platform;
import com.avaje.ebeaninternal.server.core.bootup.BootupClasses;
import com.avaje.ebeaninternal.server.type.CtCompoundType;
import com.avaje.ebeaninternal.server.type.DefaultTypeManager;
import com.avaje.ebeaninternal.server.type.RsetDataReader;
import com.avaje.ebeaninternal.server.type.ScalarDataReader;
import com.avaje.ebeaninternal.server.type.ScalarType;
import com.avaje.ebeaninternal.server.type.reflect.CheckImmutableResponse;
import com.avaje.tests.model.ivo.CMoney;
import com.avaje.tests.model.ivo.ExhangeCMoneyRate;
import com.avaje.tests.model.ivo.Money;
import org.junit.Assert;
import org.junit.Test;
import java.sql.SQLException;
import java.sql.Types;
import static org.assertj.core.api.Assertions.assertThat;
public class TestTypeManager extends BaseTestCase {
@Test
public void testEnumWithChar() throws SQLException {
DefaultTypeManager typeManager = createTypeManager();
ScalarType<?> dayOfWeekType = typeManager.createEnumScalarType(MyDayOfWeek.class);
Object val = dayOfWeekType.read(new DummyDataReader("MONDAY "));
assertThat(val).isEqualTo(MyDayOfWeek.MONDAY);
val = dayOfWeekType.read(new DummyDataReader("TUESDAY "));
assertThat(val).isEqualTo(MyDayOfWeek.TUESDAY);
val = dayOfWeekType.read(new DummyDataReader("WEDNESDAY"));
assertThat(val).isEqualTo(MyDayOfWeek.WEDNESDAY);
val = dayOfWeekType.read(new DummyDataReader("THURSDAY "));
assertThat(val).isEqualTo(MyDayOfWeek.THURSDAY);
val = dayOfWeekType.read(new DummyDataReader("FRIDAY "));
assertThat(val).isEqualTo(MyDayOfWeek.FRIDAY);
}
@Test
public void test() {
DefaultTypeManager typeManager = createTypeManager();
CheckImmutableResponse checkImmutable = typeManager.checkImmutable(Money.class);
Assert.assertTrue(checkImmutable.isImmutable());
checkImmutable = typeManager.checkImmutable(CMoney.class);
Assert.assertTrue(checkImmutable.isImmutable());
ScalarDataReader<?> dataReader = typeManager
.recursiveCreateScalarDataReader(ExhangeCMoneyRate.class);
Assert.assertTrue(dataReader instanceof CtCompoundType<?>);
dataReader = typeManager.recursiveCreateScalarDataReader(CMoney.class);
Assert.assertTrue(dataReader instanceof CtCompoundType<?>);
ScalarType<?> scalarType = typeManager.recursiveCreateScalarTypes(Money.class);
Assert.assertTrue(scalarType.getJdbcType() == Types.DECIMAL);
Assert.assertTrue(!scalarType.isJdbcNative());
Assert.assertEquals(Money.class, scalarType.getType());
}
private DefaultTypeManager createTypeManager() {
ServerConfig serverConfig = new ServerConfig();
serverConfig.setDatabasePlatform(new H2Platform());
BootupClasses bootupClasses = new BootupClasses();
return new DefaultTypeManager(serverConfig, bootupClasses);
}
/**
* Test double DataReader implementation.
*/
private static class DummyDataReader extends RsetDataReader {
String val;
public DummyDataReader(String val) {
super(null, null);
this.val = val;
}
@Override
public String getString() throws SQLException {
return val;
}
}
}
@@ -1,189 +1,189 @@
package com.avaje.ebean.text;
import com.avaje.ebean.FetchPath;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PathPropertiesTests {
@Test
public void test_noParentheses() {
PathProperties s0 = PathProperties.parse("id,name");
assertEquals(1, s0.getPathProps().size());
assertTrue(s0.getProperties(null).contains("id"));
assertTrue(s0.getProperties(null).contains("name"));
assertFalse(s0.getProperties(null).contains("status"));
}
@Test
public void test_noParentheses_needTrim() {
PathProperties s0 = PathProperties.parse(" id, name ");
assertEquals(1, s0.getPathProps().size());
assertTrue(s0.getProperties(null).contains("id"));
assertTrue(s0.getProperties(null).contains("name"));
assertFalse(s0.getProperties(null).contains("status"));
}
@Test
public void test_withParentheses() {
PathProperties s0 = PathProperties.parse("(id,name)");
assertEquals(1, s0.getPathProps().size());
assertTrue(s0.getProperties(null).contains("id"));
assertTrue(s0.getProperties(null).contains("name"));
assertFalse(s0.getProperties(null).contains("status"));
}
@Test
public void test_withColon() {
PathProperties s0 = PathProperties.parse(":(id,name)");
assertEquals(1, s0.getPathProps().size());
assertTrue(s0.getProperties(null).contains("id"));
assertTrue(s0.getProperties(null).contains("name"));
assertFalse(s0.getProperties(null).contains("status"));
}
@Test
public void test_nested() {
PathProperties s1 = PathProperties.parse("id,name,shipAddr(*)");
assertEquals(2, s1.getPathProps().size());
assertEquals(3, s1.getProperties(null).size());
assertTrue(s1.getProperties(null).contains("id"));
assertTrue(s1.getProperties(null).contains("name"));
assertTrue(s1.getProperties(null).contains("shipAddr"));
assertTrue(s1.getProperties("shipAddr").contains("*"));
assertEquals(1, s1.getProperties("shipAddr").size());
}
@Test
public void test_withParenthesesColonNested() {
PathProperties s1 = PathProperties.parse(":(id,name,shipAddr(*))");
assertEquals(2, s1.getPathProps().size());
assertEquals(3, s1.getProperties(null).size());
assertTrue(s1.getProperties(null).contains("id"));
assertTrue(s1.getProperties(null).contains("name"));
assertTrue(s1.getProperties(null).contains("shipAddr"));
assertTrue(s1.getProperties("shipAddr").contains("*"));
assertEquals(1, s1.getProperties("shipAddr").size());
}
@Test
public void test_add() {
PathProperties root = PathProperties.parse("status,date");
root.addNested("customer", PathProperties.parse("id,name"));
FetchPath expect = PathProperties.parse("status,date,customer(id,name)");
assertThat(root.toString()).isEqualTo(expect.toString());
}
@Test
public void test_add_nested() {
PathProperties root = PathProperties.parse("status,date");
root.addNested("customer", PathProperties.parse("id,name,address(line1,city)"));
FetchPath expect = PathProperties.parse("status,date,customer(id,name,address(line1,city))");
assertThat(root.toString()).isEqualTo(expect.toString());
}
@Test
public void test_all_properties() {
FetchPath root = PathProperties.parse("*");
assertThat(root.getProperties(null)).containsExactly("*");
}
@Test
public void test_all_properties_multipleLevels() {
PathProperties root = PathProperties.parse("*,customer(*)");
//PathProperties.Props rootProps = root.getProps(null);
PathProperties.Props customerProps = root.getProps("customer");
assertThat(root.getProperties(null)).containsExactly("*", "customer");
assertThat(customerProps.getPropertiesAsString()).isEqualTo("*");
}
@Test
public void test_includesProperty_when_wildcardUsed() {
PathProperties root = PathProperties.parse("*,customer(*)");
assertTrue(root.includesProperty("id"));
assertTrue(root.includesProperty("name"));
assertTrue(root.includesProperty("customer.id"));
assertTrue(root.includesProperty("customer.name"));
assertFalse(root.includesProperty("details.id"));
assertTrue(root.includesProperty("details"));
assertFalse(root.includesPath("details"));
}
@Test
public void test_includesProperty_when_specificPropertiesUsed() {
PathProperties root = PathProperties.parse("id,name,customer(*,billingAddress(city))");
assertTrue(root.includesProperty("id"));
assertTrue(root.includesProperty("name"));
assertFalse(root.includesProperty("status"));
assertTrue(root.includesProperty("customer.id"));
assertTrue(root.includesProperty("customer.foo"));
assertTrue(root.includesProperty("customer.billingAddress"));
assertTrue(root.includesProperty("customer.billingAddress.city"));
assertFalse(root.includesPath("customer.shippingAddress"));
assertFalse(root.includesPath("customer", "shippingAddress"));
assertFalse(root.includesProperty("customer.shippingAddress.city"));
assertTrue(root.includesPath(null));
assertTrue(root.includesPath("customer"));
assertTrue(root.includesPath("customer.billingAddress"));
assertTrue(root.includesPath("customer", "billingAddress"));
assertFalse(root.includesPath("customer.shippingAddress"));
assertFalse(root.includesPath("details"));
}
@Test
public void test_includesPropertyWithPrefix() {
PathProperties root = PathProperties.parse("id,name,customer(*,billingAddress(city))");
assertTrue(root.includesProperty("customer", "id"));
assertTrue(root.includesProperty("customer", "billingAddress"));
assertTrue(root.includesProperty("customer.billingAddress", "city"));
assertFalse(root.includesPath("customer", "shippingAddress"));
assertFalse(root.includesProperty("customer.shippingAddress", "city"));
}
@Test
public void test_includesPathWithPrefix() {
PathProperties root = PathProperties.parse("id,name,customer(*,billingAddress(city))");
assertTrue(root.includesPath(null, "customer"));
assertTrue(root.includesPath("customer", "billingAddress"));
assertFalse(root.includesPath(null, "details"));
assertFalse(root.includesPath("customer", "shippingAddress"));
}
}
package com.avaje.ebean.text;
import com.avaje.ebean.FetchPath;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PathPropertiesTests {
@Test
public void test_noParentheses() {
PathProperties s0 = PathProperties.parse("id,name");
assertEquals(1, s0.getPathProps().size());
assertTrue(s0.getProperties(null).contains("id"));
assertTrue(s0.getProperties(null).contains("name"));
assertFalse(s0.getProperties(null).contains("status"));
}
@Test
public void test_noParentheses_needTrim() {
PathProperties s0 = PathProperties.parse(" id, name ");
assertEquals(1, s0.getPathProps().size());
assertTrue(s0.getProperties(null).contains("id"));
assertTrue(s0.getProperties(null).contains("name"));
assertFalse(s0.getProperties(null).contains("status"));
}
@Test
public void test_withParentheses() {
PathProperties s0 = PathProperties.parse("(id,name)");
assertEquals(1, s0.getPathProps().size());
assertTrue(s0.getProperties(null).contains("id"));
assertTrue(s0.getProperties(null).contains("name"));
assertFalse(s0.getProperties(null).contains("status"));
}
@Test
public void test_withColon() {
PathProperties s0 = PathProperties.parse(":(id,name)");
assertEquals(1, s0.getPathProps().size());
assertTrue(s0.getProperties(null).contains("id"));
assertTrue(s0.getProperties(null).contains("name"));
assertFalse(s0.getProperties(null).contains("status"));
}
@Test
public void test_nested() {
PathProperties s1 = PathProperties.parse("id,name,shipAddr(*)");
assertEquals(2, s1.getPathProps().size());
assertEquals(3, s1.getProperties(null).size());
assertTrue(s1.getProperties(null).contains("id"));
assertTrue(s1.getProperties(null).contains("name"));
assertTrue(s1.getProperties(null).contains("shipAddr"));
assertTrue(s1.getProperties("shipAddr").contains("*"));
assertEquals(1, s1.getProperties("shipAddr").size());
}
@Test
public void test_withParenthesesColonNested() {
PathProperties s1 = PathProperties.parse(":(id,name,shipAddr(*))");
assertEquals(2, s1.getPathProps().size());
assertEquals(3, s1.getProperties(null).size());
assertTrue(s1.getProperties(null).contains("id"));
assertTrue(s1.getProperties(null).contains("name"));
assertTrue(s1.getProperties(null).contains("shipAddr"));
assertTrue(s1.getProperties("shipAddr").contains("*"));
assertEquals(1, s1.getProperties("shipAddr").size());
}
@Test
public void test_add() {
PathProperties root = PathProperties.parse("status,date");
root.addNested("customer", PathProperties.parse("id,name"));
FetchPath expect = PathProperties.parse("status,date,customer(id,name)");
assertThat(root.toString()).isEqualTo(expect.toString());
}
@Test
public void test_add_nested() {
PathProperties root = PathProperties.parse("status,date");
root.addNested("customer", PathProperties.parse("id,name,address(line1,city)"));
FetchPath expect = PathProperties.parse("status,date,customer(id,name,address(line1,city))");
assertThat(root.toString()).isEqualTo(expect.toString());
}
@Test
public void test_all_properties() {
FetchPath root = PathProperties.parse("*");
assertThat(root.getProperties(null)).containsExactly("*");
}
@Test
public void test_all_properties_multipleLevels() {
PathProperties root = PathProperties.parse("*,customer(*)");
//PathProperties.Props rootProps = root.getProps(null);
PathProperties.Props customerProps = root.getProps("customer");
assertThat(root.getProperties(null)).containsExactly("*", "customer");
assertThat(customerProps.getPropertiesAsString()).isEqualTo("*");
}
@Test
public void test_includesProperty_when_wildcardUsed() {
PathProperties root = PathProperties.parse("*,customer(*)");
assertTrue(root.includesProperty("id"));
assertTrue(root.includesProperty("name"));
assertTrue(root.includesProperty("customer.id"));
assertTrue(root.includesProperty("customer.name"));
assertFalse(root.includesProperty("details.id"));
assertTrue(root.includesProperty("details"));
assertFalse(root.includesPath("details"));
}
@Test
public void test_includesProperty_when_specificPropertiesUsed() {
PathProperties root = PathProperties.parse("id,name,customer(*,billingAddress(city))");
assertTrue(root.includesProperty("id"));
assertTrue(root.includesProperty("name"));
assertFalse(root.includesProperty("status"));
assertTrue(root.includesProperty("customer.id"));
assertTrue(root.includesProperty("customer.foo"));
assertTrue(root.includesProperty("customer.billingAddress"));
assertTrue(root.includesProperty("customer.billingAddress.city"));
assertFalse(root.includesPath("customer.shippingAddress"));
assertFalse(root.includesPath("customer", "shippingAddress"));
assertFalse(root.includesProperty("customer.shippingAddress.city"));
assertTrue(root.includesPath(null));
assertTrue(root.includesPath("customer"));
assertTrue(root.includesPath("customer.billingAddress"));
assertTrue(root.includesPath("customer", "billingAddress"));
assertFalse(root.includesPath("customer.shippingAddress"));
assertFalse(root.includesPath("details"));
}
@Test
public void test_includesPropertyWithPrefix() {
PathProperties root = PathProperties.parse("id,name,customer(*,billingAddress(city))");
assertTrue(root.includesProperty("customer", "id"));
assertTrue(root.includesProperty("customer", "billingAddress"));
assertTrue(root.includesProperty("customer.billingAddress", "city"));
assertFalse(root.includesPath("customer", "shippingAddress"));
assertFalse(root.includesProperty("customer.shippingAddress", "city"));
}
@Test
public void test_includesPathWithPrefix() {
PathProperties root = PathProperties.parse("id,name,customer(*,billingAddress(city))");
assertTrue(root.includesPath(null, "customer"));
assertTrue(root.includesPath("customer", "billingAddress"));
assertFalse(root.includesPath(null, "details"));
assertFalse(root.includesPath("customer", "shippingAddress"));
}
}
@@ -1,30 +1,30 @@
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();
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();
assertTrue(s, s.contains("[order_id, sum"));
}
}
@@ -1,34 +1,34 @@
package com.avaje.tests.autofetch;
import com.avaje.ebean.Ebean;
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) {
ResetBasicData.reset();
MainAutoQueryTune1 me = new MainAutoQueryTune1();
me.tuneJoin();
}
private void tuneJoin() {
List<Order> list = Ebean.find(Order.class)
.setAutoTune(true)
.fetch("customer")
.where()
.eq("status", Order.Status.NEW)
.eq("customer.name", "Rob")
.order().asc("id")
.findList();
for (Order order : list) {
order.getId();
order.getOrderDate();
}
}
}
package com.avaje.tests.autofetch;
import com.avaje.ebean.Ebean;
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) {
ResetBasicData.reset();
MainAutoQueryTune1 me = new MainAutoQueryTune1();
me.tuneJoin();
}
private void tuneJoin() {
List<Order> list = Ebean.find(Order.class)
.setAutoTune(true)
.fetch("customer")
.where()
.eq("status", Order.Status.NEW)
.eq("customer.name", "Rob")
.order().asc("id")
.findList();
for (Order order : list) {
order.getId();
order.getOrderDate();
}
}
}
@@ -1,29 +1,29 @@
package com.avaje.tests.basic;
import java.sql.Connection;
import org.avaje.datasource.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)
{
}
}
package com.avaje.tests.basic;
import java.sql.Connection;
import org.avaje.datasource.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,53 +1,53 @@
package com.avaje.tests.basic;
import java.sql.Date;
import com.avaje.ebean.cache.ServerCache;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 TestBeanReferenceRefresh extends BaseTestCase {
@Test
public void testMe() {
ResetBasicData.reset();
ServerCache beanCache = Ebean.getServerCacheManager().getBeanCache(Order.class);
beanCache.clear();
Order order = Ebean.getReference(Order.class, 1);
Assert.assertTrue(Ebean.getBeanState(order).isReference());
// invoke lazy loading
Date orderDate = order.getOrderDate();
Assert.assertNotNull(orderDate);
Customer customer = order.getCustomer();
Assert.assertNotNull(customer);
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);
}
}
package com.avaje.tests.basic;
import java.sql.Date;
import com.avaje.ebean.cache.ServerCache;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 TestBeanReferenceRefresh extends BaseTestCase {
@Test
public void testMe() {
ResetBasicData.reset();
ServerCache beanCache = Ebean.getServerCacheManager().getBeanCache(Order.class);
beanCache.clear();
Order order = Ebean.getReference(Order.class, 1);
Assert.assertTrue(Ebean.getBeanState(order).isReference());
// invoke lazy loading
Date orderDate = order.getOrderDate();
Assert.assertNotNull(orderDate);
Customer customer = order.getCustomer();
Assert.assertNotNull(customer);
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);
}
}
@@ -1,35 +1,35 @@
package com.avaje.tests.basic;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.PFile;
import com.avaje.tests.model.basic.PFileContent;
public class TestDeleteImportedPartial extends BaseTestCase {
@Test
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);
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 org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.PFile;
import com.avaje.tests.model.basic.PFileContent;
public class TestDeleteImportedPartial extends BaseTestCase {
@Test
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);
PFile file1 = Ebean.find(PFile.class, id);
PFileContent content1 = Ebean.find(PFileContent.class, contentId);
Assert.assertNull(file1);
Assert.assertNull(content1);
}
}
@@ -1,24 +1,24 @@
package com.avaje.tests.basic;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Order;
import org.junit.Assert;
import org.junit.Test;
import javax.persistence.PersistenceException;
public class TestErrorBindLog extends BaseTestCase {
@Test
public void test() {
try {
Ebean.find(Order.class).where().gt("id", "JUNK").findList();
} catch (PersistenceException e) {
String msg = e.getMessage();
Assert.assertTrue(msg.contains("Bind values:"));
}
}
}
package com.avaje.tests.basic;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Order;
import org.junit.Assert;
import org.junit.Test;
import javax.persistence.PersistenceException;
public class TestErrorBindLog extends BaseTestCase {
@Test
public void test() {
try {
Ebean.find(Order.class).where().gt("id", "JUNK").findList();
} catch (PersistenceException e) {
String msg = e.getMessage();
Assert.assertTrue(msg.contains("Bind values:"));
}
}
}
@@ -124,7 +124,7 @@ public class TestLimitQuery extends BaseTestCase {
query.findList();
sql = query.getGeneratedSql();
hasDetailsJoin = sql.contains("left outer join o_order_detail");
hasDetailsJoin = sql.contains("left join o_order_detail");
hasLimit = sql.contains("limit 10");
hasSelectedDetails = sql.contains("od.id");
hasDistinct = sql.contains("select distinct");
@@ -1,61 +1,61 @@
package com.avaje.tests.basic;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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);
Assert.assertNotNull(car.getId());
Assert.assertNotNull(engine.getEngineId());
Assert.assertNotNull(gearBox.getId());
Ebean.commitTransaction();
} finally {
Ebean.endTransaction();
}
OCar c2 = Ebean.find(OCar.class, car.getId());
Assert.assertNotNull(c2);
Assert.assertNotNull(c2.getEngine());
// gearBox not assigned yet
Assert.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());
Assert.assertNotNull(c3);
Assert.assertNotNull(c3.getEngine());
Assert.assertNotNull(c3.getGearBox());
}
}
package com.avaje.tests.basic;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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);
Assert.assertNotNull(car.getId());
Assert.assertNotNull(engine.getEngineId());
Assert.assertNotNull(gearBox.getId());
Ebean.commitTransaction();
} finally {
Ebean.endTransaction();
}
OCar c2 = Ebean.find(OCar.class, car.getId());
Assert.assertNotNull(c2);
Assert.assertNotNull(c2.getEngine());
// gearBox not assigned yet
Assert.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());
Assert.assertNotNull(c3);
Assert.assertNotNull(c3.getEngine());
Assert.assertNotNull(c3.getGearBox());
}
}
@@ -1,38 +1,38 @@
package com.avaje.tests.basic;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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.isEmpty());
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 org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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.isEmpty());
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,48 +1,48 @@
package com.avaje.tests.basic;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
public void testCountOrderBy() {
ResetBasicData.reset();
Query<Order> query = Ebean.find(Order.class).setAutoTune(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).setAutoTune(false).setForUpdate(false)
.setMaxRows(1).order().asc("orderDate").order().desc("id");
int rc = query.findList().size();
Assert.assertTrue(rc > 0);
Assert.assertTrue(!query.getGeneratedSql().toLowerCase().contains("for update"));
query = Ebean.find(Order.class).setAutoTune(false).setForUpdate(true).setMaxRows(1).order()
.asc("orderDate").order().desc("id");
rc = query.findList().size();
Assert.assertTrue(rc > 0);
Assert.assertTrue(query.getGeneratedSql().toLowerCase().contains("for update"));
}
}
package com.avaje.tests.basic;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
public void testCountOrderBy() {
ResetBasicData.reset();
Query<Order> query = Ebean.find(Order.class).setAutoTune(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).setAutoTune(false).setForUpdate(false)
.setMaxRows(1).order().asc("orderDate").order().desc("id");
int rc = query.findList().size();
Assert.assertTrue(rc > 0);
Assert.assertTrue(!query.getGeneratedSql().toLowerCase().contains("for update"));
query = Ebean.find(Order.class).setAutoTune(false).setForUpdate(true).setMaxRows(1).order()
.asc("orderDate").order().desc("id");
rc = query.findList().size();
Assert.assertTrue(rc > 0);
Assert.assertTrue(query.getGeneratedSql().toLowerCase().contains("for update"));
}
}
@@ -1,75 +1,75 @@
package com.avaje.tests.basic;
import com.avaje.ebean.BaseTestCase;
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.ResetBasicData;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class TestQueryWithCache extends BaseTestCase {
@Test
public void testCountryDeploy() {
ResetBasicData.reset();
SpiEbeanServer server = (SpiEbeanServer) Ebean.getServer(null);
BeanDescriptor<Country> beanDescriptor = server.getBeanDescriptor(Country.class);
CacheOptions cacheOptions = beanDescriptor.getCacheOptions();
assertNotNull(cacheOptions);
assertTrue(cacheOptions.isReadOnly());
assertTrue(beanDescriptor.isCacheSharableBeans());
ServerCacheManager serverCacheManager = server.getServerCacheManager();
serverCacheManager.clear(Country.class);
ServerCache beanCache = serverCacheManager.getBeanCache(Country.class);
assertEquals(0, beanCache.size());
Country nz1 = Ebean.getReference(Country.class, "NZ");
assertEquals(0, beanCache.size());
// has the effect of loading the cache via lazy loading
nz1.getName();
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").setAutoTune(false).setUseCache(false)
.findUnique();
assertTrue(nz2 == nz2b);
assertTrue(nz2 == nz3);
assertTrue(nz3 != nz4);
}
@Test
public void testSkipCache() {
ResetBasicData.reset();
Ebean.find(Country.class, "NZ");
Query<Country> query = Ebean.find(Country.class).setId("NZ").setUseCache(false);
query.findUnique();
assertThat(query.getGeneratedSql()).isNotNull();
}
}
package com.avaje.tests.basic;
import com.avaje.ebean.BaseTestCase;
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.ResetBasicData;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class TestQueryWithCache extends BaseTestCase {
@Test
public void testCountryDeploy() {
ResetBasicData.reset();
SpiEbeanServer server = (SpiEbeanServer) Ebean.getServer(null);
BeanDescriptor<Country> beanDescriptor = server.getBeanDescriptor(Country.class);
CacheOptions cacheOptions = beanDescriptor.getCacheOptions();
assertNotNull(cacheOptions);
assertTrue(cacheOptions.isReadOnly());
assertTrue(beanDescriptor.isCacheSharableBeans());
ServerCacheManager serverCacheManager = server.getServerCacheManager();
serverCacheManager.clear(Country.class);
ServerCache beanCache = serverCacheManager.getBeanCache(Country.class);
assertEquals(0, beanCache.size());
Country nz1 = Ebean.getReference(Country.class, "NZ");
assertEquals(0, beanCache.size());
// has the effect of loading the cache via lazy loading
nz1.getName();
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").setAutoTune(false).setUseCache(false)
.findUnique();
assertTrue(nz2 == nz2b);
assertTrue(nz2 == nz3);
assertTrue(nz3 != nz4);
}
@Test
public void testSkipCache() {
ResetBasicData.reset();
Ebean.find(Country.class, "NZ");
Query<Country> query = Ebean.find(Country.class).setId("NZ").setUseCache(false);
query.findUnique();
assertThat(query.getGeneratedSql()).isNotNull();
}
}
@@ -1,19 +1,19 @@
package com.avaje.tests.basic.encrypt;
import com.avaje.ebean.config.EncryptKey;
public class BasicEncryptKey implements EncryptKey {
private final String key;
public BasicEncryptKey(String key) {
this.key = key;
}
public String getStringValue() {
return key;
}
}
package com.avaje.tests.basic.encrypt;
import com.avaje.ebean.config.EncryptKey;
public class BasicEncryptKey implements EncryptKey {
private final String key;
public BasicEncryptKey(String key) {
this.key = key;
}
public String getStringValue() {
return key;
}
}
@@ -1,50 +1,50 @@
package com.avaje.tests.basic.event;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.TWithPreInsert;
public class TestPreInsertValidation extends BaseTestCase {
@Test
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 and name set in preInsert
Assert.assertNotNull(e.getId());
Assert.assertNotNull(e.getName());
TWithPreInsert e1 = Ebean.find(TWithPreInsert.class, e.getId());
e1.setTitle("Missus");
Ebean.save(e1);
}
@Test
public void testStatelessUpdate() {
TWithPreInsert e = new TWithPreInsert();
e.setName("BeanForUpdateTest");
Ebean.save(e);
TWithPreInsert bean2 = new TWithPreInsert();
bean2.setId(e.getId());
bean2.setName("stateless-update-name");
bean2.setTitle(null);
Ebean.update(bean2);
// title set on preUpdate
Assert.assertNotNull(bean2.getTitle());
}
}
package com.avaje.tests.basic.event;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.TWithPreInsert;
public class TestPreInsertValidation extends BaseTestCase {
@Test
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 and name set in preInsert
Assert.assertNotNull(e.getId());
Assert.assertNotNull(e.getName());
TWithPreInsert e1 = Ebean.find(TWithPreInsert.class, e.getId());
e1.setTitle("Missus");
Ebean.save(e1);
}
@Test
public void testStatelessUpdate() {
TWithPreInsert e = new TWithPreInsert();
e.setName("BeanForUpdateTest");
Ebean.save(e);
TWithPreInsert bean2 = new TWithPreInsert();
bean2.setId(e.getId());
bean2.setName("stateless-update-name");
bean2.setTitle(null);
Ebean.update(bean2);
// title set on preUpdate
Assert.assertNotNull(bean2.getTitle());
}
}
@@ -1,32 +1,32 @@
package com.avaje.tests.basic.join;
import java.util.List;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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);
}
}
package com.avaje.tests.basic.join;
import java.util.List;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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);
}
}
@@ -1,207 +1,207 @@
package com.avaje.tests.batchload;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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();
Assert.assertNotNull(c.getContacts());
Assert.assertTrue("no contacts on test customer 1", !c.getContacts().isEmpty());
// 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();
Assert.assertNotNull(order);
Assert.assertTrue(!order.isEmpty());
Customer customer = order.get(0).getCustomer();
Assert.assertNotNull(customer);
Assert.assertEquals(1, customer.getId().intValue());
// this should lazily fetch the contacts
List<Contact> contacts = customer.getContacts();
Assert.assertNotNull(contacts);
Assert.assertTrue("contacts not lazily fetched", !contacts.isEmpty());
} 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();
Assert.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.isEmpty()) {
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 org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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();
Assert.assertNotNull(c.getContacts());
Assert.assertTrue("no contacts on test customer 1", !c.getContacts().isEmpty());
// 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();
Assert.assertNotNull(order);
Assert.assertTrue(!order.isEmpty());
Customer customer = order.get(0).getCustomer();
Assert.assertNotNull(customer);
Assert.assertEquals(1, customer.getId().intValue());
// this should lazily fetch the contacts
List<Contact> contacts = customer.getContacts();
Assert.assertNotNull(contacts);
Assert.assertTrue("contacts not lazily fetched", !contacts.isEmpty());
} 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();
Assert.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.isEmpty()) {
System.err.println("Seen Exceptions:");
for (Throwable exception : exceptions) {
exception.printStackTrace();
}
Assert.fail();
}
}
}
@@ -1,31 +1,31 @@
package com.avaje.tests.batchload;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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 org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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();
}
}
@@ -35,7 +35,7 @@ public class TestQueryJoinToAssocOne extends BaseTestCase {
String secondaryQuery = trimSql(loggedSql.get(1), 1);
assertThat(secondaryQuery).contains("select t0.order_id, t0.id,");
assertThat(secondaryQuery).contains(" from o_order_detail t0 left outer join o_product t1");
assertThat(secondaryQuery).contains(" from o_order_detail t0 left join o_product t1");
assertThat(secondaryQuery).contains(" (t0.order_id) in (?");
assertThat(secondaryQuery).contains(" order by t0.order_id, t0.id");
}
@@ -62,7 +62,7 @@ public class TestQueryJoinToAssocOne extends BaseTestCase {
String secondaryQuery = trimSql(loggedSql.get(1), 1);
assertThat(secondaryQuery).contains("select t0.order_id, t0.id,");
assertThat(secondaryQuery).contains(" from o_order_detail t0 left outer join o_product t1");
assertThat(secondaryQuery).contains(" from o_order_detail t0 left join o_product t1");
assertThat(secondaryQuery).contains(" (t0.order_id) in (?");
assertThat(secondaryQuery).contains(" order by t0.order_id, t0.id");
}
@@ -102,7 +102,7 @@ public class TestQueryJoinToAssocOne extends BaseTestCase {
String secondaryQuery = trimSql(loggedSql.get(1), 1);
assertThat(secondaryQuery).contains("select t0.order_id, t0.id,");
assertThat(secondaryQuery).contains(" from o_order_detail t0 left outer join o_product t1");
assertThat(secondaryQuery).contains(" from o_order_detail t0 left join o_product t1");
assertThat(secondaryQuery).contains(" (t0.order_id) in (?");
assertThat(secondaryQuery).contains(" order by t0.order_id, t0.id");
}
@@ -138,6 +138,6 @@ public class TestQueryJoinToAssocOne extends BaseTestCase {
String originQuery = trimSql(loggedSql.get(0), 5);
assertThat(originQuery).contains("select t0.id, t0.status, t0.ship_date, t1.id, t1.order_qty, t1.unit_price");
assertThat(originQuery).contains(" from o_order t0 left outer join o_order_detail t1 ");
assertThat(originQuery).contains(" from o_order t0 left join o_order_detail t1 ");
}
}
@@ -141,11 +141,11 @@ public class TestSecondaryQueries extends BaseTestCase {
// select t0.id c0, t0.name c1, t0.status c2,
// t1.id c3, t1.first_name c4, t1.last_name c5, t1.phone c6, t1.mobile c7, t1.email c8, t1.cretime c9, t1.updtime c10, t1.customer_id c11, t1.group_id c12
// from o_customer t0
// left outer join contact t1 on t1.customer_id = t0.id
// left join contact t1 on t1.customer_id = t0.id
// where t0.id = ? order by t0.id; --bind(1)
Assert.assertTrue(custSecondarySql.contains("from o_customer t0 "));
Assert.assertTrue(custSecondarySql.contains("left outer join contact t1 on t1.customer_id = t0.id "));
Assert.assertTrue(custSecondarySql.contains("left join contact t1 on t1.customer_id = t0.id "));
Assert.assertTrue(custSecondarySql.contains("where t0.id "));
+147 -147
View File
@@ -1,147 +1,147 @@
package com.avaje.tests.cache;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
public void test() {
ResetBasicData.reset();
Ebean.getServerCacheManager().clear(Country.class);
ServerCache countryCache = Ebean.getServerCacheManager().getBeanCache(Country.class);
loadCountryCache();
Assert.assertTrue(countryCache.size() > 0);
// reset the statistics
countryCache.getStatistics(true);
Country c0 = Ebean.getReference(Country.class, "NZ");
ServerCacheStatistics statistics = countryCache.getStatistics(false);
long hc = statistics.getHitCount();
Assert.assertEquals(1, hc);
Assert.assertNotNull(c0);
// 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 org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
public void test() {
ResetBasicData.reset();
Ebean.getServerCacheManager().clear(Country.class);
ServerCache countryCache = Ebean.getServerCacheManager().getBeanCache(Country.class);
loadCountryCache();
Assert.assertTrue(countryCache.size() > 0);
// reset the statistics
countryCache.getStatistics(true);
Country c0 = Ebean.getReference(Country.class, "NZ");
ServerCacheStatistics statistics = countryCache.getStatistics(false);
long hc = statistics.getHitCount();
Assert.assertEquals(1, hc);
Assert.assertNotNull(c0);
// 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);
}
}
+63 -63
View File
@@ -1,63 +1,63 @@
package com.avaje.tests.cache;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.cache.ServerCache;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestQueryCache extends BaseTestCase {
@Test
@SuppressWarnings("unchecked")
public void test() {
ResetBasicData.reset();
ServerCache customerCache = Ebean.getServerCacheManager().getQueryCache(Customer.class);
customerCache.clear();
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.isEmpty());
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.assertSame(list, list2);
// readOnly defaults to true for query cache
Assert.assertSame(list, list2B);
// TODO: At this stage setReadOnly(false) does not
// create a shallow copy of the List/Set/Map
// List<Customer> list3 = Ebean.find(Customer.class).setUseQueryCache(true).setReadOnly(false).where()
// .ilike("name", "Rob").findList();
//
// Assert.assertNotSame(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 org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.cache.ServerCache;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestQueryCache extends BaseTestCase {
@Test
@SuppressWarnings("unchecked")
public void test() {
ResetBasicData.reset();
ServerCache customerCache = Ebean.getServerCacheManager().getQueryCache(Customer.class);
customerCache.clear();
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.isEmpty());
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.assertSame(list, list2);
// readOnly defaults to true for query cache
Assert.assertSame(list, list2B);
// TODO: At this stage setReadOnly(false) does not
// create a shallow copy of the List/Set/Map
// List<Customer> list3 = Ebean.find(Customer.class).setUseQueryCache(true).setReadOnly(false).where()
// .ilike("name", "Rob").findList();
//
// Assert.assertNotSame(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,60 +1,60 @@
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;
}
}
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,49 +1,49 @@
package com.avaje.tests.compositekeys.db;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Version;
@Entity
public class CaoBean {
@Id
@AttributeOverrides({
@AttributeOverride(name = "customer", column = @Column(name = "x_cust_id")) ,
@AttributeOverride(name = "type", column = @Column(name = "x_type_id"))
})
private CaoKey key;
private String description;
@Version
private Long version;
public CaoKey getKey() {
return key;
}
public void setKey(CaoKey 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;
}
package com.avaje.tests.compositekeys.db;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Version;
@Entity
public class CaoBean {
@Id
@AttributeOverrides({
@AttributeOverride(name = "customer", column = @Column(name = "x_cust_id")) ,
@AttributeOverride(name = "type", column = @Column(name = "x_type_id"))
})
private CaoKey key;
private String description;
@Version
private Long version;
public CaoKey getKey() {
return key;
}
public void setKey(CaoKey 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;
}
}
@@ -1,127 +1,127 @@
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;
}
}
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.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;
}
}
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,35 +1,35 @@
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;
}
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,57 +1,57 @@
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;
}
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,69 +1,69 @@
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;
}
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,68 +1,68 @@
package com.avaje.tests.ddd.iud;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.plugin.BeanType;
import com.avaje.ebean.plugin.ExpressionPath;
import com.avaje.ebean.plugin.SpiServer;
import com.avaje.ebean.text.json.JsonContext;
import com.avaje.tests.model.ddd.DPerson;
import com.avaje.tests.model.ivo.CMoney;
import com.avaje.tests.model.ivo.Money;
import org.junit.Test;
import java.io.IOException;
import java.util.Currency;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class TestDPersonEl {
@Test
public void test() throws IOException {
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));
SpiServer server = Ebean.getDefaultServer().getPluginApi();
BeanType<DPerson> descriptor = server.getBeanType(DPerson.class);
JsonContext jsonContext = server.json();
String json = jsonContext.toJson(p);
DPerson bean = jsonContext.toBean(DPerson.class, json);
assertEquals("first", bean.getFirstName());
assertEquals(new Money("12200"), bean.getSalary());
assertEquals(new Money("12"), bean.getCmoney().getAmount());
assertEquals(NZD, bean.getCmoney().getCurrency());
EntityBean entityBean = (EntityBean) p;
ExpressionPath elCmoney = descriptor.getExpressionPath("cmoney");
ExpressionPath elCmoneyAmt = descriptor.getExpressionPath("cmoney.amount");
ExpressionPath elCmoneyCur = descriptor.getExpressionPath("cmoney.currency");
Object cmoney = elCmoney.pathGet(entityBean);
Object amt = elCmoneyAmt.pathGet(entityBean);
Object cur = elCmoneyCur.pathGet(entityBean);
assertNotNull(cmoney);
assertEquals(new Money("12"), amt);
assertEquals(NZD, cur);
p.setCmoney(null);
assertNull(p.getCmoney());
}
}
package com.avaje.tests.ddd.iud;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.plugin.BeanType;
import com.avaje.ebean.plugin.ExpressionPath;
import com.avaje.ebean.plugin.SpiServer;
import com.avaje.ebean.text.json.JsonContext;
import com.avaje.tests.model.ddd.DPerson;
import com.avaje.tests.model.ivo.CMoney;
import com.avaje.tests.model.ivo.Money;
import org.junit.Test;
import java.io.IOException;
import java.util.Currency;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class TestDPersonEl {
@Test
public void test() throws IOException {
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));
SpiServer server = Ebean.getDefaultServer().getPluginApi();
BeanType<DPerson> descriptor = server.getBeanType(DPerson.class);
JsonContext jsonContext = server.json();
String json = jsonContext.toJson(p);
DPerson bean = jsonContext.toBean(DPerson.class, json);
assertEquals("first", bean.getFirstName());
assertEquals(new Money("12200"), bean.getSalary());
assertEquals(new Money("12"), bean.getCmoney().getAmount());
assertEquals(NZD, bean.getCmoney().getCurrency());
EntityBean entityBean = (EntityBean) p;
ExpressionPath elCmoney = descriptor.getExpressionPath("cmoney");
ExpressionPath elCmoneyAmt = descriptor.getExpressionPath("cmoney.amount");
ExpressionPath elCmoneyCur = descriptor.getExpressionPath("cmoney.currency");
Object cmoney = elCmoney.pathGet(entityBean);
Object amt = elCmoneyAmt.pathGet(entityBean);
Object cur = elCmoneyCur.pathGet(entityBean);
assertNotNull(cmoney);
assertEquals(new Money("12"), amt);
assertEquals(NZD, cur);
p.setCmoney(null);
assertNull(p.getCmoney());
}
}
@@ -32,7 +32,7 @@ public class TestDeleteByQuery extends BaseTestCase {
List<String> loggedSql = LoggedSqlCollector.stop();
assertThat(loggedSql).hasSize(1);
assertThat(trimSql(loggedSql.get(0), 1)).contains("delete from contact where id in (select t0.id from contact t0 left outer join");
assertThat(trimSql(loggedSql.get(0), 1)).contains("delete from contact where id in (select t0.id from contact t0 left join");
Query<Contact> query2 = server.find(Contact.class).where().eq("firstName", "NotARealFirstName").query();
@@ -1,39 +1,39 @@
package com.avaje.tests.genkey;
import com.avaje.ebean.config.dbplatform.IdType;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
public void test() {
EbeanServer server = Ebean.getServer(null);
SpiEbeanServer spiServer = (SpiEbeanServer)server;
IdType idType = spiServer.getDatabasePlatform().getDbIdentity().getIdType();
if (IdType.SEQUENCE == idType){
BeanDescriptor<TOne> d = spiServer.getBeanDescriptor(TOne.class);
Object id = d.nextId(null);
Assert.assertNotNull(id);
//System.out.println(id);
for (int i = 0; i < 16; i++) {
Object id2 = d.nextId(null);
Assert.assertNotNull(id2);
//System.out.println(id2);
}
}
}
}
package com.avaje.tests.genkey;
import com.avaje.ebean.config.dbplatform.IdType;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
public void test() {
EbeanServer server = Ebean.getServer(null);
SpiEbeanServer spiServer = (SpiEbeanServer)server;
IdType idType = spiServer.getDatabasePlatform().getDbIdentity().getIdType();
if (IdType.SEQUENCE == idType){
BeanDescriptor<TOne> d = spiServer.getBeanDescriptor(TOne.class);
Object id = d.nextId(null);
Assert.assertNotNull(id);
//System.out.println(id);
for (int i = 0; i < 16; i++) {
Object id2 = d.nextId(null);
Assert.assertNotNull(id2);
//System.out.println(id2);
}
}
}
}
@@ -1,51 +1,51 @@
package com.avaje.tests.idkeys;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.ESimple;
import org.junit.Assert;
import org.junit.Test;
public class TestSimpleIdInsert extends BaseTestCase {
@Test
public void test() {
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 com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.ESimple;
import org.junit.Assert;
import org.junit.Test;
public class TestSimpleIdInsert extends BaseTestCase {
@Test
public void test() {
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,55 +1,55 @@
package com.avaje.tests.inheritance;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
/**
* 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>
*/
@Test
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 org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
/**
* 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>
*/
@Test
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");
}
}
}
@@ -117,7 +117,7 @@ public class TestInheritInsert extends BaseTestCase {
Car result = query.findUnique();
assertThat(query.getGeneratedSql()).contains("order by t0.id, t2.location_code");
assertThat(query.getGeneratedSql()).contains("left outer join car_fuse t2 on t2.id = t1.fuse_id");
assertThat(query.getGeneratedSql()).contains("left join car_fuse t2 on t2.id = t1.fuse_id");
assertNotNull(result);
}
@@ -1,117 +1,117 @@
package com.avaje.tests.inheritance;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.Query;
import com.avaje.tests.inheritance.model.CalculationResult;
import com.avaje.tests.inheritance.model.Configurations;
import com.avaje.tests.inheritance.model.GroupConfiguration;
import com.avaje.tests.inheritance.model.ProductConfiguration;
public class TestInheritanceJoins extends BaseTestCase {
@Test
public void testAssocOne() {
EbeanServer server = Ebean.getDefaultServer();
ProductConfiguration pc = new ProductConfiguration();
pc.setName("PC1");
server.save(pc);
GroupConfiguration gc = new GroupConfiguration();
gc.setName("GC1");
server.save(gc);
CalculationResult r = new CalculationResult();
r.setCharge(100.0);
r.setProductConfiguration(pc);
r.setGroupConfiguration(gc);
server.save(r);
}
@Test
public void assocOne_when_null() {
EbeanServer server = Ebean.getDefaultServer();
GroupConfiguration gc = new GroupConfiguration();
gc.setName("GC1");
server.save(gc);
CalculationResult r = new CalculationResult();
r.setCharge(100.0);
// @ManyToOne with inheritance and null
r.setProductConfiguration(null);
r.setGroupConfiguration(gc);
server.save(r);
CalculationResult result = server.find(CalculationResult.class, r.getId());
GroupConfiguration group = result.getGroupConfiguration();
Assert.assertEquals(group.getId(), gc.getId());
}
@Test
public void testAssocOneWithNullAssoc() {
/* Ensures the fetch join to a property with inheritance work as a left join */
EbeanServer server = Ebean.getServer(null);
final ProductConfiguration pc = new ProductConfiguration();
pc.setName("PC1");
server.save(pc);
CalculationResult r = new CalculationResult();
final Double charge = 100.0;
r.setCharge(charge);
r.setProductConfiguration(pc);
r.setGroupConfiguration(null);
server.save(r);
}
@Test
public void testAssocMany() {
Configurations configurations = new Configurations();
EbeanServer server = Ebean.getServer(null);
server.save(configurations);
final GroupConfiguration gc = new GroupConfiguration("GC1");
configurations.add(gc);
server.save(gc);
Configurations configurationsQueried = server.find(Configurations.class, configurations.getId());
List<GroupConfiguration> groups = configurationsQueried.getGroupConfigurations();
Assert.assertTrue(!groups.isEmpty());
}
@Test
public void testAssocManyWithNoneRelated() {
Configurations configurations = new Configurations();
EbeanServer server = Ebean.getServer(null);
server.save(configurations);
Configurations configurationsQueried = server.find(Configurations.class).fetch("groupConfigurations").where().idEq(configurations.getId()).findUnique();
Assert.assertNotNull(configurationsQueried);
}
package com.avaje.tests.inheritance;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.Query;
import com.avaje.tests.inheritance.model.CalculationResult;
import com.avaje.tests.inheritance.model.Configurations;
import com.avaje.tests.inheritance.model.GroupConfiguration;
import com.avaje.tests.inheritance.model.ProductConfiguration;
public class TestInheritanceJoins extends BaseTestCase {
@Test
public void testAssocOne() {
EbeanServer server = Ebean.getDefaultServer();
ProductConfiguration pc = new ProductConfiguration();
pc.setName("PC1");
server.save(pc);
GroupConfiguration gc = new GroupConfiguration();
gc.setName("GC1");
server.save(gc);
CalculationResult r = new CalculationResult();
r.setCharge(100.0);
r.setProductConfiguration(pc);
r.setGroupConfiguration(gc);
server.save(r);
}
@Test
public void assocOne_when_null() {
EbeanServer server = Ebean.getDefaultServer();
GroupConfiguration gc = new GroupConfiguration();
gc.setName("GC1");
server.save(gc);
CalculationResult r = new CalculationResult();
r.setCharge(100.0);
// @ManyToOne with inheritance and null
r.setProductConfiguration(null);
r.setGroupConfiguration(gc);
server.save(r);
CalculationResult result = server.find(CalculationResult.class, r.getId());
GroupConfiguration group = result.getGroupConfiguration();
Assert.assertEquals(group.getId(), gc.getId());
}
@Test
public void testAssocOneWithNullAssoc() {
/* Ensures the fetch join to a property with inheritance work as a left join */
EbeanServer server = Ebean.getServer(null);
final ProductConfiguration pc = new ProductConfiguration();
pc.setName("PC1");
server.save(pc);
CalculationResult r = new CalculationResult();
final Double charge = 100.0;
r.setCharge(charge);
r.setProductConfiguration(pc);
r.setGroupConfiguration(null);
server.save(r);
}
@Test
public void testAssocMany() {
Configurations configurations = new Configurations();
EbeanServer server = Ebean.getServer(null);
server.save(configurations);
final GroupConfiguration gc = new GroupConfiguration("GC1");
configurations.add(gc);
server.save(gc);
Configurations configurationsQueried = server.find(Configurations.class, configurations.getId());
List<GroupConfiguration> groups = configurationsQueried.getGroupConfigurations();
Assert.assertTrue(!groups.isEmpty());
}
@Test
public void testAssocManyWithNoneRelated() {
Configurations configurations = new Configurations();
EbeanServer server = Ebean.getServer(null);
server.save(configurations);
Configurations configurationsQueried = server.find(Configurations.class).fetch("groupConfigurations").where().idEq(configurations.getId()).findUnique();
Assert.assertNotNull(configurationsQueried);
}
}
@@ -1,48 +1,48 @@
package com.avaje.tests.inheritance;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.TIntChild;
import com.avaje.tests.model.basic.TIntRoot;
public class TestIntInherit extends BaseTestCase {
@Test
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 org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.TIntChild;
import com.avaje.tests.model.basic.TIntRoot;
public class TestIntInherit extends BaseTestCase {
@Test
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,73 +1,73 @@
package com.avaje.tests.inheritance;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
private static final Logger logger = LoggerFactory.getLogger(TestSkippable.class);
/**
* 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>
*/
@Test
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);
logger.info(" -- seeded data");
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()));
logger.info(" -- asserted data in db");
final AttributeHolder holder = new AttributeHolder();
holder.add(listAttributeDB);
Ebean.save(holder);
logger.info(" -- saved 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);
logger.info(" -- M2M detected delete of value1 and add of value2 ?");
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.assertEquals(value2.getId(), value2_DB_2.getId());
Assert.assertTrue("Cascade failed", value2.getId().equals(value2_DB_2.getId()));
}
}
package com.avaje.tests.inheritance;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
private static final Logger logger = LoggerFactory.getLogger(TestSkippable.class);
/**
* 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>
*/
@Test
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);
logger.info(" -- seeded data");
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()));
logger.info(" -- asserted data in db");
final AttributeHolder holder = new AttributeHolder();
holder.add(listAttributeDB);
Ebean.save(holder);
logger.info(" -- saved 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);
logger.info(" -- M2M detected delete of value1 and add of value2 ?");
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.assertEquals(value2.getId(), value2_DB_2.getId());
Assert.assertTrue("Cascade failed", value2.getId().equals(value2_DB_2.getId()));
}
}
@@ -1,55 +1,55 @@
package com.avaje.tests.model.basic;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class CKeyDetail {
@Id
Integer id;
String something;
@ManyToOne
// @JoinColumns({
// @JoinColumn(name="parent_one_key", referencedColumnName="one_key"),
// @JoinColumn(name="parent_two_key", referencedColumnName="two_key")
// })
CKeyParent parent;
public CKeyDetail() {
}
public CKeyDetail(String something) {
this.something = something;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSomething() {
return something;
}
public void setSomething(String something) {
this.something = something;
}
public CKeyParent getParent() {
return parent;
}
public void setParent(CKeyParent parent) {
this.parent = parent;
}
}
package com.avaje.tests.model.basic;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class CKeyDetail {
@Id
Integer id;
String something;
@ManyToOne
// @JoinColumns({
// @JoinColumn(name="parent_one_key", referencedColumnName="one_key"),
// @JoinColumn(name="parent_two_key", referencedColumnName="two_key")
// })
CKeyParent parent;
public CKeyDetail() {
}
public CKeyDetail(String something) {
this.something = something;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSomething() {
return something;
}
public void setSomething(String something) {
this.something = something;
}
public CKeyParent getParent() {
return parent;
}
public void setParent(CKeyParent parent) {
this.parent = parent;
}
}
@@ -1,76 +1,76 @@
package com.avaje.tests.model.basic;
import javax.persistence.CascadeType;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Version;
import java.util.ArrayList;
import java.util.List;
@Entity
public class CKeyParent {
@EmbeddedId
CKeyParentId id;
String name;
@Version
int version;
@ManyToOne(cascade = CascadeType.PERSIST)
CKeyAssoc assoc;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "parent")
List<CKeyDetail> details;
public CKeyParentId getId() {
return id;
}
public void setId(CKeyParentId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public CKeyAssoc getAssoc() {
return assoc;
}
public void setAssoc(CKeyAssoc assoc) {
this.assoc = assoc;
}
public List<CKeyDetail> getDetails() {
return details;
}
public void setDetails(List<CKeyDetail> details) {
this.details = details;
}
public void add(CKeyDetail detail) {
if (details == null) {
details = new ArrayList<CKeyDetail>();
}
details.add(detail);
}
}
package com.avaje.tests.model.basic;
import javax.persistence.CascadeType;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Version;
import java.util.ArrayList;
import java.util.List;
@Entity
public class CKeyParent {
@EmbeddedId
CKeyParentId id;
String name;
@Version
int version;
@ManyToOne(cascade = CascadeType.PERSIST)
CKeyAssoc assoc;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "parent")
List<CKeyDetail> details;
public CKeyParentId getId() {
return id;
}
public void setId(CKeyParentId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public CKeyAssoc getAssoc() {
return assoc;
}
public void setAssoc(CKeyAssoc assoc) {
this.assoc = assoc;
}
public List<CKeyDetail> getDetails() {
return details;
}
public void setDetails(List<CKeyDetail> details) {
this.details = details;
}
public void add(CKeyDetail detail) {
if (details == null) {
details = new ArrayList<CKeyDetail>();
}
details.add(detail);
}
}
@@ -1,56 +1,56 @@
package com.avaje.tests.model.basic;
import javax.persistence.Embeddable;
@Embeddable
public class CKeyParentId {
Integer oneKey;
String twoKey;
public CKeyParentId() {
}
public CKeyParentId(Integer oneKey, String twoKey) {
this.oneKey = oneKey;
this.twoKey = twoKey;
}
public Integer getOneKey() {
return oneKey;
}
public void setOneKey(Integer oneKey) {
this.oneKey = oneKey;
}
public String getTwoKey() {
return twoKey;
}
public void setTwoKey(String twoKey) {
this.twoKey = twoKey;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CKeyParentId)) {
return false;
}
CKeyParentId otherKey = (CKeyParentId) o;
return otherKey.hashCode() == hashCode();
}
@Override
public int hashCode() {
int hc = getClass().getName().hashCode();
hc = 31 * hc + oneKey;
hc = 31 * hc + twoKey.hashCode();
return hc;
}
}
package com.avaje.tests.model.basic;
import javax.persistence.Embeddable;
@Embeddable
public class CKeyParentId {
Integer oneKey;
String twoKey;
public CKeyParentId() {
}
public CKeyParentId(Integer oneKey, String twoKey) {
this.oneKey = oneKey;
this.twoKey = twoKey;
}
public Integer getOneKey() {
return oneKey;
}
public void setOneKey(Integer oneKey) {
this.oneKey = oneKey;
}
public String getTwoKey() {
return twoKey;
}
public void setTwoKey(String twoKey) {
this.twoKey = twoKey;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CKeyParentId)) {
return false;
}
CKeyParentId otherKey = (CKeyParentId) o;
return otherKey.hashCode() == hashCode();
}
@Override
public int hashCode() {
int hc = getClass().getName().hashCode();
hc = 31 * hc + oneKey;
hc = 31 * hc + twoKey.hashCode();
return hc;
}
}
@@ -2,6 +2,7 @@ package com.avaje.tests.model.basic;
import com.avaje.ebean.annotation.DbEnumValue;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
@@ -31,6 +32,7 @@ public class Car extends Vehicle {
}
}
@Column(name = "siz")
private Size size;
private String driver;
@@ -1,49 +1,49 @@
package com.avaje.tests.model.basic;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
@Entity
public class ContactNote extends BasicDomain {
private static final long serialVersionUID = 7949702621226333278L;
@ManyToOne
Contact contact;
String title;
@Lob
String note;
public ContactNote(String title, String note) {
this.title = title;
this.note = note;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
}
package com.avaje.tests.model.basic;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
@Entity
public class ContactNote extends BasicDomain {
private static final long serialVersionUID = 7949702621226333278L;
@ManyToOne
Contact contact;
String title;
@Lob
String note;
public ContactNote(String title, String note) {
this.title = title;
this.note = note;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
}
@@ -1,32 +1,32 @@
package com.avaje.tests.model.basic;
import org.joda.time.LocalTime;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class TJodaEntity {
@Id
Integer id;
LocalTime localTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public LocalTime getLocalTime() {
return localTime;
}
public void setLocalTime(LocalTime localTime) {
this.localTime = localTime;
}
}
package com.avaje.tests.model.basic;
import org.joda.time.LocalTime;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class TJodaEntity {
@Id
Integer id;
LocalTime localTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public LocalTime getLocalTime() {
return localTime;
}
public void setLocalTime(LocalTime localTime) {
this.localTime = localTime;
}
}
@@ -2,6 +2,7 @@ package com.avaje.tests.model.basic;
import com.avaje.ebean.annotation.DbEnumValue;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
@@ -29,6 +30,7 @@ public class Truck extends Vehicle {
}
}
@Column(name = "siz")
private Size size;
@ManyToOne
@@ -1,30 +1,30 @@
package com.avaje.tests.model.basic;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class TruckRef {
@Id
Integer id;
String something;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSomething() {
return something;
}
public void setSomething(String something) {
this.something = something;
}
}
package com.avaje.tests.model.basic;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class TruckRef {
@Id
Integer id;
String something;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSomething() {
return something;
}
public void setSomething(String something) {
this.something = something;
}
}
@@ -1,58 +1,58 @@
package com.avaje.tests.model.basic.xtra;
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;
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 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;
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;
}
}
@@ -1,47 +1,47 @@
package com.avaje.tests.model.ddd;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Version;
import com.avaje.tests.model.ivo.ExhangeCMoneyRate;
import com.avaje.tests.model.ivo.Oid;
@Entity
public class DExhEntity {
@Id
Oid<DExhEntity> oid;
ExhangeCMoneyRate exhange;
@Version
Timestamp lastUpdated;
public Oid<DExhEntity> getOid() {
return oid;
}
public void setOid(Oid<DExhEntity> oid) {
this.oid = oid;
}
public ExhangeCMoneyRate getExhange() {
return exhange;
}
public void setExhange(ExhangeCMoneyRate exhange) {
this.exhange = exhange;
}
public Timestamp getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Timestamp lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
package com.avaje.tests.model.ddd;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Version;
import com.avaje.tests.model.ivo.ExhangeCMoneyRate;
import com.avaje.tests.model.ivo.Oid;
@Entity
public class DExhEntity {
@Id
Oid<DExhEntity> oid;
ExhangeCMoneyRate exhange;
@Version
Timestamp lastUpdated;
public Oid<DExhEntity> getOid() {
return oid;
}
public void setOid(Oid<DExhEntity> oid) {
this.oid = oid;
}
public ExhangeCMoneyRate getExhange() {
return exhange;
}
public void setExhange(ExhangeCMoneyRate exhange) {
this.exhange = exhange;
}
public Timestamp getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Timestamp lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
@@ -16,7 +16,7 @@ public class HeLink extends BaseDomain {
String location;
String comment;
String comments;
@HistoryExclude
@ManyToMany
@@ -46,12 +46,12 @@ public class HeLink extends BaseDomain {
this.location = location;
}
public String getComment() {
return comment;
public String getComments() {
return comments;
}
public void setComment(String comment) {
this.comment = comment;
public void setComments(String comments) {
this.comments = comments;
}
public List<HeDoc> getDocs() {
@@ -15,7 +15,7 @@ public class HiLink extends BaseDomain {
String location;
String comment;
String comments;
@ManyToMany
List<HiDoc> docs;
@@ -44,12 +44,12 @@ public class HiLink extends BaseDomain {
this.location = location;
}
public String getComment() {
return comment;
public String getComments() {
return comments;
}
public void setComment(String comment) {
this.comment = comment;
public void setComments(String comments) {
this.comments = comments;
}
public List<HiDoc> getDocs() {
@@ -9,6 +9,8 @@ import com.avaje.ebean.Query;
import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat;
public class TestMediaInheritanceJoinToMany extends BaseTestCase {
@Test
@@ -30,14 +32,14 @@ public class TestMediaInheritanceJoinToMany extends BaseTestCase {
// select t0.id c0, t0.name c1, t1.type c2, t1.id c3, t1.url c4, t1.note c5
// from profile t0
// left outer join media t1 on t1.id = t0.picture_id and t1.type = 'Picture'
// left join media t1 on t1.id = t0.picture_id and t1.type = 'Picture'
// where t0.name = ? ; --bind(nopic)
// specifically t1.type = 'Picture' ... on on the join and not in the where
String generatedSql = query.getGeneratedSql();
Assert.assertTrue(generatedSql.contains("from mprofile t0 left outer join mmedia t1 on t1.id = t0.picture_id and t1.type = 'Picture' "));
Assert.assertTrue(generatedSql.contains("where t0.name = ? "));
assertThat(generatedSql).contains("from mprofile t0 left join mmedia t1 on t1.id = t0.picture_id and t1.type = 'Picture' ");
assertThat(generatedSql).contains("where t0.name = ? ");
}
@@ -1,30 +1,30 @@
package com.avaje.tests.model.ivo;
import com.avaje.ebeaninternal.server.type.reflect.KnownImmutable;
public class SimpleKnownImmutable implements KnownImmutable {
public boolean isKnownImmutable(Class<?> cls) {
// Check for all allowed property types...
if (cls.isPrimitive() || String.class.equals(cls) || Object.class.equals(cls)) {
return true;
}
if (java.util.Date.class.equals(cls) || java.sql.Date.class.equals(cls) || java.sql.Timestamp.class.equals(cls)) {
// treat as immutable even through they are not strictly so
return true;
}
if (java.math.BigDecimal.class.equals(cls) || java.math.BigInteger.class.equals(cls)) {
// treat as immutable (contain non-final fields)
return true;
}
if (Integer.class.equals(cls) || Long.class.equals(cls) || Double.class.equals(cls) || Float.class.equals(cls)
|| Short.class.equals(cls) || Byte.class.equals(cls) || Character.class.equals(cls)
|| Boolean.class.equals(cls)) {
return true;
}
return false;
}
}
package com.avaje.tests.model.ivo;
import com.avaje.ebeaninternal.server.type.reflect.KnownImmutable;
public class SimpleKnownImmutable implements KnownImmutable {
public boolean isKnownImmutable(Class<?> cls) {
// Check for all allowed property types...
if (cls.isPrimitive() || String.class.equals(cls) || Object.class.equals(cls)) {
return true;
}
if (java.util.Date.class.equals(cls) || java.sql.Date.class.equals(cls) || java.sql.Timestamp.class.equals(cls)) {
// treat as immutable even through they are not strictly so
return true;
}
if (java.math.BigDecimal.class.equals(cls) || java.math.BigInteger.class.equals(cls)) {
// treat as immutable (contain non-final fields)
return true;
}
if (Integer.class.equals(cls) || Long.class.equals(cls) || Double.class.equals(cls) || Float.class.equals(cls)
|| Short.class.equals(cls) || Byte.class.equals(cls) || Character.class.equals(cls)
|| Boolean.class.equals(cls)) {
return true;
}
return false;
}
}
@@ -1,15 +1,15 @@
package com.avaje.tests.model.ivo;
public class SysTime {
private final long millis;
public SysTime(long millis) {
this.millis = millis;
}
public long getMillis() {
return millis;
}
}
package com.avaje.tests.model.ivo;
public class SysTime {
private final long millis;
public SysTime(long millis) {
this.millis = millis;
}
public long getMillis() {
return millis;
}
}
@@ -1,54 +1,54 @@
package com.avaje.tests.model.ivo.converter;
import com.avaje.ebean.config.CompoundType;
import com.avaje.ebean.config.CompoundTypeProperty;
import com.avaje.tests.model.ivo.CMoney;
import com.avaje.tests.model.ivo.ExhangeCMoneyRate;
import com.avaje.tests.model.ivo.Rate;
public class ExhangeCompoundType implements CompoundType<ExhangeCMoneyRate> {
public ExhangeCMoneyRate create(Object[] propertyValues) {
return new ExhangeCMoneyRate((Rate)propertyValues[0], (CMoney)propertyValues[1]);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public CompoundTypeProperty<ExhangeCMoneyRate, ?>[] getProperties() {
CompoundTypeProperty[] props = {new RateProp(), new CMoneyProp()};
return props;
}
static class RateProp implements CompoundTypeProperty<ExhangeCMoneyRate, Rate> {
public String getName() {
return "rate";
}
public Rate getValue(ExhangeCMoneyRate valueObject) {
return valueObject.getRate();
}
public int getDbType() {
return 0;
}
}
static class CMoneyProp implements CompoundTypeProperty<ExhangeCMoneyRate, CMoney> {
public String getName() {
return "cmoney";
}
public CMoney getValue(ExhangeCMoneyRate valueObject) {
return valueObject.getCmoney();
}
public int getDbType() {
return 0;
}
}
}
package com.avaje.tests.model.ivo.converter;
import com.avaje.ebean.config.CompoundType;
import com.avaje.ebean.config.CompoundTypeProperty;
import com.avaje.tests.model.ivo.CMoney;
import com.avaje.tests.model.ivo.ExhangeCMoneyRate;
import com.avaje.tests.model.ivo.Rate;
public class ExhangeCompoundType implements CompoundType<ExhangeCMoneyRate> {
public ExhangeCMoneyRate create(Object[] propertyValues) {
return new ExhangeCMoneyRate((Rate)propertyValues[0], (CMoney)propertyValues[1]);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public CompoundTypeProperty<ExhangeCMoneyRate, ?>[] getProperties() {
CompoundTypeProperty[] props = {new RateProp(), new CMoneyProp()};
return props;
}
static class RateProp implements CompoundTypeProperty<ExhangeCMoneyRate, Rate> {
public String getName() {
return "rate";
}
public Rate getValue(ExhangeCMoneyRate valueObject) {
return valueObject.getRate();
}
public int getDbType() {
return 0;
}
}
static class CMoneyProp implements CompoundTypeProperty<ExhangeCMoneyRate, CMoney> {
public String getName() {
return "cmoney";
}
public CMoney getValue(ExhangeCMoneyRate valueObject) {
return valueObject.getCmoney();
}
public int getDbType() {
return 0;
}
}
}
@@ -1,51 +1,51 @@
package com.avaje.tests.model.ivo.converter;
import org.joda.time.Interval;
import com.avaje.ebean.config.CompoundType;
import com.avaje.ebean.config.CompoundTypeProperty;
public class JodaIntervalCompoundType implements CompoundType<Interval>{
public Interval create(Object[] propertyValues) {
return new Interval((Long)propertyValues[0], (Long)propertyValues[1]);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public CompoundTypeProperty<Interval, ?>[] getProperties() {
CompoundTypeProperty[] props = {new Start(), new End()};
return props;
}
static class Start implements CompoundTypeProperty<Interval, Long> {
public String getName() {
return "startMillis";
}
public Long getValue(Interval valueObject) {
return valueObject.getStartMillis();
}
public int getDbType() {
return java.sql.Types.TIMESTAMP;
}
}
static class End implements CompoundTypeProperty<Interval, Long> {
public String getName() {
return "endMillis";
}
public Long getValue(Interval valueObject) {
return valueObject.getEndMillis();
}
public int getDbType() {
return java.sql.Types.TIMESTAMP;
}
}
}
package com.avaje.tests.model.ivo.converter;
import org.joda.time.Interval;
import com.avaje.ebean.config.CompoundType;
import com.avaje.ebean.config.CompoundTypeProperty;
public class JodaIntervalCompoundType implements CompoundType<Interval>{
public Interval create(Object[] propertyValues) {
return new Interval((Long)propertyValues[0], (Long)propertyValues[1]);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public CompoundTypeProperty<Interval, ?>[] getProperties() {
CompoundTypeProperty[] props = {new Start(), new End()};
return props;
}
static class Start implements CompoundTypeProperty<Interval, Long> {
public String getName() {
return "startMillis";
}
public Long getValue(Interval valueObject) {
return valueObject.getStartMillis();
}
public int getDbType() {
return java.sql.Types.TIMESTAMP;
}
}
static class End implements CompoundTypeProperty<Interval, Long> {
public String getName() {
return "endMillis";
}
public Long getValue(Interval valueObject) {
return valueObject.getEndMillis();
}
public int getDbType() {
return java.sql.Types.TIMESTAMP;
}
}
}
@@ -1,24 +1,24 @@
package com.avaje.tests.model.ivo.converter;
import java.sql.Timestamp;
import com.avaje.ebean.config.ScalarTypeConverter;
import com.avaje.tests.model.ivo.SysTime;
public class SysTimeConverter implements ScalarTypeConverter<SysTime, Timestamp> {
public SysTime getNullValue() {
return null;
}
public Timestamp unwrapValue(SysTime beanType) {
return new Timestamp(beanType.getMillis());
}
public SysTime wrapValue(Timestamp scalarType) {
return new SysTime(scalarType.getTime());
}
}
package com.avaje.tests.model.ivo.converter;
import java.sql.Timestamp;
import com.avaje.ebean.config.ScalarTypeConverter;
import com.avaje.tests.model.ivo.SysTime;
public class SysTimeConverter implements ScalarTypeConverter<SysTime, Timestamp> {
public SysTime getNullValue() {
return null;
}
public Timestamp unwrapValue(SysTime beanType) {
return new Timestamp(beanType.getMillis());
}
public SysTime wrapValue(Timestamp scalarType) {
return new SysTime(scalarType.getTime());
}
}
@@ -31,7 +31,7 @@ public class TestOneToOneOptionalRelationship extends BaseTestCase {
String sql = trimSql(loggedSql.get(0), 1);
Assert.assertTrue(sql.contains("select t0.id, t0.name"));
Assert.assertTrue(sql.contains(" from oto_account t0 left outer join oto_user t1 on t1.account_id = t0.id where t0.id = ?"));
Assert.assertTrue(sql.contains(" from oto_account t0 left join oto_user t1 on t1.account_id = t0.id where t0.id = ?"));
}
@@ -66,7 +66,7 @@ public class TestOneToOneOptionalRelationship extends BaseTestCase {
String sql = trimSql(loggedSql.get(0), 1);
Assert.assertTrue(sql.contains("select t0.id, t0.name"));
Assert.assertTrue(sql.contains(" from oto_account t0 left outer join oto_user t1 on t1.account_id = t0.id where t0.id = ?"));
Assert.assertTrue(sql.contains(" from oto_account t0 left join oto_user t1 on t1.account_id = t0.id where t0.id = ?"));
String lazyLoadSql = trimSql(loggedSql.get(1), 5);
Assert.assertTrue(lazyLoadSql.contains("select t0.id, t0.name, t0.version, t0.when_created, t0.when_modified, t0.account_id from oto_user t0 where t0.id = ?"));
@@ -104,6 +104,6 @@ public class TestOneToOneOptionalRelationship extends BaseTestCase {
String sql = trimSql(loggedSql.get(0), 1);
Assert.assertTrue(sql.contains("select t0.id, t0.name"));
Assert.assertTrue(sql.contains(" from oto_account t0 left outer join oto_user t1 on t1.account_id = t0.id where t0.id = ?"));
Assert.assertTrue(sql.contains(" from oto_account t0 left join oto_user t1 on t1.account_id = t0.id where t0.id = ?"));
}
}
@@ -22,7 +22,7 @@ public class TestPview extends BaseTestCase {
query.findList();
String generatedSql = sqlOf(query, 1);
Assert.assertTrue(generatedSql.contains("select distinct t0.amount, t1.value from paggview t0 join pp u1 on u1.id = t0.pview_id join pp_to_ww u2z_ on u2z_.pp_id = u1.id join wview u2 on u2.id = u2z_.ww_id left outer join pp t1 on t1.id = t0.pview_id where u2.id = ? order by t1.value"));
Assert.assertTrue(generatedSql.contains("select distinct t0.amount, t1.value from paggview t0 join pp u1 on u1.id = t0.pview_id join pp_to_ww u2z_ on u2z_.pp_id = u1.id join wview u2 on u2.id = u2z_.ww_id left join pp t1 on t1.id = t0.pview_id where u2.id = ? order by t1.value"));
}
@@ -65,6 +65,6 @@ public class TestViewBaseEntity extends BaseTestCase {
assertThat(details).isNotEmpty();
}
assertThat(query.getGeneratedSql()).contains("from order_agg_vw t0 left outer join o_order t1 on t1.id = t0.order_id left outer join o_customer t3 on t3.id = t1.kcustomer_id left outer join o_order_detail t2 on t2.order_id = t1.id where t2.id > 0 and t0.order_total > ?");
assertThat(query.getGeneratedSql()).contains("from order_agg_vw t0 left join o_order t1 on t1.id = t0.order_id left join o_customer t3 on t3.id = t1.kcustomer_id left join o_order_detail t2 on t2.order_id = t1.id where t2.id > 0 and t0.order_total > ?");
}
}
@@ -48,7 +48,7 @@ public class TestImplicitJoinOnParentRelationship extends BaseTestCase {
query.findList();
String expectedSql = "select distinct t0.id, t0.name from o_customer t0 left outer join o_order u1 on u1.kcustomer_id = t0.id left outer join o_order_detail u2 on u2.order_id = u1.id left outer join o_product u3 on u3.id = u2.product_id where (u3.name = ? or t0.id = ? ) ";
String expectedSql = "select distinct t0.id, t0.name from o_customer t0 left join o_order u1 on u1.kcustomer_id = t0.id left join o_order_detail u2 on u2.order_id = u1.id left join o_product u3 on u3.id = u2.product_id where (u3.name = ? or t0.id = ? ) ";
Assert.assertEquals(expectedSql, sqlOf(query, 1));
}
@@ -64,7 +64,7 @@ public class TestImplicitJoinOnParentRelationship extends BaseTestCase {
query.findList();
String expectedSql = "select distinct t0.id, t0.name from o_customer t0 left outer join o_order u1 on u1.kcustomer_id = t0.id left outer join o_order_detail u2 on u2.order_id = u1.id left outer join o_product u3 on u3.id = u2.product_id where (u3.name = ? or t0.id = ? ) ";
String expectedSql = "select distinct t0.id, t0.name from o_customer t0 left join o_order u1 on u1.kcustomer_id = t0.id left join o_order_detail u2 on u2.order_id = u1.id left join o_product u3 on u3.id = u2.product_id where (u3.name = ? or t0.id = ? ) ";
Assert.assertEquals(expectedSql, sqlOf(query, 1));
}
}
@@ -13,14 +13,14 @@ public class TestJoinOptOneCascade extends BaseTestCase {
@Test
public void test() {
// the left outer join cascades to the join for c
// the left join cascades to the join for c
Query<EOptOneA> query = Ebean.find(EOptOneA.class).fetch("b").fetch("b.c");
query.findList();
String sql = query.getGeneratedSql();
Assert.assertTrue(sql.contains("left outer join eopt_one_b "));
Assert.assertTrue(sql.contains("left outer join eopt_one_c "));
Assert.assertTrue(sql.contains("left join eopt_one_b "));
Assert.assertTrue(sql.contains("left join eopt_one_c "));
}
}
@@ -1,30 +1,30 @@
package com.avaje.tests.query;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class TestLimitQuery extends BaseTestCase {
@Test
public void testHasManyWithLimit() {
ResetBasicData.reset();
List<Customer> customers = Ebean.find(Customer.class)
.setAutoTune(false)
.setFirstRow(0)
.setMaxRows(10)
.where().like("name", "%A%")
.findList();
// should at least find the "Cust NoAddress" customer
Assert.assertTrue(!customers.isEmpty());
}
package com.avaje.tests.query;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class TestLimitQuery extends BaseTestCase {
@Test
public void testHasManyWithLimit() {
ResetBasicData.reset();
List<Customer> customers = Ebean.find(Customer.class)
.setAutoTune(false)
.setFirstRow(0)
.setMaxRows(10)
.where().like("name", "%A%")
.findList();
// should at least find the "Cust NoAddress" customer
Assert.assertTrue(!customers.isEmpty());
}
}
@@ -60,14 +60,14 @@ public class TestManyWhereJoin extends BaseTestCase {
// select distinct t0.id c0, t0.status c1,
// t1.id c2, t1.status c3, t1.order_date c4, t1.ship_date c5, t2.name c6, t1.cretime c7, t1.updtime c8, t1.kcustomer_id c9, t0.id
// from o_customer t0
// left outer join o_order t1 on t1.kcustomer_id = t0.id
// left outer join o_customer t2 on t2.id = t1.kcustomer_id
// left join o_order t1 on t1.kcustomer_id = t0.id
// left join o_customer t2 on t2.id = t1.kcustomer_id
// join o_order u1 on u1.kcustomer_id = t0.id
// where t1.order_date is not null and u1.status = ?
// order by t0.id; --bind(NEW)
Assert.assertTrue(sql.contains("select distinct t0.id, t0.status, t1.id, t1.status,"));
Assert.assertTrue(sql.contains("left outer join o_order t1 on "));
Assert.assertTrue(sql.contains("left join o_order t1 on "));
Assert.assertTrue(sql.contains("join o_order u1 on "));
Assert.assertTrue(sql.contains(" u1.status = ?"));
}
@@ -150,7 +150,7 @@ public class TestManyWhereJoin extends BaseTestCase {
// t1.id c8, t1.order_qty c9, t1.ship_qty c10, t1.unit_price c11, t1.cretime c12, t1.updtime c13, t1.order_id c14, t1.product_id c15, t0.cretime, t0.id, t1.id, t1.order_qty, t1.cretime
// from o_order t0
// join o_customer t2 on t2.id = t0.kcustomer_id
// left outer join o_order_detail t1 on t1.order_id = t0.id
// left join o_order_detail t1 on t1.order_id = t0.id
// join o_order_detail u1 on u1.order_id = t0.id
// where t1.id > 0 and u1.product_id = ?
// order by t0.cretime, t0.id, t1.id asc, t1.order_qty asc, t1.cretime desc; --bind(1)
@@ -160,6 +160,6 @@ public class TestManyWhereJoin extends BaseTestCase {
Assert.assertTrue(sql.contains(" u1.product_id = ?"));
// additional join for fetching the many details
Assert.assertTrue(sql.contains(" left outer join o_order_detail t1 on t1.order_id = t0.id"));
Assert.assertTrue(sql.contains(" left join o_order_detail t1 on t1.order_id = t0.id"));
}
}
@@ -61,7 +61,7 @@ public class TestManyWhereJoinM2M extends BaseTestCase {
String sql = query.getGeneratedSql();
Assert.assertTrue(sql.contains("select distinct"));
Assert.assertTrue(sql.contains("left outer join mrole "));
Assert.assertTrue(sql.contains("left join mrole "));
Assert.assertTrue(sql.contains("join mrole "));
Assert.assertTrue(sql.contains(".role_name = ?"));
@@ -33,15 +33,15 @@ public class TestQueryFetchManyTwoDeep extends BaseTestCase {
List<Customer> list = query.findList();
Assert.assertTrue("has rows", !list.isEmpty());
Assert.assertTrue(query.getGeneratedSql().contains("from o_customer t0 "));
Assert.assertTrue(query.getGeneratedSql().contains("left outer join o_order t1 on t1.kcustomer_id = t0.id"));
Assert.assertTrue(query.getGeneratedSql().contains("left outer join o_customer t2 on t2.id = t1.kcustomer_id"));
Assert.assertTrue(query.getGeneratedSql().contains("left join o_order t1 on t1.kcustomer_id = t0.id"));
Assert.assertTrue(query.getGeneratedSql().contains("left join o_customer t2 on t2.id = t1.kcustomer_id"));
Assert.assertFalse(query.getGeneratedSql().contains("join or_order_ship"));
//select t0.id c0, t0.status c1, t0.name c2, t0.smallnote c3, t0.anniversary c4, t0.cretime c5, t0.updtime c6, t0.billing_address_id c7, t0.shipping_address_id c8, t1.id c9, t1.status c10, t1.order_date c11, t1.ship_date c12,
// t2.name c13, t1.cretime c14, t1.updtime c15, t1.kcustomer_id c16
// from o_customer t0
// left outer join o_order t1 on t1.kcustomer_id = t0.id
// left outer join o_customer t2 on t2.id = t1.kcustomer_id
// left join o_order t1 on t1.kcustomer_id = t0.id
// left join o_customer t2 on t2.id = t1.kcustomer_id
// where t1.order_date is not null order by t0.id; --bind()
@@ -77,16 +77,16 @@ public class TestQueryFetchManyTwoDeep extends BaseTestCase {
// select ...
// from or_order_ship t0
// left outer join o_order t1 on t1.id = t0.order_id
// left outer join o_customer t3 on t3.id = t1.kcustomer_id
// left outer join o_order_detail t2 on t2.order_id = t1.id
// left join o_order t1 on t1.id = t0.order_id
// left join o_customer t3 on t3.id = t1.kcustomer_id
// left join o_order_detail t2 on t2.order_id = t1.id
// where t2.id > 0 ; --bind()
Assert.assertTrue(generatedSql.contains("from or_order_ship t0"));
// Relationship from OrderShipment to Order is optional so outer join here
Assert.assertTrue(generatedSql.contains("left outer join o_order t1 on t1.id = t0.order_id"));
Assert.assertTrue(generatedSql.contains("left outer join o_customer t3 on t3.id = t1.kcustomer_id"));
Assert.assertTrue(generatedSql.contains("left outer join o_order_detail t2 on t2.order_id = t1.id"));
Assert.assertTrue(generatedSql.contains("left join o_order t1 on t1.id = t0.order_id"));
Assert.assertTrue(generatedSql.contains("left join o_customer t3 on t3.id = t1.kcustomer_id"));
Assert.assertTrue(generatedSql.contains("left join o_order_detail t2 on t2.order_id = t1.id"));
// If OrderShipment to Order is not optional you get inner joins up to o_order_detail (which is a many)
@@ -95,7 +95,7 @@ public class TestQueryFetchManyTwoDeep extends BaseTestCase {
// from or_order_ship t0
// join o_order t1 on t1.id = t0.order_id
// join o_customer t3 on t3.id = t1.kcustomer_id
// left outer join o_order_detail t2 on t2.order_id = t1.id
// left join o_order_detail t2 on t2.order_id = t1.id
// where t2.id > 0 ; --bind()
}
@@ -119,15 +119,15 @@ public class TestQueryFetchManyTwoDeep extends BaseTestCase {
// select ...
// from contact t0
// join o_customer t1 on t1.id = t0.customer_id
// left outer join o_order t2 on t2.kcustomer_id = t1.id
// left outer join o_customer t3 on t3.id = t2.kcustomer_id
// left join o_order t2 on t2.kcustomer_id = t1.id
// left join o_customer t3 on t3.id = t2.kcustomer_id
// where t2.order_date is not null ; --bind()
Assert.assertTrue(generatedSql.contains("from contact t0 "));
// Relationship from Contact to Customer is mandatory so inner join here
Assert.assertTrue(generatedSql.contains("join o_customer t1 on t1.id = t0.customer_id"));
// outer join on many relationship 'orders'
Assert.assertTrue(generatedSql.contains("left outer join o_order t2 on t2.kcustomer_id = t1.id"));
Assert.assertTrue(generatedSql.contains("left join o_order t2 on t2.kcustomer_id = t1.id"));
}
@@ -27,9 +27,9 @@ public class TestQueryMultiManyOrder extends BaseTestCase {
Assert.assertTrue(!list.isEmpty());
Assert.assertTrue(sql.contains("join o_customer "));
Assert.assertFalse(sql.contains("left outer join contact "));
Assert.assertFalse(sql.contains("left outer join o_order_detail "));
Assert.assertFalse(sql.contains("left outer join o_product "));
Assert.assertFalse(sql.contains("left join contact "));
Assert.assertFalse(sql.contains("left join o_order_detail "));
Assert.assertFalse(sql.contains("left join o_product "));
}
}
@@ -1,140 +1,140 @@
package com.avaje.tests.query;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 static org.assertj.core.api.StrictAssertions.assertThat;
public class TestSubQuery extends BaseTestCase {
@Test
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();
Ebean.find(Order.class).where().in("id", sq).findList();
}
public void testCompositeKey() {
ResetBasicData.reset();
Query<CKeyParent> sq = Ebean.createQuery(CKeyParent.class).select("id.oneKey")
.setAutoTune(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) ";
assertThat(sql).contains(golden);
}
/**
* 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")
* .setAutoTune(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")
.setAutoTune(false).where().query();
Query<Vehicle> pq = Ebean.find(Vehicle.class).where().in("id", sq).query();
pq.findList();
String sql = pq.getGeneratedSql();
// 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 )";
assertThat(sql).contains(golden);
}
/**
* 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")
.setAutoTune(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();
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 = ? )";
assertThat(sql).contains(golden);
}
/**
* 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")
.setAutoTune(false).where().query();
Query<Vehicle> pq = Ebean.find(Vehicle.class).where().in("id", sq).query();
pq.findList();
String sql = pq.getGeneratedSql();
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left outer join vehicle t1 on t1.id = t0.vehicle_id )";
assertThat(sql).contains(golden);
}
}
package com.avaje.tests.query;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 static org.assertj.core.api.StrictAssertions.assertThat;
public class TestSubQuery extends BaseTestCase {
@Test
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();
Ebean.find(Order.class).where().in("id", sq).findList();
}
public void testCompositeKey() {
ResetBasicData.reset();
Query<CKeyParent> sq = Ebean.createQuery(CKeyParent.class).select("id.oneKey")
.setAutoTune(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) ";
assertThat(sql).contains(golden);
}
/**
* 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")
* .setAutoTune(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")
.setAutoTune(false).where().query();
Query<Vehicle> pq = Ebean.find(Vehicle.class).where().in("id", sq).query();
pq.findList();
String sql = pq.getGeneratedSql();
// 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 join vehicle t1 on t1.id = t0.vehicle_id )";
assertThat(sql).contains(golden);
}
/**
* 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")
.setAutoTune(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();
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left join vehicle t1 on t1.id = t0.vehicle_id where t1.license_number = ? )";
assertThat(sql).contains(golden);
}
/**
* 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")
.setAutoTune(false).where().query();
Query<Vehicle> pq = Ebean.find(Vehicle.class).where().in("id", sq).query();
pq.findList();
String sql = pq.getGeneratedSql();
String golden = "(t0.id) in (select t0.vehicle_id from vehicle_driver t0 left join vehicle t1 on t1.id = t0.vehicle_id )";
assertThat(sql).contains(golden);
}
}
@@ -1,63 +1,63 @@
package com.avaje.tests.query;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.Order;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 java.sql.Timestamp;
import static org.assertj.core.api.Assertions.assertThat;
public class TestWhereRawClause extends BaseTestCase {
@Test
public void testRawClauseWithJunction() {
ResetBasicData.reset();
Query<Order> query = Ebean.find(Order.class)
.where()
.raw("(status = ? or (orderDate < ? and shipDate is null) or customer.name like ?)",
Order.Status.APPROVED, new Timestamp(System.currentTimeMillis()), "Rob")
.query();
query.findList();
assertThat(query.getGeneratedSql()).contains(" where (t0.status = ? or (t0.order_date < ? and t0.ship_date is null) or t1.name like ?)");
}
@Test
public void testRawClause() {
ResetBasicData.reset();
Ebean.find(OrderDetail.class)
.where()
.not(Expr.eq("id", 1))
.raw("orderQty < shipQty")
.findList();
}
@Test
public void testRawWithBindParams() {
ResetBasicData.reset();
Ebean.find(OrderDetail.class)
.where()
.ne("id", 42)
.raw("orderQty < ?", 100)
.gt("id", 1)
.raw("unitPrice > ? and product.id > ?", 2, 3)
.findList();
}
}
package com.avaje.tests.query;
import com.avaje.ebean.Query;
import com.avaje.tests.model.basic.Order;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 java.sql.Timestamp;
import static org.assertj.core.api.Assertions.assertThat;
public class TestWhereRawClause extends BaseTestCase {
@Test
public void testRawClauseWithJunction() {
ResetBasicData.reset();
Query<Order> query = Ebean.find(Order.class)
.where()
.raw("(status = ? or (orderDate < ? and shipDate is null) or customer.name like ?)",
Order.Status.APPROVED, new Timestamp(System.currentTimeMillis()), "Rob")
.query();
query.findList();
assertThat(query.getGeneratedSql()).contains(" where (t0.status = ? or (t0.order_date < ? and t0.ship_date is null) or t1.name like ?)");
}
@Test
public void testRawClause() {
ResetBasicData.reset();
Ebean.find(OrderDetail.class)
.where()
.not(Expr.eq("id", 1))
.raw("orderQty < shipQty")
.findList();
}
@Test
public void testRawWithBindParams() {
ResetBasicData.reset();
Ebean.find(OrderDetail.class)
.where()
.ne("id", 42)
.raw("orderQty < ?", 100)
.gt("id", 1)
.raw("unitPrice > ? and product.id > ?", 2, 3)
.findList();
}
}
@@ -57,7 +57,7 @@ public class TestDisjunctWhereOuterJoin extends BaseTestCase {
String sql = query.getGeneratedSql();
Assert.assertTrue(sql.contains("select distinct"));
Assert.assertTrue(sql.contains("outer join mrole "));
Assert.assertTrue(sql.contains("left join mrole "));
Assert.assertTrue(sql.contains(".role_name = ?"));
} finally {
@@ -49,14 +49,14 @@ public class TestDisjunctWhereOuterOnMany extends BaseTestCase {
// select distinct t0.id c0, t0.name c1
// from uuone t0
// join uutwo u1 on u1.master_id = t0.id
// left outer join uutwo t1 on t1.master_id = t0.id
// left join uutwo t1 on t1.master_id = t0.id
// where (t0.name = ? or u1.name = ? ) ;
// --bind(testDisjOuter_2_name,testDisjOuter_CHILD_1)
Assert.assertEquals(2, list.size());
Assert.assertEquals(2, rowCount);
String expectedSql = "select distinct t0.id, t0.name from uuone t0 left outer join uutwo u1 on u1.master_id = t0.id where (t0.name = ? or u1.name = ? ) ";
String expectedSql = "select distinct t0.id, t0.name from uuone t0 left join uutwo u1 on u1.master_id = t0.id where (t0.name = ? or u1.name = ? ) ";
Assert.assertEquals(expectedSql, sqlOf(query, 1));
}
@@ -50,14 +50,14 @@ public class TestQueryJoinManyNonRoot extends BaseTestCase {
assertTrue(!list.isEmpty());
assertTrue(sql.contains("join o_customer t1 on t1.id "));
assertTrue(sql.contains("left outer join contact t2 on"));
assertTrue(sql.contains("left join contact t2 on"));
// select t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t1.name c4, t0.cretime c5, t0.updtime c6,
// t1.id c7, t1.status c8, t1.name c9, t1.smallnote c10, t1.anniversary c11, t1.cretime c12, t1.updtime c13, t1.billing_address_id c14, t1.shipping_address_id c15,
// t2.id c16, t2.first_name c17, t2.last_name c18, t2.phone c19, t2.mobile c20, t2.email c21, t2.cretime c22, t2.updtime c23, t2.customer_id c24, t2.group_id c25
// from o_order t0
// join o_customer t1 on t1.id = t0.kcustomer_id
// left outer join contact t2 on t2.customer_id = t1.id
// left join contact t2 on t2.customer_id = t1.id
// where t0.id > ? ; --bind(0)
}
@@ -79,10 +79,10 @@ public class TestQueryJoinManyNonRoot extends BaseTestCase {
assertTrue(!list.isEmpty());
assertTrue(sql.contains("join o_customer t1 on t1.id "));
assertTrue(sql.contains("left outer join o_order_detail "));
assertTrue(sql.contains("left outer join o_product "));
assertTrue(sql.contains("left join o_order_detail "));
assertTrue(sql.contains("left join o_product "));
Assert.assertFalse(sql.contains("left outer join contact"));
Assert.assertFalse(sql.contains("left join contact"));
}
@@ -107,10 +107,10 @@ public class TestQueryJoinManyNonRoot extends BaseTestCase {
assertTrue(!list.isEmpty());
assertTrue(sql.contains("join o_customer t1 on t1.id "));
assertTrue(sql.contains("left outer join contact "));
assertTrue(sql.contains("left join contact "));
Assert.assertFalse(sql.contains("left outer join o_order_detail "));
Assert.assertFalse(sql.contains("left outer join o_product "));
Assert.assertFalse(sql.contains("left join o_order_detail "));
Assert.assertFalse(sql.contains("left join o_product "));
}
@@ -80,7 +80,7 @@ public class TestQueryManyToOneWhereClauseJoin extends BaseTestCase {
String generatedSql = query.getGeneratedSql();
Assert.assertTrue(generatedSql.contains("from o_order t0 join o_customer t1 on t1.id = t0.kcustomer_id"));
Assert.assertTrue(generatedSql.contains("left outer join contact t2 on t2.customer_id = t1.id"));
Assert.assertTrue(generatedSql.contains("left join contact t2 on t2.customer_id = t1.id"));
Assert.assertTrue(generatedSql.contains("where lower(t1.name) like ?"));
// select t0.id c0, t0.status c1, t0.order_date c2, t0.ship_date c3, t1.name c4, t0.cretime c5, t0.updtime c6,
@@ -88,7 +88,7 @@ public class TestQueryManyToOneWhereClauseJoin extends BaseTestCase {
// t2.id c16, t2.first_name c17, t2.last_name c18, t2.phone c19, t2.mobile c20, t2.email c21, t2.cretime c22, t2.updtime c23, t2.customer_id c24, t2.group_id c25
// from o_order t0
// join o_customer t1 on t1.id = t0.kcustomer_id
// left outer join contact t2 on t2.customer_id = t1.id
// left join contact t2 on t2.customer_id = t1.id
// where lower(t1.name) like ? ; --bind(rob%)
}
}
@@ -76,7 +76,7 @@ public class TestOrderByWithDistinct extends BaseTestCase {
// select distinct t0.userid c0, t0.user_name c1, t1.id c2, t1.name c3
// from muser t0
// left outer join muser_type t1 on t1.id = t0.user_type_id
// left join muser_type t1 on t1.id = t0.user_type_id
// join mrole_muser u1z_ on u1z_.muser_userid = t0.userid
// join mrole u1 on u1.roleid = u1z_.mrole_roleid
// where u1.role_name = ?
@@ -109,7 +109,7 @@ public class TestOrderByWithDistinct extends BaseTestCase {
// select distinct t0.userid c0, t0.user_name c1, t1.id c2, t1.name c3
// from muser t0
// left outer join muser_type t1 on t1.id = t0.user_type_id
// left join muser_type t1 on t1.id = t0.user_type_id
// join mrole_muser u1z_ on u1z_.muser_userid = t0.userid
// join mrole u1 on u1.roleid = u1z_.mrole_roleid
// where u1.role_name = ?
@@ -37,12 +37,12 @@ public class TestQueryConversationRowCount extends BaseTestCase {
// select distinct t0.id c0, t0.title c1, t0.open c2, t0.version c3, t0.when_created c4, t0.when_updated c5, t0.group_id c6, t0.when_created
// from c_conversation t0
// left outer join c_participation u1 on u1.conversation_id = t0.id
// left join c_participation u1 on u1.conversation_id = t0.id
// where t0.group_id = ? and ((t0.open = ? and u1.user_id = ? ) or t0.open = ? )
// order by t0.when_created desc;
Assert.assertTrue(generatedSql.contains("select distinct t0.id, t0.title, t0.isopen"));
Assert.assertTrue(generatedSql.contains("left outer join c_participation u1 on u1.conversation_id = t0.id"));
Assert.assertTrue(generatedSql.contains("left join c_participation u1 on u1.conversation_id = t0.id"));
Assert.assertTrue(generatedSql.contains("where t0.group_id = ? and ((t0.isopen = ? and u1.user_id = ? ) or t0.isopen = ? )"));
@@ -52,7 +52,7 @@ public class TestQueryConversationRowCount extends BaseTestCase {
// select count(*) from (
// select distinct t0.id c0
// from c_conversation t0
// left outer join c_participation u1 on u1.conversation_id = t0.id
// left join c_participation u1 on u1.conversation_id = t0.id
// where t0.group_id = ? and ((t0.open = ? and u1.user_id = ? ) or t0.open = ? )
// ); --bind(1,true,1,true)
@@ -60,7 +60,7 @@ public class TestQueryConversationRowCount extends BaseTestCase {
Assert.assertEquals(1, loggedSql.size());
String countSql = trimSql(loggedSql.get(0), 0);
Assert.assertTrue(countSql.contains("select count(*) from ( select distinct t0.id from c_conversation t0 left outer join c_participation u1 on u1.conversation_id = t0.id where t0.group_id = ? and ((t0.isopen = ? and u1.user_id = ? ) or t0.isopen = ? )"));
Assert.assertTrue(countSql.contains("select count(*) from ( select distinct t0.id from c_conversation t0 left join c_participation u1 on u1.conversation_id = t0.id where t0.group_id = ? and ((t0.isopen = ? and u1.user_id = ? ) or t0.isopen = ? )"));
}
}
@@ -30,6 +30,6 @@ public class TestQueryRawExpressionMany extends BaseTestCase {
query.findCount();
List<String> sql = LoggedSqlCollector.stop();
assertThat(trimSql(sql.get(0), 1)).contains("select count(*) from ( select distinct t0.id from o_order t0 left outer join o_order_detail t1 on t1.order_id = t0.id where t1.order_qty = ?)");
assertThat(trimSql(sql.get(0), 1)).contains("select count(*) from ( select distinct t0.id from o_order t0 left join o_order_detail t1 on t1.order_id = t0.id where t1.order_qty = ?)");
}
}
@@ -34,14 +34,14 @@ public class TestQueryRowCountWithMany extends BaseTestCase {
// t1.id c8, t1.order_qty c9, t1.ship_qty c10, t1.unit_price c11, t1.cretime c12, t1.updtime c13, t1.order_id c14, t1.product_id c15, t0.cretime, t0.id, t1.id, t1.order_qty, t1.cretime
// from o_order t0
// join o_customer t2 on t2.id = t0.kcustomer_id
// left outer join o_order_detail t1 on t1.order_id = t0.id
// left join o_order_detail t1 on t1.order_id = t0.id
// join o_order_detail u1 on u1.order_id = t0.id
// where t1.id > 0 and u1.product_id = ?
// order by t0.cretime, t0.id, t1.id asc, t1.order_qty asc, t1.cretime desc; --bind(1)
String generatedSql = sqlOf(query, 1);
Assert.assertTrue(generatedSql.contains("select distinct t0.id, t0.status,")); // need the distinct
Assert.assertTrue(generatedSql.contains("left outer join o_order_detail t1 on t1.order_id = t0.id")); //fetch join
Assert.assertTrue(generatedSql.contains("left join o_order_detail t1 on t1.order_id = t0.id")); //fetch join
Assert.assertTrue(generatedSql.contains("join o_order_detail u1 on u1.order_id = t0.id")); //predicate join
Assert.assertTrue(generatedSql.contains(" u1.product_id = ?")); // u1 as predicate alias
Assert.assertTrue(generatedSql.contains(" order by t0.cretime"));
@@ -50,7 +50,7 @@ public class TestQueryRowCountWithMany extends BaseTestCase {
int rowCount = query.findCount();
// select count(*) from o_order t0
// left outer join o_order_detail t1 on t1.order_id = t0.id
// left join o_order_detail t1 on t1.order_id = t0.id
// where t1.product_id = ? ; --bind(1)
// select count(*) from (
@@ -107,7 +107,7 @@ public class TestQuerySingleAttribute extends BaseTestCase {
List<String> names = query.findSingleAttributeList();
assertThat(sqlOf(query)).contains("select distinct t0.name from o_customer t0 left outer join o_address t1 on t1.id = t0.billing_address_id where t0.status = ? and lower(t1.city) like ?");
assertThat(sqlOf(query)).contains("select distinct t0.name from o_customer t0 left join o_address t1 on t1.id = t0.billing_address_id where t0.status = ? and lower(t1.city) like ?");
assertThat(names).isNotNull();
}
@@ -1,74 +1,74 @@
package com.avaje.tests.rawsql;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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();
Assert.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) {
Order order = oa.getOrder();
order.getId();
order.getStatus();
oa.getTotalAmount();
Customer c = order.getCustomer();
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 org.junit.Assert;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
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 BaseTestCase {
@Test
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();
Assert.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) {
Order order = oa.getOrder();
order.getId();
order.getStatus();
oa.getTotalAmount();
Customer c = order.getCustomer();
c.getId();
c.getName();
// invoke lazy loading as this property
// has not populated originally
// order.getOrderDate();
}
}
}

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