#1624 - ENH: Create io.ebean.DB as alias for Ebean and io.ebean.Database as alias for EbeanServer

This commit is contained in:
rob bygrave
2019-02-01 22:53:41 +13:00
parent 31d7c6fed8
commit f3cb7e2cfd
11 changed files with 2956 additions and 1652 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,67 @@
package io.ebean;
import io.ebean.config.ContainerConfig;
import io.ebean.config.DatabaseConfig;
/**
* Creates Database instances.
* <p>
* This uses either DatabaseConfig or properties in the application.properties file to
* configure and create a Database instance.
* </p>
* <p>
* The Database instance can either be registered with the DB singleton or
* not. The DB singleton effectively holds a map of Database by a name.
* If the Database is registered with the DB singleton you can retrieve it
* later via {@link DB#byName(String)}.
* </p>
* <p>
* One Database can be nominated as the 'default/primary' Database. Many
* methods on the DB singleton such as {@link DB#find(Class)} are just a
* convenient way of using the 'default/primary' Database.
* </p>
*/
public class DatabaseFactory {
/**
* Initialise the container with clustering configuration.
* <p>
* Call this prior to creating any Database instances or alternatively set the
* ContainerConfig on the ServerConfig when creating the first Database instance.
*/
public static synchronized void initialiseContainer(ContainerConfig containerConfig) {
EbeanServerFactory.initialiseContainer(containerConfig);
}
/**
* Create using ebean.properties to configure the server.
*/
public static synchronized Database create(String name) {
return EbeanServerFactory.create(name);
}
/**
* Create using the ServerConfig object to configure the server.
*/
public static synchronized Database create(DatabaseConfig config) {
return EbeanServerFactory.create(config);
}
/**
* Create using the ServerConfig additionally specifying a classLoader to use as the context class loader.
*/
public static synchronized Database createWithContextClassLoader(DatabaseConfig config, ClassLoader classLoader) {
return EbeanServerFactory.createWithContextClassLoader(config, classLoader);
}
/**
* Shutdown gracefully all EbeanServers cleaning up any resources as required.
* <p>
* This is typically invoked via JVM shutdown hook and not explicitly called.
* </p>
*/
public static synchronized void shutdown() {
EbeanServerFactory.shutdown();
}
}
+1 -1
View File
@@ -120,7 +120,7 @@ public final class Ebean {
private static final Logger logger = LoggerFactory.getLogger(Ebean.class);
static {
EbeanVersion.getVersion(); // initalizes the version class and logs the version.
EbeanVersion.getVersion(); // initialises the version class and logs the version.
}
/**
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,44 @@
package io.ebean.config;
import io.ebean.DatabaseFactory;
/**
* The configuration used for creating a Database.
* <p>
* Used to programmatically construct an Database and optionally register it
* with the DB singleton.
* </p>
* <p>
* If you just use DB thout this programmatic configuration Ebean will read
* the application.properties file and take the configuration from there. This usually
* includes searching the class path and automatically registering any entity
* classes and listeners etc.
* </p>
* <pre>{@code
*
* DatabaseConfig config = new DatabaseConfig();
*
* // read the ebean.properties and load
* // those settings into this serverConfig object
* config.loadFromProperties();
*
* // explicitly register the entity beans to avoid classpath scanning
* config.addClass(Customer.class);
* config.addClass(User.class);
*
* Database db = DatabaseFactory.create(config);
*
* }</pre>
*
* <p>
* Note that ServerConfigProvider provides a standard Java ServiceLoader mechanism that can
* be used to apply configuration to the DatabaseConfig.
* </p>
*
* @author emcgreal
* @author rbygrave
* @see DatabaseFactory
*/
public class DatabaseConfig extends ServerConfig {
}
@@ -17,7 +17,7 @@ public class EbeanServer_deleteAllByIdTest extends BaseTestCase {
List<EBasicVer> someBeans = beans(3);
Ebean.saveAll(someBeans);
DB.saveAll(someBeans);
List<Integer> ids = new ArrayList<>();
for (EBasicVer someBean : someBeans) {
ids.add(someBean.getId());
@@ -25,7 +25,7 @@ public class EbeanServer_deleteAllByIdTest extends BaseTestCase {
// act
LoggedSqlCollector.start();
Ebean.deleteAll(EBasicVer.class, ids);
DB.deleteAll(EBasicVer.class, ids);
List<String> loggedSql = LoggedSqlCollector.stop();
assertThat(loggedSql).hasSize(1);
@@ -37,21 +37,18 @@ public class EbeanServer_deleteAllByIdTest extends BaseTestCase {
List<EBasicVer> someBeans = beans(3);
Ebean.saveAll(someBeans);
DB.saveAll(someBeans);
List<Integer> ids = new ArrayList<>();
for (EBasicVer someBean : someBeans) {
ids.add(someBean.getId());
}
EbeanServer server = Ebean.getDefaultServer();
Database db = DB.getDefault();
// act
LoggedSqlCollector.start();
Transaction txn = server.beginTransaction();
try {
server.deleteAll(EBasicVer.class, ids, txn);
try (Transaction txn = db.beginTransaction()) {
db.deleteAll(EBasicVer.class, ids, txn);
txn.commit();
} finally {
txn.end();
}
List<String> loggedSql = LoggedSqlCollector.stop();
assertThat(loggedSql).hasSize(1);
@@ -63,7 +60,7 @@ public class EbeanServer_deleteAllByIdTest extends BaseTestCase {
List<EBasicVer> someBeans = beans(3);
Ebean.saveAll(someBeans);
DB.saveAll(someBeans);
List<Integer> ids = new ArrayList<>();
for (EBasicVer someBean : someBeans) {
ids.add(someBean.getId());
@@ -71,7 +68,7 @@ public class EbeanServer_deleteAllByIdTest extends BaseTestCase {
LoggedSqlCollector.start();
Ebean.deleteAllPermanent(EBasicVer.class, ids);
DB.deleteAllPermanent(EBasicVer.class, ids);
List<String> loggedSql = LoggedSqlCollector.stop();
assertThat(loggedSql).hasSize(1);
@@ -84,21 +81,18 @@ public class EbeanServer_deleteAllByIdTest extends BaseTestCase {
List<EBasicVer> someBeans = beans(3);
Ebean.saveAll(someBeans);
DB.saveAll(someBeans);
List<Integer> ids = new ArrayList<>();
for (EBasicVer someBean : someBeans) {
ids.add(someBean.getId());
}
EbeanServer server = Ebean.getDefaultServer();
Database db = DB.getDefault();
// act
LoggedSqlCollector.start();
Transaction txn = server.beginTransaction();
try {
server.deleteAllPermanent(EBasicVer.class, ids, txn);
try (Transaction txn = db.beginTransaction()) {
db.deleteAllPermanent(EBasicVer.class, ids, txn);
txn.commit();
} finally {
txn.end();
}
List<String> loggedSql = LoggedSqlCollector.stop();
assertThat(loggedSql).hasSize(1);
+29 -27
View File
@@ -1,12 +1,13 @@
package io.ebean.plugin;
import io.ebean.Ebean;
import io.ebean.EbeanServer;
import io.ebean.DB;
import io.ebean.Database;
import io.ebean.FetchPath;
import io.ebean.Query;
import io.ebean.text.PathProperties;
import io.ebeaninternal.api.SpiQuery;
import io.ebeaninternal.server.querydefn.OrmQueryDetail;
import org.junit.Test;
import org.tests.inheritance.Stockforecast;
import org.tests.model.basic.Car;
import org.tests.model.basic.Customer;
@@ -15,60 +16,61 @@ import org.tests.model.basic.OrderDetail;
import org.tests.model.basic.Person;
import org.tests.model.basic.Product;
import org.tests.model.basic.Vehicle;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BeanTypeTest {
static EbeanServer server = Ebean.getDefaultServer();
static Database db = DB.getDefault();
<T> BeanType<T> beanType(Class<T> cls) {
return server.getPluginApi().getBeanType(cls);
return db.getPluginApi().getBeanType(cls);
}
@Test
public void getBeanType() throws Exception {
public void getBeanType() {
assertThat(beanType(Order.class).getBeanType()).isEqualTo(Order.class);
}
@Test
public void getTypeAtPath_when_ManyToOne() throws Exception {
public void getTypeAtPath_when_ManyToOne() {
BeanType<Order> orderType = beanType(Order.class);
BeanType<?> customerType = orderType.getBeanTypeAtPath("customer");
assertThat(customerType.getBeanType()).isEqualTo(Customer.class);
}
@Test
public void getTypeAtPath_when_OneToMany() throws Exception {
public void getTypeAtPath_when_OneToMany() {
BeanType<Order> orderType = beanType(Order.class);
BeanType<?> detailsType = orderType.getBeanTypeAtPath("details");
assertThat(detailsType.getBeanType()).isEqualTo(OrderDetail.class);
}
@Test
public void getTypeAtPath_when_nested() throws Exception {
public void getTypeAtPath_when_nested() {
BeanType<Order> orderType = beanType(Order.class);
BeanType<?> productType = orderType.getBeanTypeAtPath("details.product");
assertThat(productType.getBeanType()).isEqualTo(Product.class);
}
@Test(expected = RuntimeException.class)
public void getTypeAtPath_when_simpleType() throws Exception {
public void getTypeAtPath_when_simpleType() {
beanType(Order.class).getBeanTypeAtPath("status");
}
@Test
public void createBean() throws Exception {
public void createBean() {
assertThat(beanType(Order.class).createBean()).isNotNull();
}
@Test
public void property() throws Exception {
public void property() {
Order order = new Order();
order.setStatus(Order.Status.APPROVED);
@@ -78,13 +80,13 @@ public class BeanTypeTest {
}
@Test
public void getBaseTable() throws Exception {
public void getBaseTable() {
assertThat(beanType(Order.class).getBaseTable()).isEqualTo("o_order");
}
@Test
public void beanId_and_getBeanId() throws Exception {
public void beanId_and_getBeanId() {
Order order = new Order();
order.setId(42);
@@ -97,7 +99,7 @@ public class BeanTypeTest {
}
@Test
public void setBeanId() throws Exception {
public void setBeanId() {
Order order = new Order();
beanType(Order.class).setBeanId(order, 42);
@@ -106,7 +108,7 @@ public class BeanTypeTest {
}
@Test
public void isDocStoreIndex() throws Exception {
public void isDocStoreIndex() {
assertThat(beanType(Order.class).isDocStoreMapped()).isFalse();
assertThat(beanType(Person.class).isDocStoreMapped()).isFalse();
@@ -116,7 +118,7 @@ public class BeanTypeTest {
}
@Test
public void docStore_getEmbedded() throws Exception {
public void docStore_getEmbedded() {
BeanDocType<Order> orderDocType = beanType(Order.class).docStore();
FetchPath customer = orderDocType.getEmbedded("customer");
@@ -125,7 +127,7 @@ public class BeanTypeTest {
}
@Test
public void docStore_getEmbeddedManyRoot() throws Exception {
public void docStore_getEmbeddedManyRoot() {
BeanDocType<Order> orderDocType = beanType(Order.class).docStore();
@@ -139,28 +141,28 @@ public class BeanTypeTest {
}
@Test
public void getDocStoreQueueId() throws Exception {
public void getDocStoreQueueId() {
assertThat(beanType(Order.class).getDocStoreQueueId()).isEqualTo("order");
assertThat(beanType(Customer.class).getDocStoreQueueId()).isEqualTo("customer");
}
@Test
public void getDocStoreIndexType() throws Exception {
public void getDocStoreIndexType() {
assertThat(beanType(Order.class).docStore().getIndexType()).isEqualTo("order");
assertThat(beanType(Customer.class).docStore().getIndexType()).isEqualTo("customer");
}
@Test
public void getDocStoreIndexName() throws Exception {
public void getDocStoreIndexName() {
assertThat(beanType(Order.class).docStore().getIndexType()).isEqualTo("order");
assertThat(beanType(Customer.class).docStore().getIndexType()).isEqualTo("customer");
}
@Test
public void docStoreNested() throws Exception {
public void docStoreNested() {
FetchPath parse = PathProperties.parse("id,name");
@@ -169,9 +171,9 @@ public class BeanTypeTest {
}
@Test
public void docStoreApplyPath() throws Exception {
public void docStoreApplyPath() {
SpiQuery<Order> orderQuery = (SpiQuery<Order>) server.find(Order.class);
SpiQuery<Order> orderQuery = (SpiQuery<Order>) db.find(Order.class);
beanType(Order.class).docStore().applyPath(orderQuery);
OrmQueryDetail detail = orderQuery.getDetail();
@@ -228,13 +230,13 @@ public class BeanTypeTest {
@Test
public void addInheritanceWhere_when_leaf() {
Query<Vehicle> query = server.find(Vehicle.class);
Query<Vehicle> query = db.find(Vehicle.class);
beanType(Car.class).addInheritanceWhere(query);
}
@Test
public void addInheritanceWhere_when_root() {
Query<Vehicle> query = server.find(Vehicle.class);
Query<Vehicle> query = db.find(Vehicle.class);
beanType(Vehicle.class).addInheritanceWhere(query);
}
@@ -1,14 +1,13 @@
package io.ebean.text.json;
import io.ebean.Ebean;
import io.ebean.EbeanServer;
import com.fasterxml.jackson.core.JsonGenerator;
import io.ebean.DB;
import io.ebean.text.PathProperties;
import org.junit.Test;
import org.tests.model.basic.Contact;
import org.tests.model.basic.Customer;
import org.tests.model.basic.Order;
import org.tests.model.basic.ResetBasicData;
import com.fasterxml.jackson.core.JsonGenerator;
import org.junit.Test;
import java.io.StringReader;
import java.io.StringWriter;
@@ -16,16 +15,18 @@ import java.util.List;
import java.util.Map;
import static org.assertj.core.api.StrictAssertions.assertThat;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class JsonContextTest {
@Test
public void testIsSupportedType() throws Exception {
public void testIsSupportedType() {
EbeanServer server = Ebean.getDefaultServer();
JsonContext json = server.json();
JsonContext json = DB.json();
assertTrue(json.isSupportedType(Customer.class));
assertFalse(json.isSupportedType(System.class));
}
@@ -35,14 +36,14 @@ public class JsonContextTest {
ResetBasicData.reset();
List<Order> orders = Ebean.find(Order.class)
List<Order> orders = DB.find(Order.class)
.fetch("customer", "id, name")
.where().eq("customer.id", 1)
.findList();
String json = Ebean.json().toJson(orders);
String json = DB.json().toJson(orders);
List<Order> orders1 = Ebean.json().toList(Order.class, json);
List<Order> orders1 = DB.json().toList(Order.class, json);
Customer customer = null;
for (Order order : orders1) {
@@ -60,16 +61,16 @@ public class JsonContextTest {
ResetBasicData.reset();
List<Order> orders = Ebean.find(Order.class)
List<Order> orders = DB.find(Order.class)
.select("status")
.fetch("customer", "id, name")
.findList();
String json = Ebean.json().toJson(orders);
String json = DB.json().toJson(orders);
JsonReadOptions options = new JsonReadOptions().setEnableLazyLoading(true);
List<Order> orders1 = Ebean.json().toList(Order.class, json, options);
List<Order> orders1 = DB.json().toList(Order.class, json, options);
for (Order order : orders1) {
Customer customer = order.getCustomer();
@@ -81,11 +82,9 @@ public class JsonContextTest {
}
@Test
public void test_toObject() throws Exception {
public void test_toObject() {
EbeanServer server = Ebean.getDefaultServer();
JsonContext json = server.json();
JsonContext json = DB.getDefault().json();
Customer customer = new Customer();
customer.setId(1);
@@ -111,7 +110,7 @@ public class JsonContextTest {
String jsonWithUnknown = "{\"id\":42,\"unknownProp\":\"foo\",\"name\":\"rob\",\"version\":1}";
Customer customer = Ebean.json().toBean(Customer.class, jsonWithUnknown);
Customer customer = DB.json().toBean(Customer.class, jsonWithUnknown);
assertEquals(Integer.valueOf(42), customer.getId());
assertEquals("rob", customer.getName());
}
@@ -139,7 +138,7 @@ public class JsonContextTest {
options.addRootVisitor(custReadVisitor);
Customer customer = Ebean.json().toBean(Customer.class, jsonWithUnknown, options);
Customer customer = DB.json().toBean(Customer.class, jsonWithUnknown, options);
assertEquals(Integer.valueOf(42), customer.getId());
assertEquals("rob", customer.getName());
@@ -160,7 +159,7 @@ public class JsonContextTest {
JsonReadOptions options = new JsonReadOptions();
options.addRootVisitor(custReadVisitor);
Customer customer = Ebean.json().toBean(Customer.class, someJsonAllKnown, options);
Customer customer = DB.json().toBean(Customer.class, someJsonAllKnown, options);
assertEquals(Integer.valueOf(42), customer.getId());
assertEquals("rob", customer.getName());
@@ -171,10 +170,8 @@ public class JsonContextTest {
@Test
public void testCreateGenerator() throws Exception {
EbeanServer server = Ebean.getDefaultServer();
StringWriter writer = new StringWriter();
JsonContext json = server.json();
JsonContext json = DB.json();
JsonGenerator generator = json.createGenerator(writer);
Customer customer = new Customer();
@@ -198,10 +195,8 @@ public class JsonContextTest {
@Test
public void testCreateGenerator_writeRaw() throws Exception {
EbeanServer server = Ebean.getDefaultServer();
StringWriter writer = new StringWriter();
JsonContext json = server.json();
JsonContext json = DB.json();
JsonGenerator generator = json.createGenerator(writer);
// test that we can write anything via writeRaw()
@@ -2,14 +2,14 @@ package io.ebeaninternal.dbmigration.model.build;
import io.ebean.BaseTestCase;
import io.ebean.Ebean;
import io.ebean.DB;
import io.ebean.config.DbConstraintNaming;
import io.ebeaninternal.api.SpiEbeanServer;
import io.ebeaninternal.dbmigration.ddlgeneration.platform.DefaultConstraintMaxLength;
import io.ebeaninternal.dbmigration.model.MColumn;
import io.ebeaninternal.dbmigration.model.MTable;
import io.ebeaninternal.dbmigration.model.ModelContainer;
import io.ebeaninternal.dbmigration.model.visitor.VisitAllUsing;
import io.ebeaninternal.api.SpiEbeanServer;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -19,7 +19,7 @@ public class ModelBuildBeanVisitorTest extends BaseTestCase {
@Test
public void test() {
SpiEbeanServer defaultServer = (SpiEbeanServer) Ebean.getDefaultServer();
SpiEbeanServer defaultServer = (SpiEbeanServer) DB.getDefault();
ModelContainer model = new ModelContainer();
@@ -1,28 +1,27 @@
package io.ebeaninternal.server.transaction;
import io.ebean.Ebean;
import io.ebean.DB;
import io.ebean.Transaction;
import io.ebean.cache.ServerCache;
import io.ebean.cache.ServerCacheManager;
import org.junit.Test;
import org.tests.model.basic.Contact;
import org.tests.model.basic.Customer;
import org.tests.model.basic.EBasic;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class JdbcTransactionTest {
@Test
public void isSkipCache() throws Exception {
public void isSkipCache() {
Transaction transaction = Ebean.beginTransaction();
try {
try (Transaction transaction = DB.beginTransaction()) {
// implicitly skip false due to query only at this point
assertThat(transaction.isSkipCache()).isFalse();
EBasic basic = new EBasic("b1");
Ebean.save(basic);
DB.save(basic);
// implicitly skip true due to save
assertThat(transaction.isSkipCache()).isTrue();
@@ -35,42 +34,35 @@ public class JdbcTransactionTest {
transaction.setSkipCache(true);
assertThat(transaction.isSkipCache()).isTrue();
} finally {
transaction.end();
}
}
@Test
public void skipCacheAfterSave() throws Exception {
public void skipCacheAfterSave() {
ServerCacheManager cacheManager = Ebean.getDefaultServer().getServerCacheManager();
ServerCacheManager cacheManager = DB.getDefault().getServerCacheManager();
ServerCache customerBeanCache = cacheManager.getBeanCache(Customer.class);
ServerCache contactNatKeyCache = cacheManager.getNaturalKeyCache(Contact.class);
Transaction transaction = Ebean.beginTransaction();
try {
try (Transaction transaction = DB.beginTransaction()) {
customerBeanCache.getStatistics(true);
contactNatKeyCache.getStatistics(true);
Customer.find.byId(19898989);
Ebean.find(Contact.class).where().eq("email", "junk@foo.com").findOne();
DB.find(Contact.class).where().eq("email", "junk@foo.com").findOne();
assertThat(customerBeanCache.getStatistics(true).getMissCount()).isEqualTo(1);
assertThat(contactNatKeyCache.getStatistics(true).getMissCount()).isEqualTo(1);
EBasic basic = new EBasic("b1");
Ebean.save(basic);
DB.save(basic);
// these don't hit L2 cache due to the save of b1
Customer.find.byId(29898989);
Ebean.find(Contact.class).where().eq("email", "junk2@foo.com").findOne();
DB.find(Contact.class).where().eq("email", "junk2@foo.com").findOne();
assertThat(customerBeanCache.getStatistics(true).getMissCount()).isEqualTo(0);
assertThat(contactNatKeyCache.getStatistics(true).getMissCount()).isEqualTo(0);
} finally {
transaction.end();
}
}