Refactor tests, move some internal deploy tests to ebean-core

This commit is contained in:
Rob Bygrave
2022-03-27 17:44:43 +13:00
parent 2acdf2f4bf
commit 28088a5e54
26 changed files with 556 additions and 79 deletions
@@ -1,14 +1,50 @@
package io.ebeaninternal.server.deploy;
import io.ebean.DB;
import io.ebean.Database;
import io.ebean.annotation.Platform;
import io.ebeaninternal.api.SpiEbeanServer;
import org.tests.model.basic.Animal;
import javax.persistence.PersistenceException;
public class BaseTest {
protected SpiEbeanServer server = (SpiEbeanServer)DB.getDefault();
protected SpiEbeanServer db = (SpiEbeanServer)DB.getDefault();
protected <T> BeanDescriptor<T> getBeanDescriptor(Class<T> cls) {
return server.descriptor(cls);
return db.descriptor(cls);
}
protected SpiEbeanServer spiEbeanServer() {
return db;
}
protected Database server() {
return db;
}
protected void initTables() {
try {
db.find(Animal.class).findCount();
} catch (PersistenceException e) {
db.script().run("/h2-init.sql");
}
}
protected boolean isH2() {
return isPlatform(Platform.H2);
}
protected boolean isPostgres() {
return isPlatform(Platform.POSTGRES);
}
protected boolean isSqlServer() {
return isPlatform(Platform.SQLSERVER);
}
protected boolean isMySql() {
return isPlatform(Platform.MYSQL);
}
protected boolean isPlatform(Platform platform) {
return db.platform().base().equals(platform);
}
}
@@ -0,0 +1,177 @@
package io.ebeaninternal.server.deploy;
import io.ebean.DB;
import io.ebean.bean.EntityBean;
import io.ebean.plugin.Property;
import io.ebeaninternal.server.core.CacheOptions;
import io.ebeaninternal.server.deploy.meta.DeployBeanDescriptor;
import io.ebeaninternal.server.deploy.meta.DeployIdentityMode;
import io.ebeanservice.docstore.api.DocStoreBeanAdapter;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.*;
import org.tests.model.bridge.BSite;
import org.tests.model.bridge.BUser;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BeanDescriptorTest extends BaseTest {
private BeanDescriptor<Customer> customerDesc = spiEbeanServer().descriptor(Customer.class);
@Test
public void createReference() {
Customer bean = customerDesc.createReference(null, false, 42, null);
assertThat(bean.getId()).isEqualTo(42);
Assertions.assertThat(server().beanState(bean).isReadOnly()).isFalse();
}
@Test
public void createReference_whenReadOnly() {
Customer bean = customerDesc.createReference(Boolean.TRUE, false, 42, null);
Assertions.assertThat(server().beanState(bean).isReadOnly()).isTrue();
}
@Test
public void createReference_whenNotReadOnly() {
Customer bean = customerDesc.createReference(Boolean.FALSE, false, 42, null);
Assertions.assertThat(server().beanState(bean).isReadOnly()).isFalse();
bean = customerDesc.createReference(42, null);
Assertions.assertThat(server().beanState(bean).isReadOnly()).isFalse();
}
@Test
public void createReference_when_disabledLazyLoad() {
Customer bean = customerDesc.createReference(Boolean.FALSE, true, 42, null);
Assertions.assertThat(server().beanState(bean).isDisableLazyLoad()).isTrue();
}
@Test
public void createReference_with_inheritance() {
initTables();
Cat cat = new Cat();
cat.setName("Puss");
DB.save(cat);
Dog dog = new Dog();
dog.setRegistrationNumber("DOGGIE");
DB.save(dog);
AnimalShelter shelter = new AnimalShelter();
shelter.setName("My Animal Shelter");
shelter.getAnimals().add(cat);
shelter.getAnimals().add(dog);
DB.save(shelter);
BeanDescriptor<Animal> animalDesc = spiEbeanServer().descriptor(Animal.class);
Animal bean = animalDesc.createReference(Boolean.FALSE, false, dog.getId(), null);
assertThat(bean.getId()).isEqualTo(dog.getId());
}
@Test
public void allProperties() {
BeanDescriptor<Order> desc = getBeanDescriptor(Order.class);
Collection<? extends Property> props = desc.allProperties();
assertThat(props).extracting("name").contains("id", "status", "orderDate", "shipDate");
}
@Test
public void matchBaseTable() {
BeanDescriptor<Customer> desc = getBeanDescriptor(Customer.class);
assertTrue(desc.matchBaseTable("o_customer"));
}
@Test
public void matchBaseTable_whenTableHasSchema_expect_matchRegardlessOfSchema() {
DeployBeanDescriptor<Customer> deploy = mockDeployCustomer();
when(deploy.getBaseTable()).thenReturn("foo.o_customer");
BeanDescriptor<?> desc1 = new BeanDescriptor<>(mockOwner(), deploy);
assertTrue(desc1.matchBaseTable("o_customer"));
when(deploy.getBaseTable()).thenReturn("bar.o_customer");
BeanDescriptor<?> desc2 = new BeanDescriptor<>(mockOwner(), deploy);
assertTrue(desc2.matchBaseTable("o_customer"));
}
@SuppressWarnings("unchecked")
private DeployBeanDescriptor<Customer> mockDeployCustomer() {
DeployBeanDescriptor<Customer> deploy = mock(DeployBeanDescriptor.class);
when(deploy.getBeanType()).thenReturn(Customer.class);
when(deploy.getIdentityMode()).thenReturn(DeployIdentityMode.auto());
when(deploy.buildIdentityMode()).thenReturn(IdentityMode.NONE);
when(deploy.getCacheOptions()).thenReturn(CacheOptions.NO_CACHING);
return deploy;
}
private BeanDescriptorMap mockOwner() {
BeanDescriptorMap owner = mock(BeanDescriptorMap.class);
when(owner.createDocStoreBeanAdapter(any(), any())).thenReturn(mock(DocStoreBeanAdapter.class));
return owner;
}
@Test
public void merge_when_empty() {
Customer from = new Customer();
from.setId(42);
from.setName("rob");
Customer to = new Customer();
customerDesc.merge((EntityBean) from, (EntityBean) to);
assertThat(to.getId()).isEqualTo(42);
assertThat(to.getName()).isEqualTo("rob");
}
@Test
public void isIdTypeExternal_when_externalId() {
BeanDescriptor<Country> countryDesc = spiEbeanServer().descriptor(Country.class);
assertThat(countryDesc.isIdGeneratedValue()).isFalse();
}
@Test
public void isIdTypeExternal_when_platformGenerator_noGeneratedValueAnnotation() {
assertThat(customerDesc.isIdGeneratedValue()).isFalse();
}
@Test
public void isIdTypeExternal_when_explicitGeneratedValue() {
BeanDescriptor<Contact> desc = spiEbeanServer().descriptor(Contact.class);
assertThat(desc.isIdGeneratedValue()).isTrue();
}
@Test
public void isIdTypeExternal_when_uuidGenerator_and_generatedValue() {
BeanDescriptor<BSite> desc = spiEbeanServer().descriptor(BSite.class);
assertThat(desc.isIdGeneratedValue()).isTrue();
}
@Test
public void isIdTypeExternal_when_uuidGenerator_and_noGeneratedValue() {
BeanDescriptor<BUser> desc = spiEbeanServer().descriptor(BUser.class);
assertThat(desc.isIdGeneratedValue()).isFalse();
}
}
@@ -0,0 +1,114 @@
package io.ebeaninternal.server.deploy;
import io.ebean.DatabaseFactory;
import io.ebean.config.DatabaseConfig;
import io.ebean.event.AbstractBeanPersistListener;
import io.ebean.event.BeanPersistAdapter;
import io.ebean.event.BeanPersistListener;
import io.ebeaninternal.api.SpiEbeanServer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.EBasic;
import static org.junit.jupiter.api.Assertions.*;
public class BeanDescriptor_registerTest {
@Test
public void testRegisterDeregister() {
DatabaseConfig config = new DatabaseConfig();
config.setName("h2other");
config.loadFromProperties();
config.setDdlExtra(false);
config.setRegister(false);
config.setDefaultServer(false);
config.getClasses().add(EBasic.class);
SpiEbeanServer ebeanServer = (SpiEbeanServer)DatabaseFactory.create(config);
try {
BeanDescriptor<EBasic> desc = ebeanServer.descriptor(EBasic.class);
persistListenerRegistrationTests(desc);
persistControllerRegistrationTests(desc);
} finally {
ebeanServer.shutdown();
}
}
private void persistControllerRegistrationTests(BeanDescriptor<EBasic> desc) {
Controller1 controller1 = new Controller1();
assertNull(desc.persistController());
desc.register(controller1);
assertSame(controller1, desc.persistController());
Controller2 controller2 = new Controller2();
desc.register(controller2);
Assertions.assertEquals(2, ((ChainedBeanPersistController) desc.persistController()).size());
desc.deregister(controller1);
assertEquals(1, ((ChainedBeanPersistController) desc.persistController()).size());
desc.deregister(controller2);
assertEquals(0, ((ChainedBeanPersistController) desc.persistController()).size());
}
private void persistListenerRegistrationTests(BeanDescriptor<EBasic> desc) {
Listener1 listener1 = new Listener1();
assertNull(desc.persistListener());
desc.register(listener1);
assertSame(listener1, desc.persistListener());
Listener2 listener2 = new Listener2();
desc.register(listener2);
BeanPersistListener persistListener = desc.persistListener();
assertTrue(persistListener instanceof ChainedBeanPersistListener);
assertEquals(2, ((ChainedBeanPersistListener) persistListener).size());
desc.deregister(listener1);
assertEquals(1, ((ChainedBeanPersistListener) desc.persistListener()).size());
desc.deregister(listener2);
assertEquals(0, ((ChainedBeanPersistListener) desc.persistListener()).size());
}
public static class Listener1 extends AbstractBeanPersistListener {
@Override
public boolean isRegisterFor(Class<?> cls) {
return EBasic.class.isAssignableFrom(cls);
}
}
public static class Listener2 extends AbstractBeanPersistListener {
@Override
public boolean isRegisterFor(Class<?> cls) {
return EBasic.class.isAssignableFrom(cls);
}
}
public static class Controller1 extends BeanPersistAdapter {
@Override
public boolean isRegisterFor(Class<?> cls) {
return EBasic.class.isAssignableFrom(cls);
}
}
public static class Controller2 extends BeanPersistAdapter {
@Override
public boolean isRegisterFor(Class<?> cls) {
return EBasic.class.isAssignableFrom(cls);
}
}
}
@@ -0,0 +1,32 @@
package io.ebeaninternal.server.deploy;
import io.ebean.DB;
import io.ebeaninternal.api.SpiEbeanServer;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.Customer;
import org.tests.model.basic.EBasic;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class BeanDescriptor_whenCreatedPropertyTest {
@Test
public void test() {
SpiEbeanServer server = (SpiEbeanServer) DB.getDefault();
BeanDescriptor<Customer> desc = server.descriptor(Customer.class);
BeanProperty whenCreatedProperty = desc.whenCreatedProperty();
assertEquals("cretime", whenCreatedProperty.dbColumn());
BeanProperty whenModifiedProperty = desc.whenModifiedProperty();
assertEquals("updtime", whenModifiedProperty.dbColumn());
BeanDescriptor<EBasic> eBasicDesc = server.descriptor(EBasic.class);
assertNull(eBasicDesc.whenCreatedProperty());
assertNull(eBasicDesc.whenModifiedProperty());
}
}
@@ -0,0 +1,81 @@
package io.ebeaninternal.server.deploy;
import io.ebean.DB;
import io.ebean.bean.BeanCollection;
import io.ebean.bean.EntityBean;
import io.ebean.common.BeanList;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.Contact;
import org.tests.model.basic.Customer;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
public class BeanPropertyAssocManyTest extends BaseTest {
private BeanDescriptor<Customer> customerDesc = spiEbeanServer().descriptor(Customer.class);
@SuppressWarnings("unchecked")
private BeanPropertyAssocMany<Customer> contacts() {
return (BeanPropertyAssocMany<Customer>) customerDesc.beanProperty("contacts");
}
@Test
public void createReferenceIfNull_when_notBeanCollection_expect_null() {
Customer customer = new Customer();
customer.setContacts(new ArrayList<>());
BeanCollection<?> ref = contacts().createReferenceIfNull((EntityBean) customer);
assertNull(ref);
}
@Test
public void createReferenceIfNull_when_null_expect_ref() {
Customer customer = new Customer();
customer.setContacts(null);
BeanCollection<?> ref = contacts().createReferenceIfNull((EntityBean) customer);
assertNotNull(ref);
assertTrue(ref.isReference());
}
@Test
public void lazyLoadMany_addsToParentCollection() {
Customer customer = new Customer();
customer.setContacts(new BeanList<>());
Contact contact = new Contact();
contact.setCustomer(customer);
contacts().lazyLoadMany((EntityBean) contact);
assertThat(customer.getContacts()).hasSize(1);
assertThat(customer.getContacts().get(0)).isSameAs(contact);
}
// @Test
// public void findIdsByParentId() {
//
// ResetBasicData.reset();
//
// List<Long> ids = DB.find(Customer.class).orderBy("id").setMaxRows(2).findIds();
//
// List<Object> customerIds = new ArrayList<>();
// customerIds.add(ids.get(0));
// customerIds.add(ids.get(1));
//
// List<Object> contactIdsForOne = contacts().findIdsByParentId(ids.get(0), null, null, null, true);
//
// List<Object> contactIdsForMultiple = contacts().findIdsByParentId(null, customerIds, null, null, true);
//
// assertThat(contactIdsForOne).isNotEmpty();
// assertThat(contactIdsForMultiple).isNotEmpty();
// }
}
@@ -0,0 +1,87 @@
package io.ebeaninternal.server.deploy;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.Address;
import org.tests.model.basic.BWithQIdent;
import org.tests.model.basic.Customer;
public class DeployPropertyParserTest extends BaseTest {
private final BeanDescriptor<Customer> descriptor = getBeanDescriptor(Customer.class);
private final BeanDescriptor<Address> addressBeanDescriptor = getBeanDescriptor(Address.class);
private final BeanDescriptor<BWithQIdent> bWithQIdentDescriptor = getBeanDescriptor(BWithQIdent.class);
@Test
public void from_prefix_expect_unchanged() {
Assertions.assertThat(parser().parse("(select x from status join status)")).isEqualTo("(select x from status join status)");
}
@Test
public void depth0_path() {
Assertions.assertThat(parser().parse("pre status post")).isEqualTo("pre ${}status post");
}
@Test
public void depth1_path() {
Assertions.assertThat(parser().parse("billingAddress.city")).isEqualTo("${billingAddress}city");
}
@Test
public void depth2_path() {
Assertions.assertThat(parser().parse("max(billingAddress.country.name)")).isEqualTo("max(${billingAddress.country}name)");
}
@Test
public void simpleMax() {
Assertions.assertThat(parser().parse("max(name)")).isEqualTo("max(${}name)");
}
@Test
public void combined() {
Assertions.assertThat(parser().parse("sum(status * name)")).isEqualTo("sum(${}status * ${}name)");
}
@Test
public void combined_withAtColumn() {
Assertions.assertThat(addressParser().parse("concat(line1, line2, '-EA')")).isEqualTo("concat(${}line_1, ${}line_2, '-EA')");
}
@Test
public void withExplicitQuote_all_platforms() {
Assertions.assertThat(withQuoteParser().parse("t0.`CODE` like ?")).isEqualTo("t0.`CODE` like ?");
Assertions.assertThat(withQuoteParser().parse("t0.[CODE] like ?")).isEqualTo("t0.[CODE] like ?");
Assertions.assertThat(withQuoteParser().parse("t0.\"CODE\" like ?")).isEqualTo("t0.\"CODE\" like ?");
}
@Test
public void withQuote_when_match_h2() {
if (isH2() || isPostgres()) {
Assertions.assertThat(withQuoteParser().parse("name like ?")).isEqualTo("${}\"Name\" like ?");
} else if (isSqlServer()) {
Assertions.assertThat(withQuoteParser().parse("name like ?")).isEqualTo("${}[Name] like ?");
} else if (isMySql()) {
Assertions.assertThat(withQuoteParser().parse("name like ?")).isEqualTo("${}`Name` like ?");
}
}
@Test
public void unknown_path() {
Assertions.assertThat(parser().parse(" foo ")).isEqualTo(" foo ");
}
private DeployPropertyParser parser() {
return descriptor.parser();
}
private DeployPropertyParser addressParser() {
return addressBeanDescriptor.parser();
}
private DeployPropertyParser withQuoteParser() {
return bWithQIdentDescriptor.parser();
}
}
@@ -0,0 +1,79 @@
package io.ebeaninternal.server.deploy;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.Customer;
import static org.assertj.core.api.Assertions.assertThat;
public class FormulaPropertyPathTest extends BaseTest {
private BeanDescriptor<Customer> customerDesc = getBeanDescriptor(Customer.class);
@Test
public void isFormula() {
assertFormula("max(version)", "max", "version");
assertFormula("min(name)", "min", "name");
assertFormula("avg(id)", "avg", "id");
}
@Test
public void isFormula_count() {
assertFormula("count(status)", "count", "status");
assertFormula("count(distinct name)", "count", "name");
}
@Test
public void concat() {
assertFormula("concat(name,'-end')", "concat", "name,'-end'");
}
@Test
public void castFormula() {
assertFormula("concat(name,'-end')::String", "concat", "name,'-end'", "String", null);
}
@Test
public void cast_javaInstant() {
assertFormula("max(updtime)::Instant", "max", "updtime", "Instant", null);
}
@Test
public void alias() {
assertFormula("concat(name,'-end') name", "concat", "name,'-end'", null, "name");
assertFormula("concat(name,'-end') as name", "concat", "name,'-end'", null, "name");
}
@Test
public void castAndAlias() {
assertFormula("concat(name,'-end')::String name", "concat", "name,'-end'", "String", "name");
assertFormula("concat(name,'-end')::String as name", "concat", "name,'-end'", "String", "name");
}
private void assertFormula(String input, String funcName, String expression) {
assertFormula(input, funcName, expression, null, null);
}
private void assertFormula(String input, String funcName, String expression, String cast, String alias) {
FormulaPropertyPath propertyPath = new FormulaPropertyPath(customerDesc, input, null);
assertThat(propertyPath.internalExpression()).isEqualTo(expression);
assertThat(propertyPath.outerFunction()).isEqualTo(funcName);
if (cast != null) {
assertThat(propertyPath.cast()).isEqualTo(cast);
} else {
assertThat(propertyPath.cast()).isNull();
}
if (alias != null) {
assertThat(propertyPath.alias()).isEqualTo(alias);
} else {
assertThat(propertyPath.alias()).isNull();
}
assertThat(propertyPath.build()).isNotNull();
}
}
@@ -0,0 +1,120 @@
package io.ebeaninternal.server.deploy;
import io.ebean.DB;
import io.ebean.Database;
import io.ebean.bean.EntityBean;
import io.ebean.bean.EntityBeanIntercept;
import io.ebeaninternal.api.SpiEbeanServer;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.Customer;
import org.tests.model.basic.Order;
import org.tests.model.composite.RCustomer;
import org.tests.model.composite.RCustomerKey;
import org.tests.model.embedded.UserInterestLive;
import org.tests.model.embedded.UserInterestLiveKey;
import java.sql.Timestamp;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
public class TestBeanDescriptorHasIdProperty extends BaseTest {
SpiEbeanServer spiServer;
public TestBeanDescriptorHasIdProperty() {
Database server = DB.getDefault();
spiServer = (SpiEbeanServer) server;
}
@Test
public void testHasId() {
BeanDescriptor<Order> beanDescriptor = spiServer.descriptor(Order.class);
assertNotNull(beanDescriptor.idProperty());
assertEquals("id", beanDescriptor.idProperty().name());
assertNotNull(beanDescriptor.versionProperty());
assertEquals("updtime", beanDescriptor.versionProperty().name());
Order order = new Order();
assertFalse(beanDescriptor.hasIdValue(entityBean(order)));
assertFalse(beanDescriptor.hasVersionProperty(getIntercept(order)));
order.setId(23);
order.setUpdtime(new Timestamp(System.currentTimeMillis()));
assertTrue(beanDescriptor.hasIdValue(entityBean(order)));
assertTrue(beanDescriptor.hasVersionProperty(getIntercept(order)));
}
@Test
public void testIsReference() {
BeanDescriptor<Customer> beanDescriptor = spiServer.descriptor(Customer.class);
Customer order = new Customer();
EntityBeanIntercept ebi = getIntercept(order);
assertFalse(beanDescriptor.referenceIdPropertyOnly(ebi));
order.setId(23);
assertTrue(beanDescriptor.referenceIdPropertyOnly(ebi));
order.setName("custName");
assertFalse(beanDescriptor.referenceIdPropertyOnly(ebi));
}
@Test
public void isReference_withGeneratedOnInsertOnlyProperty_expect_false() {
BeanDescriptor<UserInterestLive> descriptor = spiServer.descriptor(UserInterestLive.class);
UserInterestLive bean = new UserInterestLive(new UserInterestLiveKey(1L, 2L));
EntityBeanIntercept ebi = getIntercept(bean);
assertFalse(descriptor.referenceIdPropertyOnly(ebi));
}
@Test
public void test_getIdForJson() {
BeanDescriptor<Order> orderDesc = spiServer.descriptor(Order.class);
Order order = new Order();
order.setId(42);
assertEquals(42, orderDesc.idForJson(order));
assertEquals(42, orderDesc.convertIdFromJson(42));
assertEquals(42, orderDesc.convertIdFromJson("42"));
assertEquals(42, orderDesc.convertIdFromJson(42L));
RCustomerKey key = new RCustomerKey();
key.setCompany("comp");
key.setName("fred");
RCustomer rCustomer = new RCustomer();
rCustomer.setKey(key);
BeanDescriptor<RCustomer> rcustDesc = spiServer.descriptor(RCustomer.class);
@SuppressWarnings("unchecked")
Map<String, Object> idForJson = (Map<String, Object>) rcustDesc.idForJson(rCustomer);
assertEquals("comp", idForJson.get("company"));
assertEquals("fred", idForJson.get("name"));
assertEquals(2, idForJson.size());
RCustomerKey keyVal = (RCustomerKey) rcustDesc.convertIdFromJson(idForJson);
assertEquals("comp", keyVal.getCompany());
assertEquals("fred", keyVal.getName());
}
private EntityBean entityBean(Object bean) {
return (EntityBean) bean;
}
private EntityBeanIntercept getIntercept(Object bean) {
return ((EntityBean) bean)._ebean_getIntercept();
}
}
@@ -0,0 +1,41 @@
package io.ebeaninternal.server.deploy;
import io.ebean.DB;
import io.ebean.bean.BeanCollection;
import io.ebean.bean.EntityBean;
import io.ebean.bean.EntityBeanIntercept;
import io.ebeaninternal.api.SpiEbeanServer;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.Contact;
import org.tests.model.basic.Customer;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class TestCollectionLoadedStatus {
@Test
public void test() {
SpiEbeanServer server = (SpiEbeanServer) DB.getDefault();
BeanDescriptor<Customer> custDesc = server.descriptor(Customer.class);
Customer customer = new Customer();
EntityBean eb = (EntityBean) customer;
EntityBeanIntercept ebi = eb._ebean_getIntercept();
BeanProperty contactsProperty = custDesc.beanProperty("contacts");
assertFalse(ebi.isLoadedProperty(contactsProperty.propertyIndex()));
Object contactsViaInternal = contactsProperty.getValue(eb);
assertNull(contactsViaInternal);
assertFalse(ebi.isLoadedProperty(contactsProperty.propertyIndex()));
List<Contact> contacts = customer.getContacts();
assertNotNull(contacts);
assertTrue(contacts instanceof BeanCollection);
assertTrue(ebi.isLoadedProperty(contactsProperty.propertyIndex()));
}
}
@@ -0,0 +1,61 @@
package io.ebeaninternal.server.deploy;
import io.ebean.Database;
import io.ebean.bean.EntityBean;
import io.ebeaninternal.api.json.SpiJsonWriter;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.Customer;
import org.tests.model.basic.Order;
import org.tests.model.basic.Order.Status;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Date;
import java.sql.Timestamp;
import static org.assertj.core.api.Assertions.assertThat;
public class TestDiffHelpInsertSimple extends BaseTest {
private final long firstTime = System.currentTimeMillis() - 10000;
private final BeanDescriptor<Order> orderDesc;
public TestDiffHelpInsertSimple() {
orderDesc = db.descriptor(Order.class);
}
private Order createBaseOrder(Database server) {
Order order1 = new Order();
order1.setId(12);
order1.setCretime(new Timestamp(firstTime));
order1.setCustomer(server.reference(Customer.class, 1234));
order1.setStatus(Status.NEW);
//order1.setShipDate(new Date(firstTime));
order1.setOrderDate(new Date(firstTime));
return order1;
}
@Test
public void basic() throws IOException {
Date date = Date.valueOf("2000-01-01");
Order order1 = createBaseOrder(db);
order1.setOrderDate(date);
StringWriter buffer = new StringWriter();
SpiJsonWriter jsonWriter = spiEbeanServer().jsonExtended().createJsonWriter(buffer);
orderDesc.jsonWriteForInsert(jsonWriter, (EntityBean) order1);
jsonWriter.flush();
String asJson = buffer.toString();
assertThat(asJson).startsWith("{\"status\":\"NEW\",\"orderDate\":\"2000-01-01\"");
assertThat(asJson).endsWith(",\"customer\":{\"id\":1234}}");
}
}
@@ -0,0 +1,89 @@
package io.ebeaninternal.server.deploy;
import io.ebean.bean.EntityBean;
import io.ebeaninternal.api.json.SpiJsonWriter;
import org.junit.jupiter.api.Test;
import org.tests.model.embedded.EMain;
import org.tests.model.embedded.Eembeddable;
import java.io.IOException;
import java.io.StringWriter;
import static org.assertj.core.api.Assertions.assertThat;
public class TestDiffHelpInsertWithEmbedded extends BaseTest {
private final BeanDescriptor<EMain> emainDesc;
public TestDiffHelpInsertWithEmbedded() {
emainDesc = getBeanDescriptor(EMain.class);
}
@Test
public void simple() throws IOException {
EMain emain1 = createEMain();
String asJson = asInsertJson((EntityBean) emain1);
assertThat(asJson).contains("{\"name\":\"foo\",\"version\":13,\"embeddable\":{\"description\":\"bar\"}}");
}
private String asInsertJson(EntityBean emain1) throws IOException {
StringWriter buffer = new StringWriter();
SpiJsonWriter jsonWriter = spiEbeanServer().jsonExtended().createJsonWriter(buffer);
emainDesc.jsonWriteForInsert(jsonWriter, emain1);
jsonWriter.flush();
return buffer.toString();
}
@Test
public void scalarPropertyAsNull() throws IOException {
EMain emain1 = createEMain();
emain1.setName(null);
String asJson = asInsertJson((EntityBean) emain1);
assertThat(asJson).contains("{\"version\":13,\"embeddable\":{\"description\":\"bar\"}}");
}
@Test
public void embeddedAsNull() throws IOException {
EMain emain1 = createEMain();
emain1.setEmbeddable(null);
String asJson = asInsertJson((EntityBean) emain1);
assertThat(asJson).contains("{\"name\":\"foo\",\"version\":13}");
}
@Test
public void embeddedPropertiesAsNull() throws IOException {
EMain emain1 = createEMain();
emain1.getEmbeddable().setDescription(null);
String asJson = asInsertJson((EntityBean) emain1);
assertThat(asJson).contains("{\"name\":\"foo\",\"version\":13,\"embeddable\":{}}");
}
private EMain createEMain() {
EMain emain = new EMain();
emain.setName("foo");
emain.setVersion(13L);
Eembeddable embeddable = new Eembeddable();
embeddable.setDescription("bar");
emain.setEmbeddable(embeddable);
return emain;
}
}
@@ -0,0 +1,54 @@
package org.tests.model.basic;
import javax.persistence.*;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "species")
public abstract class Animal {
@Id
Long id;
@Version
Long version;
@Column(name = "species", insertable = false, updatable = false, nullable = false)
String species;
@ManyToOne
AnimalShelter shelter;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public AnimalShelter getShelter() {
return shelter;
}
public void setShelter(AnimalShelter shelter) {
this.shelter = shelter;
}
}
@@ -0,0 +1,57 @@
package org.tests.model.basic;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Version;
import java.util.List;
import static javax.persistence.CascadeType.PERSIST;
@Entity
public class AnimalShelter {
@Id
Long id;
@Version
Long version;
String name;
@OneToMany(cascade = PERSIST, mappedBy = "shelter", orphanRemoval = true)
List<Animal> animals;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Animal> getAnimals() {
return animals;
}
public void setAnimals(List<Animal> animals) {
this.animals = animals;
}
}
@@ -0,0 +1,57 @@
package org.tests.model.basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Version;
import javax.validation.constraints.Size;
import java.sql.Timestamp;
@Entity
public class BWithQIdent {
@Id
Integer id;
@Column(name = "`Name`", unique = true)
@Size(max = 191) // key must not exceed 767 Bytes, so max key len for mysql with utf8mb4 = 191*4 = 764 bytes
String name;
@Column(name = "`CODE`")
String CODE;
@Version
Timestamp lastUpdated;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCODE() {
return CODE;
}
public void setCODE(String CODE) {
this.CODE = CODE;
}
public Timestamp getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Timestamp lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
@@ -0,0 +1,32 @@
package org.tests.model.basic;
import io.ebean.annotation.Formula;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("CAT")
public class Cat extends Animal {
String name;
@Formula(select = "${ta}.species")
String catFormula;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCatFormula() {
return catFormula;
}
public void setCatFormula(String catFormula) {
this.catFormula = catFormula;
}
}
@@ -0,0 +1,31 @@
package org.tests.model.basic;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import java.sql.Date;
@Entity
@DiscriminatorValue("DOG")
public class Dog extends Animal {
String registrationNumber;
Date dateOfBirth;
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
@@ -0,0 +1,20 @@
package org.tests.model.bridge;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.UUID;
@Entity
public class BSite {
@Id @GeneratedValue
UUID id;
String name;
public BSite(String name) {
this.name = name;
}
}
@@ -0,0 +1,19 @@
package org.tests.model.bridge;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.UUID;
@Entity
public class BUser {
@Id
UUID id;
String name;
public BUser(String name) {
this.name = name;
}
}
@@ -0,0 +1,43 @@
package org.tests.model.composite;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
/**
* @author rnentjes
*/
@Entity
public class RCustomer {
@EmbeddedId
private RCustomerKey key;
private String description;
public RCustomer() {
}
public RCustomer(RCustomerKey key, String description) {
this.key = key;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public RCustomerKey getKey() {
return key;
}
public void setKey(RCustomerKey key) {
this.key = key;
}
}
@@ -0,0 +1,68 @@
package org.tests.model.composite;
import javax.persistence.Embeddable;
import javax.validation.constraints.Size;
@Embeddable
public class RCustomerKey {
@Size(max=127)
private String company;
@Size(max=127)
private String name;
public RCustomerKey() {
}
public RCustomerKey(String company, String name) {
this.company = company;
this.name = name;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final RCustomerKey other = (RCustomerKey) obj;
if ((this.company == null) ? (other.company != null) : !this.company.equals(other.company)) {
return false;
}
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 89 * hash + (this.company != null ? this.company.hashCode() : 0);
hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash;
}
}
@@ -0,0 +1,34 @@
package org.tests.model.embedded;
import io.ebean.Model;
import io.ebean.annotation.WhenCreated;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import java.util.Date;
@Entity
public class UserInterestLive extends Model {
@EmbeddedId
private final UserInterestLiveKey key;
@WhenCreated
private Date createdAt;
public UserInterestLive(UserInterestLiveKey key) {
this.key = key;
}
public UserInterestLiveKey getKey() {
return key;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
}
@@ -0,0 +1,30 @@
package org.tests.model.embedded;
import javax.persistence.Embeddable;
import java.util.Objects;
@Embeddable
public class UserInterestLiveKey {
private long userId;
private long liveId;
public UserInterestLiveKey(long userId, long liveId) {
this.userId = userId;
this.liveId = liveId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserInterestLiveKey that = (UserInterestLiveKey) o;
return userId == that.userId &&
liveId == that.liveId;
}
@Override
public int hashCode() {
return Objects.hash(userId, liveId);
}
}