No effective change - change Line endings to CR (from CRLF)

This commit is contained in:
Rob Bygrave
2016-10-15 14:39:20 +13:00
parent c3f43d503f
commit 67469ef4d3
56 changed files with 3309 additions and 3309 deletions
@@ -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());
}
}
@@ -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:"));
}
}
}
@@ -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();
}
}
+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());
}
}
@@ -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");
}
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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());
}
}
@@ -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());
}
}
@@ -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();
}
}
@@ -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();
}
}
}
@@ -1,66 +1,66 @@
package com.avaje.tests.rawsql;
import java.util.List;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.FetchConfig;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.Order.Status;
import com.avaje.tests.model.basic.OrderAggregate;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestRawSqlOrmWrapper3 extends 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();
List<OrderAggregate> list2 = Ebean.find(OrderAggregate.class).setRawSql(rawSql)
.fetch("order", new FetchConfig().query())
.fetch("order.details", new FetchConfig().query())
.where().gt("order.id", 2)
.having().gt("totalAmount", 10)
.filterMany("order.details").gt("unitPrice", 2d)
.findList();
output(list2);
}
private void output(List<OrderAggregate> list) {
for (OrderAggregate oa : list) {
oa.getTotalAmount();
Order order = oa.getOrder();
order.getId();
order.getStatus();
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.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.FetchConfig;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.Order;
import com.avaje.tests.model.basic.Order.Status;
import com.avaje.tests.model.basic.OrderAggregate;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestRawSqlOrmWrapper3 extends 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();
List<OrderAggregate> list2 = Ebean.find(OrderAggregate.class).setRawSql(rawSql)
.fetch("order", new FetchConfig().query())
.fetch("order.details", new FetchConfig().query())
.where().gt("order.id", 2)
.having().gt("totalAmount", 10)
.filterMany("order.details").gt("unitPrice", 2d)
.findList();
output(list2);
}
private void output(List<OrderAggregate> list) {
for (OrderAggregate oa : list) {
oa.getTotalAmount();
Order order = oa.getOrder();
order.getId();
order.getStatus();
Customer c = order.getCustomer();
c.getId();
c.getName();
// invoke lazy loading as this property
// has not populated originally
// order.getOrderDate();
}
}
}
@@ -1,21 +1,21 @@
package com.avaje.tests.singleTableInheritance.model;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("EXT")
public class PalletLocationExternal extends PalletLocation
{
private String attribute;
public String getAttribute()
{
return attribute;
}
public void setAttribute(String attribute)
{
this.attribute = attribute;
}
}
package com.avaje.tests.singleTableInheritance.model;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("EXT")
public class PalletLocationExternal extends PalletLocation
{
private String attribute;
public String getAttribute()
{
return attribute;
}
public void setAttribute(String attribute)
{
this.attribute = attribute;
}
}
@@ -1,24 +1,24 @@
package com.avaje.tests.singleTableInheritance.model;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("INT")
public class ZoneInternal extends Zone {
private String attribute;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
@Override
public String toString() {
return "ZoneInternal " + getId() + " \"" + getAttribute() + "\"";
}
}
package com.avaje.tests.singleTableInheritance.model;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("INT")
public class ZoneInternal extends Zone {
private String attribute;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
@Override
public String toString() {
return "ZoneInternal " + getId() + " \"" + getAttribute() + "\"";
}
}
@@ -1,49 +1,49 @@
package com.avaje.tests.text.csv;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.Locale;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.text.csv.CsvReader;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestCsvReader extends BaseTestCase {
@Test
public void test() {
ResetBasicData.reset();
try {
URL resource = TestCsvReaderWithCallback.class.getResource("/test1.csv");
File f = new File(resource.getFile());
FileReader reader = new FileReader(f);
CsvReader<Customer> csvReader = Ebean.createCsvReader(Customer.class);
csvReader.setPersistBatchSize(2);
csvReader.addIgnore();
// csvReader.addProperty("id");
csvReader.addProperty("status");
csvReader.addProperty("name");
csvReader.addDateTime("anniversary", "dd-MMM-yyyy", Locale.GERMAN);
csvReader.addProperty("billingAddress.line1");
csvReader.addProperty("billingAddress.city");
csvReader.addProperty("billingAddress.country.code");
csvReader.process(reader);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package com.avaje.tests.text.csv;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.Locale;
import org.junit.Test;
import com.avaje.ebean.BaseTestCase;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.text.csv.CsvReader;
import com.avaje.tests.model.basic.Customer;
import com.avaje.tests.model.basic.ResetBasicData;
public class TestCsvReader extends BaseTestCase {
@Test
public void test() {
ResetBasicData.reset();
try {
URL resource = TestCsvReaderWithCallback.class.getResource("/test1.csv");
File f = new File(resource.getFile());
FileReader reader = new FileReader(f);
CsvReader<Customer> csvReader = Ebean.createCsvReader(Customer.class);
csvReader.setPersistBatchSize(2);
csvReader.addIgnore();
// csvReader.addProperty("id");
csvReader.addProperty("status");
csvReader.addProperty("name");
csvReader.addDateTime("anniversary", "dd-MMM-yyyy", Locale.GERMAN);
csvReader.addProperty("billingAddress.line1");
csvReader.addProperty("billingAddress.city");
csvReader.addProperty("billingAddress.country.code");
csvReader.process(reader);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -1,50 +1,50 @@
package com.avaje.tests.unitinternal;
import java.util.Locale;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebeaninternal.server.type.ScalarTypeLocale;
public class TestLocaleParse {
@Test
public void test() {
// Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC"
Locale l = parse("en");
Assert.assertEquals("en", l.getLanguage());
l = parse("de_DE");
Assert.assertEquals("de", l.getLanguage());
Assert.assertEquals("DE", l.getCountry());
l = parse("en_US_WIN");
Assert.assertEquals("en", l.getLanguage());
Assert.assertEquals("US", l.getCountry());
Assert.assertEquals("WIN", l.getVariant());
l = parse("_GB");
Assert.assertEquals("", l.getLanguage());
Assert.assertEquals("GB", l.getCountry());
Assert.assertEquals("", l.getVariant());
l = parse("fr__MAC");
Assert.assertEquals("fr", l.getLanguage());
Assert.assertEquals("", l.getCountry());
Assert.assertEquals("MAC", l.getVariant());
l = parse("de__POSIX");
Assert.assertEquals("de", l.getLanguage());
Assert.assertEquals("", l.getCountry());
Assert.assertEquals("POSIX", l.getVariant());
}
private Locale parse(String value) {
ScalarTypeLocale st = new ScalarTypeLocale();
return (Locale) st.parse(value);
}
}
package com.avaje.tests.unitinternal;
import java.util.Locale;
import org.junit.Assert;
import org.junit.Test;
import com.avaje.ebeaninternal.server.type.ScalarTypeLocale;
public class TestLocaleParse {
@Test
public void test() {
// Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC"
Locale l = parse("en");
Assert.assertEquals("en", l.getLanguage());
l = parse("de_DE");
Assert.assertEquals("de", l.getLanguage());
Assert.assertEquals("DE", l.getCountry());
l = parse("en_US_WIN");
Assert.assertEquals("en", l.getLanguage());
Assert.assertEquals("US", l.getCountry());
Assert.assertEquals("WIN", l.getVariant());
l = parse("_GB");
Assert.assertEquals("", l.getLanguage());
Assert.assertEquals("GB", l.getCountry());
Assert.assertEquals("", l.getVariant());
l = parse("fr__MAC");
Assert.assertEquals("fr", l.getLanguage());
Assert.assertEquals("", l.getCountry());
Assert.assertEquals("MAC", l.getVariant());
l = parse("de__POSIX");
Assert.assertEquals("de", l.getLanguage());
Assert.assertEquals("", l.getCountry());
Assert.assertEquals("POSIX", l.getVariant());
}
private Locale parse(String value) {
ScalarTypeLocale st = new ScalarTypeLocale();
return (Locale) st.parse(value);
}
}