Compare commits

...
Author SHA1 Message Date
rob bygrave fbc2d70967 [maven-release-plugin] prepare release ebean-11.36.1 2019-03-12 14:53:09 +13:00
rob bygrave 276e865f72 #1647 - Change ServerConfig.updateAllPropertiesInBatch to default to false 2019-03-12 14:49:00 +13:00
rob bygrave 9ded3890d7 #1649 - ENH: Add optional length() attribute to @DbEnumValue 2019-03-12 14:31:44 +13:00
rob bygrave bfeb0cd667 No effective change - update to using "Database" and DB 2019-03-12 14:29:28 +13:00
rob bygrave 119049b696 Javadoc update using "Database" vs "EbeanServer" 2019-03-07 16:53:13 +13:00
rob bygrave 33ff113585 #1648 - Change BeanFinder and BeanRepository to use Database rather than EbeanServer 2019-03-07 16:51:33 +13:00
rob bygrave 17e0953cad Javadoc update - reduce generated packages 2019-03-07 16:26:05 +13:00
rob bygrave e3ca5d2419 Javadoc update using "DB" and hide DB constructor 2019-03-07 12:01:05 +13:00
rob bygrave a5f435dbcf Javadoc update using "DB" 2019-03-07 11:25:34 +13:00
rob bygrave aa1e021501 Javadoc update using "DB" 2019-03-07 11:10:58 +13:00
rob bygrave 7ea6f16207 Javadoc update using "DB" vs "Ebean" 2019-03-07 10:56:56 +13:00
rob bygrave 197852857d #1646 - Ensure that java.sql.Array.free() is called 2019-03-07 09:25:48 +13:00
rob bygrave e7e6e00473 No effective change - Finder javadoc to use "Database" 2019-03-07 09:08:34 +13:00
rob bygrave 933c791d33 No effective change - Finder javadoc to use "Database" 2019-03-06 23:13:24 +13:00
rob bygrave 043c523c2a [maven-release-plugin] prepare for next development iteration 2019-03-05 23:06:29 +13:00
rob bygrave 82247fd4e4 [maven-release-plugin] prepare release ebean-11.35.3 2019-03-05 23:06:14 +13:00
rob bygrave 27f86548a6 #1645 - ENH: Add expression rawOrEmpty() ... as a convenience for conditionally added a raw expression 2019-03-05 23:03:22 +13:00
rob bygrave 7e8424328f [maven-release-plugin] prepare for next development iteration 2019-03-05 22:26:35 +13:00
rob bygrave 923828ce87 [maven-release-plugin] prepare release ebean-11.35.2 2019-03-05 22:26:19 +13:00
rob bygrave e195f20981 #1645 - ENH: Add expression rawOrEmpty() ... as a convenience for conditionally added a raw expression 2019-03-05 22:13:38 +13:00
rob bygrave 86d0216159 #1644 - ENH: Improve batch flush when multiple "top level" (unrelated) types are persisted 2019-03-04 12:42:08 +13:00
rob bygrave a4698ea1b6 #1643 - ENH: Add expression inOrEmpty() ... as a convenience for conditionally added a IN expression 2019-03-01 18:24:00 +13:00
rob bygrave 888384f7db No effective change (change to DB from Ebean for TestSubQuery) 2019-03-01 18:12:36 +13:00
rob bygrave 817c946eeb [maven-release-plugin] prepare for next development iteration 2019-02-24 16:20:36 +13:00
rob bygrave 1749c2cb4c [maven-release-plugin] prepare release ebean-11.35.1 2019-02-24 16:20:21 +13:00
rob bygrave 3afd3c4530 #1640 Additionally add expression eq and in support for Inet and Postgres any
Bump ebean-types to 1.3 with of() helper methods
2019-02-24 16:18:49 +13:00
rob bygrave e5f98f1b7a #1640 Additionally add expression eq and in support for Inet and Postgres any 2019-02-24 15:29:07 +13:00
rob bygrave 2e496c9e1e Bump pom to 11.35.1-SNAPSHOT 2019-02-21 22:15:49 +13:00
Rob BygraveandGitHub 5975694538 #1640 - For Postgres support mapping InetAddress to INET db column (#1641)
* #1640 - For Postgres support mapping InetAddress to INET db column

* #1640 - For Postgres support mapping InetAddress to INET db column

Support for Inet and Cdir types + offlineMigrationGeneration + PlatformConfig.databaseInetAddressVarchar for turning off InetAddress mapping on Postgres
2019-02-21 22:14:21 +13:00
rob bygrave 03a42f7f6e No effective change - update test DefaultProfileHandlerTest to output profiling files to target 2019-02-21 09:37:14 +13:00
rob bygrave 84f1e05eb4 [maven-release-plugin] prepare for next development iteration 2019-02-18 10:58:21 +13:00
rob bygrave da20ced1ed [maven-release-plugin] prepare release ebean-11.34.3 2019-02-18 10:58:08 +13:00
rob bygrave 1f1a6e2c04 #1642 - Bump to ebean-datasource 4.5.1 with offline/online support 2019-02-18 10:50:34 +13:00
Roland PramlandRob Bygrave 6b83800a83 FIX: Proper sort of migration versions (possible regression due #1577) (#1639) 2019-02-17 17:40:07 +13:00
rob bygrave c344551e4d [maven-release-plugin] prepare for next development iteration 2019-02-13 11:57:09 +13:00
rob bygrave 6b4aff7191 [maven-release-plugin] prepare release ebean-11.34.2 2019-02-13 11:56:55 +13:00
Roland PramlandRob Bygrave fc7fae35c9 FIX: When saving multiple m2m beans, only last m2m wins (Regression due #1630) (#1638)
* provide test case, that shows problem on multiple-m2m

* FIX: When saving multiple m2m beans, only last m2m wins (Regression due #1630)
2019-02-12 09:31:04 +13:00
rob bygrave 7929d8c0b8 Fix test data ordering 2019-02-11 23:17:54 +13:00
rob bygrave 058766dd92 No effective change - adjust test to use DB and try with resources 2019-02-11 23:13:57 +13:00
rob bygrave 4fdb8a77b4 Fix test data 2019-02-11 23:08:50 +13:00
Manuel PoloandRob Bygrave 56be1fc047 Fixed missing EBEAN_PROPS_FILE loading (#1635) 2019-02-11 23:02:10 +13:00
rob bygrave 192a946cf6 #1634 ENH: Add convenience expressions "equal to or null" eqOrNull() 2019-02-11 22:59:47 +13:00
rob bygrave aa7b15fd6e #1637 - build on jdk11 2019-02-11 22:48:10 +13:00
Roland PramlandRob Bygrave cb74ef01e0 build on jdk11 (#1637) 2019-02-11 22:42:05 +13:00
rob bygrave 829dfcb013 #1634 - ENH: Add convenience expressions "greater than or null" gtOrNull(), ltOrNull() and inRangeWith() 2019-02-09 00:30:55 +13:00
rob bygrave 25b6d2a5a0 [maven-release-plugin] prepare for next development iteration 2019-02-07 23:43:13 +13:00
rob bygrave 14fbc3a955 [maven-release-plugin] prepare release ebean-11.34.1 2019-02-07 23:42:57 +13:00
rob bygrave e41da2f995 #1632 - ENH: Add bind parameter expansion for SqlUpdate
Fix test with bind type.
2019-02-07 23:35:44 +13:00
rob bygrave ea60e42a4d #1633 - ENH: Add bind parameter expansion for raw() expressions 2019-02-07 23:29:42 +13:00
rob bygrave efce6b57e1 #1632 - ENH: Add bind parameter expansion for SqlUpdate 2019-02-07 23:19:00 +13:00
rob bygrave 988e4c7386 WIP Bind parameter expansion 2019-02-07 21:10:57 +13:00
rob bygrave 9e1d7ab722 #1631 - Change logging for SqlUpdate ... such that it is more consistent with other SQL logging wrt JDBC batch 2019-02-07 17:20:49 +13:00
rob bygrave 0c03a8b925 #1630 - ENH: Improve jdbc batch use when persisting ManyToMany intersection changes 2019-02-05 17:35:58 +13:00
rob bygrave 37a66f1ee2 Playing around with SqlUpdate and bind expansion for ?1 etc 2019-02-04 14:24:47 +13:00
rob bygrave a02673359d No effective change - tidy BindParams 2019-02-04 12:34:02 +13:00
rob bygrave f9d13cbba7 Merge branch 'master' of github.com:ebean-orm/ebean 2019-02-04 11:55:04 +13:00
rob bygrave f787483e30 #1629 - ENH: Add sqlQuery(sql) and sqlUpdate(sql) ... as alias for createSqlQuery(sql) and createSqlUpdate(sql) 2019-02-04 11:54:45 +13:00
rob bygrave 9e33f36808 #1629 - ENH: Add sqlQuery(sql) and sqlUpdate(sql) ... as alias for createSqlQuery(sql) and createSqlUpdate(sql) 2019-02-04 11:14:54 +13:00
Roland PramlandRob Bygrave 6a7e6caa66 Test fixes (#1628)
* FIX: mysql index sizes

* FIX: osolete whitespace in sqlserver tests

* Updated mssql-jdbc, this fixes problems in the batch insert (https://github.com/Microsoft/mssql-jdbc/pull/912)

* fix tablename  (reserved word in mariadb)

* ignored failing tests for sqlserver
2019-02-04 09:20:09 +13:00
rob bygrave 5a4a0e3886 Bump version to 11.34.1-SNAPSHOT 2019-02-03 22:39:23 +13:00
rob bygrave c3f586c461 Merge branch 'feature/1624-Database' 2019-02-03 22:21:36 +13:00
rob bygrave 99f7243d6c #1627 - Bump ebean-datasource to 4.3.4 2019-02-03 22:14:25 +13:00
rob bygrave 7026c00290 [maven-release-plugin] prepare for next development iteration 2019-02-02 22:29:02 +13:00
rob bygrave b751823abb #1624 - ENH: Create io.ebean.DB as alias for Ebean and io.ebean.Database as alias for EbeanServer
Adjust Model and Finder to use DB and Database
2019-02-01 23:20:53 +13:00
rob bygrave f3cb7e2cfd #1624 - ENH: Create io.ebean.DB as alias for Ebean and io.ebean.Database as alias for EbeanServer 2019-02-01 22:53:41 +13:00
156 changed files with 5925 additions and 2884 deletions
+30 -8
View File
@@ -9,7 +9,7 @@
<groupId>io.ebean</groupId>
<artifactId>ebean</artifactId>
<version>11.33.3</version>
<version>11.36.1</version>
<packaging>jar</packaging>
<name>ebean</name>
@@ -22,7 +22,7 @@
<scm>
<developerConnection>scm:git:git@github.com:ebean-orm/ebean.git</developerConnection>
<tag>ebean-11.33.3</tag>
<tag>ebean-11.36.1</tag>
</scm>
<profiles>
@@ -117,13 +117,19 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-annotation</artifactId>
<version>4.5</version>
<version>4.6</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-types</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-datasource</artifactId>
<version>4.3.3</version>
<version>4.5.1</version>
</dependency>
<dependency>
@@ -188,6 +194,21 @@
<scope>provided</scope>
</dependency>
<!-- Provided scope to compile with java 11 -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.4.0-b180830.0438</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
<scope>provided</scope>
</dependency>
<!-- Provided scope for Postgres JSON/JSONB support -->
<dependency>
<groupId>org.postgresql</groupId>
@@ -222,7 +243,7 @@
<dependency>
<groupId>org.avaje</groupId>
<artifactId>avaje-agentloader</artifactId>
<version>2.1.2</version>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
@@ -259,7 +280,7 @@
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.4.0.jre8</version>
<version>7.2.0.jre8</version>
<scope>test</scope>
</dependency>
@@ -327,9 +348,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<version>2.22.1</version>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
<trimStackTrace>false</trimStackTrace>
<failIfNoTests>false</failIfNoTests>
<includes>
<include>**/Test*.java</include>
@@ -371,7 +393,7 @@
<overview>src/main/java/io/ebean/overview.html</overview>
<source>1.8</source>
<doclet>org.avaje.doclet.PygmentsDoclet</doclet>
<excludePackageNames>io.ebeaninternal.*:com.avaje.ebean.util</excludePackageNames>
<excludePackageNames>io.ebeaninternal.*:io.ebeanservice:io.ebean.common:io.ebean.bean:io.ebean.service:io.ebean.metric:io.ebean.util:io.ebean.config.properties:io.ebean.config.dbplatform*</excludePackageNames>
<docletArtifact>
<groupId>org.avaje</groupId>
<artifactId>pygments-doclet</artifactId>
+16 -21
View File
@@ -15,8 +15,8 @@ import java.util.Optional;
* public class CustomerFinder extends BeanFinder<Long,Customer> {
*
* @Inject
* public CustomerFinder(EbeanServer server) {
* super(Customer.class, server);
* public CustomerFinder(Database database) {
* super(Customer.class, database);
* }
*
* // ... add customer specific finders
@@ -29,25 +29,25 @@ import java.util.Optional;
*/
public abstract class BeanFinder<I,T> {
protected final EbeanServer server;
protected final Database server;
protected final Class<T> type;
/**
* Create with the given bean type and EbeanServer instance.
* Create with the given bean type and Database instance.
*
* @param type The bean type
* @param server The EbeanServer instance typically created via Spring factory or equivalent.
* @param server The Database instance typically created via Spring factory or equivalent.
*/
protected BeanFinder(Class<T> type, EbeanServer server) {
protected BeanFinder(Class<T> type, Database server) {
this.type = type;
this.server = server;
}
/**
* Return the EbeanServer to use.
* Return the Database to use.
*/
public EbeanServer db() {
public Database db() {
return server;
}
@@ -66,21 +66,20 @@ public abstract class BeanFinder<I,T> {
}
/**
* Return typically a different EbeanServer to the default.
* Return typically a different Database to the default.
* <p>
* This is equivalent to {@link Ebean#getServer(String)}
* This is equivalent to {@link DB#byName(String)}
*
* @param server The name of the EbeanServer. If this is null then the default EbeanServer is
* returned.
* @param server The name of the Database. If this is null then the default Database is returned.
*/
public EbeanServer db(String server) {
return Ebean.getServer(server);
public Database db(String server) {
return DB.byName(server);
}
/**
* Creates an entity reference for this ID.
* <p>
* Equivalent to {@link EbeanServer#getReference(Class, Object)}
* Equivalent to {@link Database#getReference(Class, Object)}
*/
@Nonnull
public T ref(I id) {
@@ -89,8 +88,6 @@ public abstract class BeanFinder<I,T> {
/**
* Retrieves an entity by ID.
* <p>
* Equivalent to {@link EbeanServer#find(Class, Object)}
*/
@Nullable
public T findById(I id) {
@@ -107,8 +104,6 @@ public abstract class BeanFinder<I,T> {
/**
* Delete a bean by Id.
* <p>
* Equivalent to {@link EbeanServer#delete(Class, Object)}
*/
public void deleteById(I id) {
db().delete(type, id);
@@ -138,7 +133,7 @@ public abstract class BeanFinder<I,T> {
* }</pre>
*
* <p>
* Equivalent to {@link EbeanServer#update(Class)}
* Equivalent to {@link Database#update(Class)}
*/
protected UpdateQuery<T> updateQuery() {
return db().update(type);
@@ -147,7 +142,7 @@ public abstract class BeanFinder<I,T> {
/**
* Creates a query.
* <p>
* Equivalent to {@link EbeanServer#find(Class)}
* Equivalent to {@link Database#find(Class)}
*/
protected Query<T> query() {
return db().find(type);
+14 -14
View File
@@ -13,7 +13,7 @@ import java.util.Collection;
* public class CustomerRepository extends BeanRepository<Long,Customer> {
*
* @Inject
* public CustomerRepository(EbeanServer server) {
* public CustomerRepository(Database server) {
* super(Customer.class, server);
* }
*
@@ -34,23 +34,23 @@ import java.util.Collection;
public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
/**
* Create with the given bean type and EbeanServer instance.
* Create with the given bean type and Database instance.
* <p>
* Typically users would extend BeanRepository rather than BeanFinder.
* </p>
* <pre>{@code
*
* @Inject
* public CustomerRepository(EbeanServer server) {
* public CustomerRepository(Database server) {
* super(Customer.class, server);
* }
*
* }</pre>
*
* @param type The bean type
* @param server The EbeanServer instance typically created via Spring factory or equivalent
* @param server The Database instance typically created via Spring factory or equivalent
*/
protected BeanRepository(Class<T> type, EbeanServer server) {
protected BeanRepository(Class<T> type, Database server) {
super(type, server);
}
@@ -75,7 +75,7 @@ public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
*
* }</pre>
*
* @see EbeanServer#markAsDirty(Object)
* @see Database#markAsDirty(Object)
*/
public void markAsDirty(T bean) {
db().markAsDirty(bean);
@@ -111,7 +111,7 @@ public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
* Ebean will detect if this is a new bean or a previously fetched bean and perform either an
* insert or an update based on that.
*
* @see EbeanServer#save(Object)
* @see Database#save(Object)
*/
public void save(T bean) {
db().save(bean);
@@ -127,7 +127,7 @@ public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
/**
* Update this entity.
*
* @see EbeanServer#update(Object)
* @see Database#update(Object)
*/
public void update(T bean) {
db().update(bean);
@@ -136,7 +136,7 @@ public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
/**
* Insert this entity.
*
* @see EbeanServer#insert(Object)
* @see Database#insert(Object)
*/
public void insert(T bean) {
db().insert(bean);
@@ -157,7 +157,7 @@ public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
* deleted. Note that, if JDBC batch mode is used then this always returns true.
* </p>
*
* @see EbeanServer#delete(Object)
* @see Database#delete(Object)
*/
public boolean delete(T bean) {
return db().delete(bean);
@@ -177,7 +177,7 @@ public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
* want to perform a hard/permanent delete.
* </p>
*
* @see EbeanServer#deletePermanent(Object)
* @see Database#deletePermanent(Object)
*/
public boolean deletePermanent(T bean) {
return db().deletePermanent(bean);
@@ -189,7 +189,7 @@ public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
* Ebean will detect if this is a new bean or a previously fetched bean and perform either an
* insert or an update based on that.
*
* @see EbeanServer#merge(Object)
* @see Database#merge(Object)
*/
public void merge(T bean) {
db().merge(bean);
@@ -201,7 +201,7 @@ public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
* Ebean will detect if this is a new bean or a previously fetched bean and perform either an
* insert or an update based on that.
*
* @see EbeanServer#merge(Object, MergeOptions)
* @see Database#merge(Object, MergeOptions)
*/
public void merge(T bean, MergeOptions options) {
db().merge(bean, options);
@@ -210,7 +210,7 @@ public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
/**
* Refreshes this entity from the database.
*
* @see EbeanServer#refresh(Object)
* @see Database#refresh(Object)
*/
public void refresh(T bean) {
db().refresh(bean);
+3 -4
View File
@@ -1,10 +1,9 @@
package io.ebean;
import javax.annotation.Nullable;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Provides access to the internal state of an entity bean.
*/
@@ -58,7 +57,7 @@ public interface BeanState {
*
* // set loaded state on the email property to false so that
* // the email property is not included in a stateless update
* Ebean.getBeanState(user).setPropertyLoaded("email", false);
* DB.getBeanState(user).setPropertyLoaded("email", false);
*
* user.update();
*
@@ -103,7 +102,7 @@ public interface BeanState {
/**
* Advanced - Used to programmatically build a partially or fully loaded
* entity bean. First create an entity bean via
* {@link EbeanServer#createEntityBean(Class)}, then populate its properties
* {@link Database#createEntityBean(Class)}, then populate its properties
* and then call this method specifying which properties where loaded or null
* for a fully loaded entity bean.
*/
+16 -18
View File
@@ -17,11 +17,11 @@ import java.sql.SQLException;
*
* String sql = "{call sp_order_mod(?,?)}";
*
* CallableSql cs = Ebean.createCallableSql(sql);
* CallableSql cs = DB.createCallableSql(sql);
* cs.setParameter(1, "turbo");
* cs.registerOut(2, Types.INTEGER);
*
* Ebean.execute(cs);
* DB.execute(cs);
*
* // read the out parameter
* Integer returnValue = (Integer) cs.getObject(2);
@@ -38,7 +38,7 @@ import java.sql.SQLException;
*
* String sql = "{call sp_insert_order(?,?)}";
*
* CallableSql cs = Ebean.createCallableSql(sql);
* CallableSql cs = DB.createCallableSql(sql);
*
* // Inform Ebean this stored procedure inserts into the
* // oe_order table and inserts + updates the oe_order_detail table.
@@ -46,35 +46,33 @@ import java.sql.SQLException;
* cs.addModification("oe_order", true, false, false);
* cs.addModification("oe_order_detail", true, true, false);
*
* Transaction t = Ebean.startTransaction();
*
* // execute using JDBC batching 10 statements at a time
* t.setBatchMode(true);
* t.setBatchSize(10);
* try {
* try (Transaction t = DB.beginTransaction()) {
*
* // execute using JDBC batching 10 statements at a time
* t.setBatchMode(true);
* t.setBatchSize(10);
*
* cs.setParameter(1, "Was");
* cs.setParameter(2, "Banana");
* Ebean.execute(cs);
* DB.execute(cs);
*
* cs.setParameter(1, "Here");
* cs.setParameter(2, "Kumera");
* Ebean.execute(cs);
* DB.execute(cs);
*
* cs.setParameter(1, "More");
* cs.setParameter(2, "Apple");
* Ebean.execute(cs);
* DB.execute(cs);
*
* // Ebean.externalModification("oe_order",true,false,false);
* // Ebean.externalModification("oe_order_detail",true,true,false);
* Ebean.commitTransaction();
* // DB.externalModification("oe_order",true,false,false);
* // DB.externalModification("oe_order_detail",true,true,false);
* t.commit();
*
* } finally {
* Ebean.endTransaction();
* }
* }</pre>
*
* @see SqlUpdate
* @see Ebean#execute(CallableSql)
*/
public interface CallableSql {
@@ -173,7 +171,7 @@ public interface CallableSql {
* Add table modification information to the TransactionEvent.
* <p>
* This would be similar to using the
* <code>Ebean.externalModification()</code> method. It may be easier and make
* <code>DB.externalModification()</code> method. It may be easier and make
* more sense to set it here with the CallableSql.
* </p>
* <p>
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 Database instances 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
@@ -30,7 +30,7 @@ import java.util.function.Predicate;
* String sql = "select id, name from customer where name like :name and status_code = :status";
*
* List<CustomerDto> beans =
* Ebean.findDto(CustomerDto.class, sql)
* DB.findDto(CustomerDto.class, sql)
* .setParameter("name", "Acme%")
* .setParameter("status", "ACTIVE")
* .findList();
+17 -104
View File
@@ -24,113 +24,26 @@ import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
/**
* This Ebean object is effectively a singleton that holds a map of registered
* {@link EbeanServer}s. It additionally provides a convenient way to use the
* 'default' EbeanServer.
* Ebean is a registry of {@link Database} by name. Ebean has now been renamed to {@link DB}.
* <p>
* If you are using a Dependency Injection framework such as
* <strong>Spring</strong> or <strong>Guice</strong> you will probably
* <strong>NOT</strong> use this Ebean singleton object. Instead you will
* configure and construct EbeanServer instances using {@link ServerConfig} and
* {@link EbeanServerFactory} and inject those EbeanServer instances into your
* data access objects.
* </p>
* Ebean is effectively this is an alias for {@link DB} which is the new and improved name for Ebean.
* <p>
* In documentation "Ebean singleton" refers to this object.
* </p>
* <ul>
* <li>There is one EbeanServer per Database (javax.sql.DataSource).</li>
* <li>EbeanServers can be 'registered' with the Ebean singleton (put into its
* map). Registered EbeanServer's can later be retrieved via
* {@link #getServer(String)}.</li>
* <li>One EbeanServer can be referred to as the 'default' EbeanServer. For
* convenience, the Ebean singleton (this object) provides methods such as
* {@link #find(Class)} that proxy through to the 'default' EbeanServer. This
* can be useful for applications that use a single database.</li>
* </ul>
* <p>
* For developer convenience Ebean has static methods that proxy through to the
* methods on the <em>'default'</em> EbeanServer. These methods are provided for
* developers who are mostly using a single database. Many developers will be
* able to use the methods on Ebean rather than get a EbeanServer.
* </p>
* <p>
* EbeanServers can be created and used without ever needing or using the Ebean
* singleton. Refer to {@link ServerConfig#setRegister(boolean)}.
* </p>
* <p>
* You can either programmatically create/register EbeanServers via
* {@link EbeanServerFactory} or they can automatically be created and
* registered when you first use the Ebean singleton. When EbeanServers are
* created automatically they are configured using information in the
* ebean.properties file.
* </p>
* <pre>{@code
*
* // fetch shipped orders (and also their customer)
* List<Order> list = Ebean.find(Order.class)
* .fetch("customer")
* .where()
* .eq("status.code", Order.Status.SHIPPED)
* .findList();
*
* // read/use the order list ...
* for (Order order : list) {
* Customer customer = order.getCustomer();
* ...
* }
*
* }</pre>
* <pre>{@code
*
* // fetch order 10, modify and save
* Order order = Ebean.find(Order.class, 10);
*
* OrderStatus shipped = Ebean.getReference(OrderStatus.class,"SHIPPED");
* order.setStatus(shipped);
* order.setShippedDate(shippedDate);
* ...
*
* // implicitly creates a transaction and commits
* Ebean.save(order);
*
* }</pre>
* <p>
* When you have multiple databases and need access to a specific one the
* {@link #getServer(String)} method provides access to the EbeanServer for that
* specific database.
* </p>
* <pre>{@code
*
* // Get access to the Human Resources EbeanServer/Database
* EbeanServer hrDb = Ebean.getServer("hr");
*
* // fetch contact 3 from the HR database
* Contact contact = hrDb.find(Contact.class, 3);
*
* contact.setName("I'm going to change");
* ...
*
* // save the contact back to the HR database
* hrDb.save(contact);
*
* }</pre>
* The preference is to use DB and Database rather than Ebean and EbeanServer.
*/
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.
}
/**
* Manages creation and cache of EbeanServers.
* Manages creation and cache of Databases.
*/
private static final Ebean.ServerManager serverMgr = new Ebean.ServerManager();
/**
* Helper class for managing fast and safe access and creation of
* EbeanServers.
* Helper class for managing fast and safe access and creation of Databases.
*/
private static final class ServerManager {
@@ -147,7 +60,7 @@ public final class Ebean {
private final Object monitor = new Object();
/**
* The 'default' EbeanServer.
* The 'default' Database.
*/
private EbeanServer defaultServer;
@@ -166,20 +79,20 @@ public final class Ebean {
throw e;
} catch (DataSourceConfigurationException e) {
String msg = "Configuration error creating DataSource for the default EbeanServer." +
String msg = "Configuration error creating DataSource for the default Database." +
" This typically means a missing application-test.yaml or missing ebean-test-config dependency." +
" See https://ebean.io/docs/trouble-shooting#datasource";
throw new DataSourceConfigurationException(msg, e);
} catch (Throwable e) {
logger.error("Error trying to create the default EbeanServer", e);
logger.error("Error trying to create the default Database", e);
throw new RuntimeException(e);
}
}
private EbeanServer getDefaultServer() {
if (defaultServer == null) {
String msg = "The default EbeanServer has not been defined?";
String msg = "The default Database has not been defined?";
msg += " This is normally set via the ebean.datasource.default property.";
msg += " Otherwise it should be registered programmatically via registerServer()";
throw new PersistenceException(msg);
@@ -201,7 +114,7 @@ public final class Ebean {
}
/**
* Synchronized read, create and put of EbeanServers.
* Synchronized read, create and put of Databases.
*/
private EbeanServer getWithCreate(String name) {
@@ -240,7 +153,7 @@ public final class Ebean {
}
/**
* Get the EbeanServer for a given DataSource. If name is null this will
* Get the Database for a given DataSource. If name is null this will
* return the 'default' EbeanServer.
* <p>
* This is provided to access EbeanServer for databases other than the
@@ -631,7 +544,8 @@ public final class Ebean {
* Customer customer = new Customer();
* customer.setId(7);
* customer.setName("ModifiedNameNoOCC");
* ebeanServer.update(customer);
*
* DB.update(customer);
*
* }</pre>
*
@@ -1131,10 +1045,9 @@ public final class Ebean {
*
* String sql = "select c.id, c.name from customer c where c.name like ? order by c.name";
*
* Query<Customer> query = ebeanServer.findNative(Customer.class, sql);
* query.setParameter(1, "Rob%");
*
* List<Customer> customers = query.findList();
* List<Customer> customers = DB.findNative(Customer.class, sql)
* .setParameter(1, "Rob%")
* .findList()
*
* }</pre>
*
File diff suppressed because it is too large Load Diff
@@ -22,8 +22,8 @@ package io.ebean;
* example.setName("Rob%");
* example.setNotes("%something%");
*
* List&lt;Customer&gt; list =
* Ebean.find(Customer.class)
* List<Customer> list =
* DB.find(Customer.class)
* .where()
* // pass the bean into the where() clause
* .exampleLike(example)
@@ -46,7 +46,7 @@ package io.ebean;
* .includeZeros();
*
* List<Customer> list =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .where()
* .add(qbe)
* .findList();
+40 -18
View File
@@ -13,27 +13,15 @@ import java.util.Map;
* {@link Query#where()}.
* </p>
* <p>
* This provides a convenient way to create expressions for the 'Default'
* server. It is actually a short cut for using the ExpressionFactory of the
* 'default' EbeanServer.
* This provides a convenient way to create expressions for the default
* database.
* <p>
* See also {@link Ebean#getExpressionFactory()}
* See also {@link DB#getExpressionFactory()}
* </p>
* <p>
* Creates standard common expressions for using in a Query Where or Having
* clause.
* </p>
* <pre>{@code
*
* // Example: Using an Expr.or() method
* Query<Order> query = Ebean.createQuery(Order.class);
* query.where(
* Expr.or(Expr.eq("status", Order.NEW),
* Expr.gt("orderDate", lastWeek));
*
* List<Order> list = query.findList();
* ...
* }</pre>
*
* @see Query#where()
*/
@@ -71,7 +59,6 @@ public class Expr {
* </p>
*/
public static Expression inRange(String propertyName, Object value1, Object value2) {
return Ebean.getExpressionFactory().inRange(propertyName, value1, value2);
}
@@ -79,7 +66,6 @@ public class Expr {
* Between - property between the two given values.
*/
public static Expression between(String propertyName, Object value1, Object value2) {
return Ebean.getExpressionFactory().between(propertyName, value1, value2);
}
@@ -87,7 +73,6 @@ public class Expr {
* Between - value between two given properties.
*/
public static Expression between(String lowProperty, String highProperty, Object value) {
return Ebean.getExpressionFactory().betweenProperties(lowProperty, highProperty, value);
}
@@ -253,6 +238,43 @@ public class Expr {
return Ebean.getExpressionFactory().in(propertyName, values);
}
/**
* In where null or empty values means that no predicate is added to the query.
* <p>
* That is, only add the IN predicate if the values are not null or empty.
* <p>
* Without this we typically need to code an <code>if</code> block to only add
* the IN predicate if the collection is not empty like:
* </p>
*
* <h3>Without inOrEmpty()</h3>
* <pre>{@code
*
* query.where() // add some predicates
* .eq("status", Status.NEW);
*
* if (ids != null && !ids.isEmpty()) {
* query.where().in("customer.id", ids);
* }
*
* query.findList();
*
* }</pre>
*
* <h3>Using inOrEmpty()</h3>
* <pre>{@code
*
* query.where()
* .eq("status", Status.NEW)
* .inOrEmpty("customer.id", ids)
* .findList();
*
* }</pre>
*/
public static Expression inOrEmpty(String propertyName, Collection<?> values) {
return Ebean.getExpressionFactory().inOrEmpty(propertyName, values);
}
/**
* Id Equal to - ID property is equal to the value.
*/
+78 -3
View File
@@ -30,9 +30,9 @@ import java.util.Map;
* Expr.or(Expr.eq("status", Order.Status.NEW),
* Expr.gt("orderDate", lastWeek));
*
* Query<Order> query = Ebean.createQuery(Order.class);
* query.where().add(newOrLastWeek);
* List<Order> list = query.findList();
* List<Order> list = DB.find(Order.class)
* .where().add(newOrLastWeek)
* .findList();
* ...
* }</pre>
*
@@ -122,6 +122,11 @@ public interface ExpressionFactory {
*/
Expression eq(String propertyName, Object value);
/**
* Equal To or Null - property equal to the given value or null.
*/
Expression eqOrNull(String propertyName, Object value);
/**
* Not Equal To - property not equal to the given value.
*/
@@ -157,6 +162,25 @@ public interface ExpressionFactory {
*/
Expression inRange(String propertyName, Object value1, Object value2);
/**
* Value in Range between 2 properties.
*
* <pre>{@code
*
* .startDate.inRangeWith(endDate, now)
*
* // which equates to
* startDate <= now and (endDate > now or endDate is null)
*
* }</pre>
*
* <p>
* This is a convenience expression combining a number of simple expressions.
* The most common use of this could be called "effective dating" where 2 date or
* timestamp columns represent the date range in which
*/
Expression inRangeWith(String lowProperty, String highProperty, Object value);
/**
* Between - property between the two given values.
*/
@@ -167,6 +191,14 @@ public interface ExpressionFactory {
*/
Expression betweenProperties(String lowProperty, String highProperty, Object value);
/**
* Greater Than Or Null - property greater than the given value or null.
* <p>
* A convenient expression combining GT and Is Null. Most often useful for range
* expressions where the top range value is nullable.
*/
Expression gtOrNull(String propertyName, Object value);
/**
* Greater Than - property greater than the given value.
*/
@@ -178,6 +210,14 @@ public interface ExpressionFactory {
*/
Expression ge(String propertyName, Object value);
/**
* Less Than or Null - property less than the given value or null.
* <p>
* A convenient expression combining LT and Is Null. Most often useful for range
* expressions where the bottom range value is nullable.
*/
Expression ltOrNull(String propertyName, Object value);
/**
* Less Than - property less than the given value.
*/
@@ -285,6 +325,41 @@ public interface ExpressionFactory {
*/
Expression in(String propertyName, Collection<?> values);
/**
* In where null or empty values means that no predicate is added to the query.
* <p>
* That is, only add the IN predicate if the values are not null or empty.
* <p>
* Without this we typically need to code an <code>if</code> block to only add
* the IN predicate if the collection is not empty like:
* </p>
*
* <h3>Without inOrEmpty()</h3>
* <pre>{@code
*
* query.where() // add some predicates
* .eq("status", Status.NEW);
*
* if (ids != null && !ids.isEmpty()) {
* query.where().in("customer.id", ids);
* }
*
* query.findList();
*
* }</pre>
*
* <h3>Using inOrEmpty()</h3>
* <pre>{@code
*
* query.where()
* .eq("status", Status.NEW)
* .inOrEmpty("customer.id", ids)
* .findList();
*
* }</pre>
*/
Expression inOrEmpty(String propertyName, Collection<?> values);
/**
* Not In - property has a value in the array of values.
*/
+142 -26
View File
@@ -321,7 +321,7 @@ public interface ExpressionList<T> {
* <pre>{@code
*
* List<String> names =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .select("name")
* .orderBy().asc("name")
* .findSingleAttributeList();
@@ -332,7 +332,7 @@ public interface ExpressionList<T> {
* <pre>{@code
*
* List<String> names =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .setDistinct(true)
* .select("name")
* .where().eq("status", Customer.Status.NEW)
@@ -352,7 +352,7 @@ public interface ExpressionList<T> {
* <pre>{@code
*
* String name =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .select("name")
* .where().eq("id", 42)
* .findSingleAttribute();
@@ -435,7 +435,7 @@ public interface ExpressionList<T> {
* </p>
* <pre>{@code
*
* PagedList<Order> pagedList = Ebean.find(Order.class)
* PagedList<Order> pagedList = DB.find(Order.class)
* .setFirstRow(50)
* .setMaxRows(20)
* .findPagedList();
@@ -502,7 +502,7 @@ public interface ExpressionList<T> {
* <pre>{@code
*
* List<Customer> customers =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .setDistinct(true)
* .select("name") // only select the customer name
* .findList();
@@ -575,7 +575,7 @@ public interface ExpressionList<T> {
*
* List<CountedValue<Order.Status>> orderStatusCount =
*
* Ebean.find(Order.class)
* DB.find(Order.class)
* .select("status")
* .where()
* .gt("orderDate", LocalDate.now().minusMonths(3))
@@ -758,20 +758,6 @@ public interface ExpressionList<T> {
/**
* Add an Expression to the list.
* <p>
* This returns the list so that add() can be chained.
* </p>
* <pre>{@code
*
* Query<Customer> query = Ebean.find(Customer.class);
* query.where()
* .like("name","Rob%")
* .eq("status", Customer.ACTIVE);
*
* List<Customer> list = query.findList();
* ...
*
* }</pre>
*/
ExpressionList<T> add(Expression expr);
@@ -785,6 +771,11 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> eq(String propertyName, Object value);
/**
* Equal To or Null - property is equal to a given value or null.
*/
ExpressionList<T> eqOrNull(String propertyName, Object value);
/**
* Not Equal To - property not equal to the given value.
*/
@@ -802,6 +793,25 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> ine(String propertyName, String value);
/**
* Value in Range between 2 properties.
*
* <pre>{@code
*
* .startDate.inRangeWith(endDate, now)
*
* // which equates to
* startDate <= now and (endDate > now or endDate is null)
*
* }</pre>
*
* <p>
* This is a convenience expression combining a number of simple expressions.
* The most common use of this could be called "effective dating" where 2 date or
* timestamp columns represent the date range in which
*/
ExpressionList<T> inRangeWith(String lowProperty, String highProperty, Object value);
/**
* In Range - property >= value1 and property < value2.
* <p>
@@ -825,6 +835,11 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> gt(String propertyName, Object value);
/**
* Greater Than or Null - property greater than the given value or null.
*/
ExpressionList<T> gtOrNull(String propertyName, Object value);
/**
* Greater Than or Equal to - property greater than or equal to the given
* value.
@@ -836,6 +851,11 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> lt(String propertyName, Object value);
/**
* Less Than or Null - property less than the given value or null.
*/
ExpressionList<T> ltOrNull(String propertyName, Object value);
/**
* Less Than or Equal to - property less than or equal to the given value.
*/
@@ -873,11 +893,10 @@ public interface ExpressionList<T> {
* example.setName("Rob%");
* example.setNotes("%something%");
*
* List<Customer> list = Ebean.find(Customer.class).where()
* // pass the bean into the where() clause
* .exampleLike(example)
* // you can add other expressions to the same query
* .gt("id", 2).findList();
* List<Customer> list =
* DB.find(Customer.class)
* .where().exampleLike(example)
* .findList();
*
* }</pre>
* <p>
@@ -892,7 +911,7 @@ public interface ExpressionList<T> {
* // create a ExampleExpression with more control
* ExampleExpression qbe = new ExampleExpression(example, true, LikeType.EQUAL_TO).includeZeros();
*
* List<Customer> list = Ebean.find(Customer.class).where().add(qbe).findList();
* List<Customer> list = DB.find(Customer.class).where().add(qbe).findList();
*
* }</pre>
*/
@@ -969,6 +988,41 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> in(String propertyName, Collection<?> values);
/**
* In where null or empty values means that no predicate is added to the query.
* <p>
* That is, only add the IN predicate if the values are not null or empty.
* <p>
* Without this we typically need to code an <code>if</code> block to only add
* the IN predicate if the collection is not empty like:
* </p>
*
* <h3>Without inOrEmpty()</h3>
* <pre>{@code
*
* query.where() // add some predicates
* .eq("status", Status.NEW);
*
* if (ids != null && !ids.isEmpty()) {
* query.where().in("customer.id", ids);
* }
*
* query.findList();
*
* }</pre>
*
* <h3>Using inOrEmpty()</h3>
* <pre>{@code
*
* query.where()
* .eq("status", Status.NEW)
* .inOrEmpty("customer.id", ids)
* .findList();
*
* }</pre>
*/
ExpressionList<T> inOrEmpty(String propertyName, Collection<?> values);
/**
* In - using a subQuery.
* <p>
@@ -1213,6 +1267,68 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> raw(String raw);
/**
* Only add the raw expression if the values is not null or empty.
* <p>
* This is a pure convenience expression to make it nicer to deal with the pattern where we use
* raw() expression with a subquery and only want to add the subquery predicate when the collection
* of values is not empty.
* </p>
* <h3>Without inOrEmpty()</h3>
* <pre>{@code
*
* query.where() // add some predicates
* .eq("status", Status.NEW);
*
* // common pattern - we can use rawOrEmpty() instead
* if (orderIds != null && !orderIds.isEmpty()) {
* query.where().raw("t0.customer_id in (select o.customer_id from orders o where o.id in (?1))", orderIds);
* }
*
* query.findList();
*
* }</pre>
*
* <h3>Using rawOrEmpty()</h3>
* Note that in the example below we use the <code>?1</code> bind parameter to get "parameter expansion"
* for each element in the collection.
*
* <pre>{@code
*
* query.where()
* .eq("status", Status.NEW)
* // only add the expression if orderIds is not empty
* .rawOrEmpty("t0.customer_id in (select o.customer_id from orders o where o.id in (?1))", orderIds);
* .findList();
*
* }</pre>
*
* <h3>Postgres ANY</h3>
* With Postgres we would often use the SQL <code>ANY</code> expression and array parameter binding
* rather than <code>IN</code>.
*
* <pre>{@code
*
* query.where()
* .eq("status", Status.NEW)
* .rawOrEmpty("t0.customer_id in (select o.customer_id from orders o where o.id = any(?))", orderIds);
* .findList();
*
* }</pre>
* <p>
* Note that we need to cast the Postgres array for UUID types like:
* </p>
* <pre>{@code
*
* " ... = any(?::uuid[])"
*
* }</pre>
*
* @param raw The raw expression that is typically a subquery
* @param values The values which is typically a list or set of id values.
*/
ExpressionList<T> rawOrEmpty(String raw, Collection<?> values);
/**
* Add a match expression.
*
+10 -12
View File
@@ -15,7 +15,7 @@ import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* The extended API for EbeanServer.
* The extended API for Database.
* <p>
* This provides the finder methods that take an explicit transaction rather than obtaining
* the transaction from the usual mechanism (which is ThreadLocal based).
@@ -26,7 +26,7 @@ import java.util.function.Predicate;
* the transaction to use.
* </p>
* <p>
* Note that in all cases the transaction supplied can be null and in this case the EbeanServer
* Note that in all cases the transaction supplied can be null and in this case the Database
* will use the normal mechanism to obtain the transaction to use.
* </p>
*/
@@ -121,7 +121,7 @@ public interface ExtendedServer {
* <p>
* <pre>{@code
*
* ebeanServer.find(Order.class)
* DB.find(Order.class)
* .where().eq("status", Order.Status.NEW)
* .order().asc("id")
* .findEach((Order order) -> {
@@ -155,7 +155,7 @@ public interface ExtendedServer {
* <p>
* <pre>{@code
*
* ebeanServer.find(Order.class)
* DB.find(Order.class)
* .where().eq("status", Order.Status.NEW)
* .order().asc("id")
* .findEachWhile((Order order) -> {
@@ -194,8 +194,7 @@ public interface ExtendedServer {
* <p>
* <pre>{@code
*
* List<Customer> customers =
* ebeanServer.find(Customer.class)
* List<Customer> customers = DB.find(Customer.class)
* .where().ilike("name", "rob%")
* .findList();
*
@@ -272,7 +271,7 @@ public interface ExtendedServer {
* <p>
* <pre>{@code
*
* PagedList<Order> pagedList = Ebean.find(Order.class)
* PagedList<Order> pagedList = DB.find(Order.class)
* .setFirstRow(50)
* .setMaxRows(20)
* .findPagedList();
@@ -301,8 +300,7 @@ public interface ExtendedServer {
* <p>
* <pre>{@code
*
* Set<Customer> customers =
* ebeanServer.find(Customer.class)
* Set<Customer> customers = DB.find(Customer.class)
* .where().ilike("name", "rob%")
* .findSet();
*
@@ -341,7 +339,7 @@ public interface ExtendedServer {
* <pre>{@code
*
* List<String> names =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .select("name")
* .orderBy().asc("name")
* .findSingleAttributeList();
@@ -351,7 +349,7 @@ public interface ExtendedServer {
* <pre>{@code
*
* List<String> names =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .setDistinct(true)
* .select("name")
* .where().eq("status", Customer.Status.NEW)
@@ -413,7 +411,7 @@ public interface ExtendedServer {
/**
* Execute the update query returning the number of rows updated.
* <p>
* The update query must be created using {@link EbeanServer#update(Class)}.
* The update query must be created using {@link Database#update(Class)}.
* </p>
*
* @param query the update query to execute
+6 -6
View File
@@ -24,7 +24,7 @@ import java.io.Serializable;
* <p>
* <pre>{@code
* // Normal fetch join results in a single SQL query
* List<Order> list = Ebean.find(Order.class).fetch("details").findList();
* List<Order> list = DB.find(Order.class).fetch("details").findList();
*
* // Find Orders join details using a single SQL query
* }</pre>
@@ -36,7 +36,7 @@ import java.io.Serializable;
*
* // This will use 2 SQL queries to build this object graph
* List<Order> list =
* Ebean.find(Order.class)
* DB.find(Order.class)
* .fetch("details", new FetchConfig().query())
* .findList();
*
@@ -52,7 +52,7 @@ import java.io.Serializable;
*
* // This will use 3 SQL queries to build this object graph
* List<Order> list =
* Ebean.find(Order.class)
* DB.find(Order.class)
* .fetch("details", new FetchConfig().query())
* .fetch("customer", new FetchConfig().queryFirst(5))
* .findList();
@@ -70,7 +70,7 @@ import java.io.Serializable;
* <pre>{@code
* // This will use 3 SQL queries to build this object graph
* List<Order> list =
* Ebean.find(Order.class)
* DB.find(Order.class)
* .select("status, shipDate")
* .fetch("details", "quantity, price", new FetchConfig().query())
* .fetch("details.product", "sku, name")
@@ -100,7 +100,7 @@ import java.io.Serializable;
* <pre>{@code
*
* List<Order> list =
* Ebean.find(Order.class)
* DB.find(Order.class)
* .fetch("customer", new FetchConfig().query(10).lazy(5))
* .findList();
*
@@ -121,7 +121,7 @@ import java.io.Serializable;
* <p>
* <pre>{@code
*
* List<Order> list = Ebean.find(Order.class)
* List<Order> list = DB.find(Order.class)
* .fetch("customer","name", new FetchConfig().lazy(5))
* .fetch("customer.contacts","contactName, phone, email")
* .fetch("customer.shippingAddress")
+4 -4
View File
@@ -25,14 +25,14 @@ import java.util.Set;
* // get a list of entities (query execution statistics in this case)
*
* List<MetaQueryStatistic> list =
* Ebean.find(MetaQueryStatistic.class).findList();
* DB.find(MetaQueryStatistic.class).findList();
*
* long nowMinus24Hrs = System.currentTimeMillis() - 24 * (1000 * 60 * 60);
*
* // sort and filter the list returning a filtered list...
*
* List<MetaQueryStatistic> filteredList =
* Ebean.filter(MetaQueryStatistic.class)
* DB.filter(MetaQueryStatistic.class)
* .sort("avgTimeMicros desc")
* .gt("executionCount", 0)
* .gt("lastQueryTime", nowMinus24Hrs)
@@ -63,12 +63,12 @@ import java.util.Set;
* // get a list of entities (query execution statistics)
*
* List<Order> orders =
* Ebean.find(Order.class).findList();
* DB.find(Order.class).findList();
*
* // Apply a filter...
*
* List<Order> filteredOrders =
* Ebean.filter(Order.class)
* DB.filter(Order.class)
* .startsWith("customer.name", "Rob")
* .eq("customer.shippingAddress.city", "Auckland")
* .filter(orders);
+30 -26
View File
@@ -2,7 +2,6 @@ package io.ebean;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
/**
@@ -14,8 +13,7 @@ import java.util.List;
* </p>
* <h3>Testing</h3>
* <p>
* For testing the mocki-ebean project has the ability to replace the finder implementation
* <p>
* For testing the mocki-ebean project has the ability to replace the finder implementation.
* </p>
* <pre>{@code
*
@@ -25,7 +23,7 @@ import java.util.List;
* super(Customer.class);
* }
*
* // Add your customer finder methods ...
* // Add finder methods ...
*
* public Customer byName(String name) {
* return query().eq("name", name).findOne();
@@ -46,6 +44,15 @@ import java.util.List;
* ...
*
* }</pre>
* <p>
* When the Finder is registered as a field on Customer it can then be used like:
* </p>
* <pre>{@code
*
* Customer rob = Customer.find.byName("Rob");
*
* }</pre>
*
*/
public class Finder<I, T> {
@@ -55,9 +62,9 @@ public class Finder<I, T> {
private final Class<T> type;
/**
* The name of the EbeanServer, null for the default server.
* The name of the database this finder will use, null for the default database.
*/
private final String serverName;
private final String _$dbName;
/**
* Create with the type of the entity bean.
@@ -82,15 +89,15 @@ public class Finder<I, T> {
*/
public Finder(Class<T> type) {
this.type = type;
this.serverName = null;
this._$dbName = null;
}
/**
* Create with the type of the entity bean and specific server name.
* Create with the type of the entity bean and specific database name.
*/
public Finder(Class<T> type, String serverName) {
public Finder(Class<T> type, String databaseName) {
this.type = type;
this.serverName = serverName;
this._$dbName = databaseName;
}
/**
@@ -108,30 +115,27 @@ public class Finder<I, T> {
}
/**
* Return the underlying 'default' EbeanServer.
* <p>
* This provides full access to the API such as explicit transaction demarcation etc.
* Return the Database this finder will use.
*/
public EbeanServer db() {
return Ebean.getServer(serverName);
public Database db() {
return DB.byName(_$dbName);
}
/**
* Return typically a different EbeanServer to the default.
* Return typically a different Database to the default.
* <p>
* This is equivalent to {@link Ebean#getServer(String)}
* This is equivalent to {@link DB#byName(String)}
*
* @param server The name of the EbeanServer. If this is null then the default EbeanServer is
* returned.
* @param databaseName The name of the Database. If this is null then the default database is returned.
*/
public EbeanServer db(String server) {
return Ebean.getServer(server);
public Database db(String databaseName) {
return DB.byName(databaseName);
}
/**
* Creates an entity reference for this ID.
* <p>
* Equivalent to {@link EbeanServer#getReference(Class, Object)}
* Equivalent to {@link Database#getReference(Class, Object)}
*/
@Nonnull
public T ref(I id) {
@@ -141,7 +145,7 @@ public class Finder<I, T> {
/**
* Retrieves an entity by ID.
* <p>
* Equivalent to {@link EbeanServer#find(Class, Object)}
* Equivalent to {@link Database#find(Class, Object)}
*/
@Nullable
public T byId(I id) {
@@ -151,7 +155,7 @@ public class Finder<I, T> {
/**
* Delete a bean by Id.
* <p>
* Equivalent to {@link EbeanServer#delete(Class, Object)}
* Equivalent to {@link Database#delete(Class, Object)}
*/
public void deleteById(I id) {
db().delete(type, id);
@@ -181,7 +185,7 @@ public class Finder<I, T> {
* }</pre>
*
* <p>
* Equivalent to {@link EbeanServer#update(Class)}
* Equivalent to {@link Database#update(Class)}
*/
public UpdateQuery<T> update() {
return db().update(type);
@@ -190,7 +194,7 @@ public class Finder<I, T> {
/**
* Creates a query.
* <p>
* Equivalent to {@link EbeanServer#find(Class)}
* Equivalent to {@link Database#find(Class)}
*/
public Query<T> query() {
return db().find(type);
+1 -1
View File
@@ -20,7 +20,7 @@ import java.util.concurrent.TimeoutException;
* <pre>{@code
*
* // create a query to find all orders
* Query<Order> query = Ebean.find(Order.class);
* Query<Order> query = DB.find(Order.class);
*
* // execute the query in a background thread
* // immediately returning the futureList
+3 -3
View File
@@ -11,7 +11,7 @@ package io.ebean;
* </p>
* <pre>{@code
* Query q =
* Ebean.find(Person.class)
* DB.find(Person.class)
* .where()
* .or()
* .like("name", "Rob%")
@@ -30,7 +30,7 @@ package io.ebean;
* <pre>{@code
*
* Query q =
* Ebean.find(Person.class)
* DB.find(Person.class)
* .where()
* .or()
* .like("name", "Rob%")
@@ -50,7 +50,7 @@ package io.ebean;
* </p>
* <pre>{@code
* Query<Customer> q =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .where()
* .or()
* .and()
+19 -25
View File
@@ -11,15 +11,15 @@ import io.ebean.bean.EntityBean;
* Ebean users.
* <p>
* Note that there is a ebean-mocker project that enables you to use Mockito or similar
* tools to still mock out the underlying 'default EbeanServer' for testing purposes.
* tools to still mock out the underlying 'default Database' for testing purposes.
* <p>
* You may choose not use this Model mapped superclass if you don't like the 'Active Record' style
* or if you believe it 'pollutes' your entity beans.
* <p>
* You can use Dependency Injection like Guice or Spring to construct and wire a EbeanServer instance
* You can use Dependency Injection like Guice or Spring to construct and wire a Database instance
* and have that same instance used with this Model and Finder. The way that works is that when the
* DI container creates the EbeanServer instance it can be registered with the Ebean singleton. In this
* way the EbeanServer instance can be injected as per normal Guice / Spring dependency injection and
* DI container creates the Database instance it can be registered with DB. In this
* way the Database instance can be injected as per normal Guice / Spring dependency injection and
* that same instance also used to support the Model and Finder active record style.
* <p>
* If you choose to use the Model mapped superclass you will probably also chose to additionally add
@@ -76,15 +76,14 @@ import io.ebean.bean.EntityBean;
public abstract class Model {
/**
* Return the underlying 'default' EbeanServer.
* Return the underlying 'default' Database.
* <p>
* This provides full access to the API such as explicit transaction demarcation etc.
* <p>
* Example:
* <pre>{@code
*
* Transaction transaction = Customer.db().beginTransaction();
* try {
* try (Transaction transaction = Customer.db().beginTransaction()) {
*
* // turn off cascade persist for this transaction
* transaction.setPersistCascade(false);
@@ -104,26 +103,21 @@ public abstract class Model {
*
* transaction.commit();
*
* } finally {
* transaction.end();
* }
*
* }</pre>
*/
public static EbeanServer db() {
return Ebean.getDefaultServer();
public static Database db() {
return DB.getDefault();
}
/**
* Return a named EbeanServer that is typically different to the default server.
* <p>
* If you are using multiple databases then each database has a name and maps to a single
* EbeanServer. You can use this method to get an EbeanServer for another database.
* Return a named Database that is typically different to the default database.
*
* @param server The name of the EbeanServer. If this is null then the default EbeanServer is returned.
* @param server The name of the Database. If this is null then the default Database is returned.
*/
public static EbeanServer db(String server) {
return Ebean.getServer(server);
public static Database db(String server) {
return DB.byName(server);
}
/**
@@ -146,7 +140,7 @@ public abstract class Model {
*
* }</pre>
*
* @see EbeanServer#markAsDirty(Object)
* @see Database#markAsDirty(Object)
*/
public void markAsDirty() {
db().markAsDirty(this);
@@ -182,7 +176,7 @@ public abstract class Model {
* Ebean will detect if this is a new bean or a previously fetched bean and perform either an
* insert or an update based on that.
*
* @see EbeanServer#save(Object)
* @see Database#save(Object)
*/
public void save() {
db().save(this);
@@ -202,7 +196,7 @@ public abstract class Model {
/**
* Update this entity.
*
* @see EbeanServer#update(Object)
* @see Database#update(Object)
*/
public void update() {
db().update(this);
@@ -211,7 +205,7 @@ public abstract class Model {
/**
* Insert this entity.
*
* @see EbeanServer#insert(Object)
* @see Database#insert(Object)
*/
public void insert() {
db().insert(this);
@@ -232,7 +226,7 @@ public abstract class Model {
* deleted. Note that, if JDBC batch mode is used then this always returns true.
* </p>
*
* @see EbeanServer#delete(Object)
* @see Database#delete(Object)
*/
public boolean delete() {
return db().delete(this);
@@ -245,7 +239,7 @@ public abstract class Model {
* want to perform a hard/permanent delete.
* </p>
*
* @see EbeanServer#deletePermanent(Object)
* @see Database#deletePermanent(Object)
*/
public boolean deletePermanent() {
return db().deletePermanent(this);
@@ -275,7 +269,7 @@ public abstract class Model {
/**
* Refreshes this entity from the database.
*
* @see EbeanServer#refresh(Object)
* @see Database#refresh(Object)
*/
public void refresh() {
db().refresh(this);
+1 -2
View File
@@ -24,8 +24,7 @@ import java.util.concurrent.Future;
* // We want to find the first 50 new orders
* // ... so we don't really need setFirstRow(0)
*
* PagedList<Order> pagedList
* = ebeanServer.find(Order.class)
* PagedList<Order> pagedList = DB.find(Order.class)
* .where().eq("status", Order.Status.NEW)
* .order().asc("id")
* .setFirstRow(0)
+1 -1
View File
@@ -26,7 +26,7 @@ import java.util.List;
* pairs.add("sj2", 1001);
* pairs.add("pf3", 1000);
*
* List<OCachedNatKeyBean3> list = Ebean.find(OCachedNatKeyBean3.class)
* List<OCachedNatKeyBean3> list = DB.find(OCachedNatKeyBean3.class)
* .where()
* .eq("store", "def")
* .inPairs(pairs) // IN clause with 'pairs' of values
+44 -88
View File
@@ -19,10 +19,7 @@ import java.util.function.Predicate;
* <p>
* <pre>{@code
*
* List<Order> orderList =
* ebeanServer.find(Order.class)
* .fetch("customer")
* .fetch("details")
* List<Order> orderList = DB.find(Order.class)
* .where()
* .like("customer.name","rob%")
* .gt("orderDate",lastWeek)
@@ -38,29 +35,14 @@ import java.util.function.Predicate;
* <pre>{@code
*
* String oql =
* +" fetch customer "
* +" fetch details "
* +" where customer.name like :custName and orderDate > :minOrderDate "
* +" order by customer.id, id desc "
* +" limit 50 ";
*
* Query<Order> query = ebeanServer.createQuery(Order.class, oql);
* query.setParameter("custName", "Rob%");
* query.setParameter("minOrderDate", lastWeek);
*
* List<Order> orderList = query.findList();
* ...
* }</pre>
* <p>
* Example: Using a named query called "with.cust.and.details"
* </p>
* <pre>{@code
*
* Query<Order> query = ebeanServer.createNamedQuery(Order.class,"with.cust.and.details");
* query.setParameter("custName", "Rob%");
* query.setParameter("minOrderDate", lastWeek);
*
* List<Order> orderList = query.findList();
* List<Order> orderList = DB.createQuery(Order.class, oql)
* .setParameter("custName", "Rob%")
* .setParameter("minOrderDate", lastWeek)
* .findList();
* ...
* }</pre>
* <h3>AutoTune</h3>
@@ -377,7 +359,7 @@ public interface Query<T> {
* <pre>{@code
*
* // fetch a bean with JSON content
* EBasicJsonList bean= Ebean.find(EBasicJsonList.class)
* EBasicJsonList bean= DB.find(EBasicJsonList.class)
* .setId(42)
* .setAllowLoadErrors() // collect errors into bean state if we have invalid JSON
* .findOne();
@@ -436,8 +418,7 @@ public interface Query<T> {
* </p>
* <pre>{@code
*
* List<Customer> customers =
* ebeanServer.find(Customer.class)
* List<Customer> customers = DB.find(Customer.class)
* // Only fetch the customer id, name and status.
* // This is described as a "Partial Object"
* .select("name, status")
@@ -465,8 +446,7 @@ public interface Query<T> {
* <pre>{@code
*
* // query orders...
* List<Order> orders =
* ebeanServer.find(Order.class)
* List<Order> orders = DB.find(Order.class)
* // fetch the customer...
* // ... getting the customers name and phone number
* .fetch("customer", "name, phoneNumber")
@@ -481,8 +461,7 @@ public interface Query<T> {
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* ebeanServer.find(Customer.class)
* List<Customer> customers = DB.find(Customer.class)
* .select("name, status")
* .fetch("contacts", "firstName,lastName,email")
* .findList();
@@ -551,8 +530,7 @@ public interface Query<T> {
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* ebeanServer.find(Customer.class)
* List<Customer> customers = DB.find(Customer.class)
* .select("name, status")
* .fetch("contacts", "firstName,lastName,email", new FetchConfig().lazy(10))
* .findList();
@@ -573,8 +551,7 @@ public interface Query<T> {
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* ebeanServer.find(Customer.class)
* List<Customer> customers = DB.find(Customer.class)
* // eager fetch the contacts
* .fetch("contacts")
* .findList();
@@ -637,8 +614,7 @@ public interface Query<T> {
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers =
* ebeanServer.find(Customer.class)
* List<Customer> customers = DB.find(Customer.class)
* // lazy fetch contacts with a batch size of 100
* .fetch("contacts", new FetchConfig().lazy(100))
* .findList();
@@ -658,7 +634,7 @@ public interface Query<T> {
/**
* Execute the query returning the list of Id's.
* <p>
* This query will execute against the EbeanServer that was used to create it.
* This query will execute against the Database that was used to create it.
* </p>
*/
@Nonnull
@@ -680,12 +656,11 @@ public interface Query<T> {
* the jdbc statement and resultSet are closed at the end of the iteration.
* </p>
* <p>
* This query will execute against the EbeanServer that was used to create it.
* This query will execute against the Database that was used to create it.
* </p>
* <pre>{@code
*
* Query<Customer> query =
* ebeanServer.find(Customer.class)
* Query<Customer> query = DB.find(Customer.class)
* .where().eq("status", Status.NEW)
* .order().asc("id");
*
@@ -732,7 +707,7 @@ public interface Query<T> {
* </p>
* <pre>{@code
*
* ebeanServer.find(Customer.class)
* DB.find(Customer.class)
* .where().eq("status", Status.NEW)
* .order().asc("id")
* .findEach((Customer customer) -> {
@@ -761,7 +736,7 @@ public interface Query<T> {
* </p>
* <pre>{@code
*
* ebeanServer.find(Customer.class)
* DB.find(Customer.class)
* .fetch("contacts", new FetchConfig().query(2))
* .where().eq("status", Status.NEW)
* .order().asc("id")
@@ -784,12 +759,11 @@ public interface Query<T> {
/**
* Execute the query returning the list of objects.
* <p>
* This query will execute against the EbeanServer that was used to create it.
* This query will execute against the Database that was used to create it.
* </p>
* <pre>{@code
*
* List<Customer> customers =
* ebeanServer.find(Customer.class)
* List<Customer> customers = DB.find(Customer.class)
* .where().ilike("name", "rob%")
* .findList();
*
@@ -801,12 +775,11 @@ public interface Query<T> {
/**
* Execute the query returning the set of objects.
* <p>
* This query will execute against the EbeanServer that was used to create it.
* This query will execute against the Database that was used to create it.
* </p>
* <pre>{@code
*
* Set<Customer> customers =
* ebeanServer.find(Customer.class)
* Set<Customer> customers = DB.find(Customer.class)
* .where().ilike("name", "rob%")
* .findSet();
*
@@ -818,7 +791,7 @@ public interface Query<T> {
/**
* Execute the query returning a map of the objects.
* <p>
* This query will execute against the EbeanServer that was used to create it.
* This query will execute against the Database that was used to create it.
* </p>
* <p>
* You can use setMapKey() so specify the property values to be used as keys
@@ -826,8 +799,7 @@ public interface Query<T> {
* </p>
* <pre>{@code
*
* Map<String, Product> map =
* ebeanServer.find(Product.class)
* Map<String, Product> map = DB.find(Product.class)
* .setMapKey("sku")
* .findMap();
*
@@ -843,7 +815,7 @@ public interface Query<T> {
* <pre>{@code
*
* List<String> names =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .select("name")
* .orderBy().asc("name")
* .findSingleAttributeList();
@@ -854,7 +826,7 @@ public interface Query<T> {
* <pre>{@code
*
* List<String> names =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .setDistinct(true)
* .select("name")
* .where().eq("status", Customer.Status.NEW)
@@ -875,7 +847,7 @@ public interface Query<T> {
* <pre>{@code
*
* String name =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .select("name")
* .where().eq("id", 42)
* .findSingleAttribute();
@@ -934,8 +906,7 @@ public interface Query<T> {
* <pre>{@code
*
* // assuming the sku of products is unique...
* Product product =
* ebeanServer.find(Product.class)
* Product product = DB.find(Product.class)
* .where().eq("sku", "aa113")
* .findOne();
* ...
@@ -947,8 +918,7 @@ public interface Query<T> {
* <pre>{@code
*
* // Fetch order 1 and additionally fetch join its order details...
* Order order =
* ebeanServer.find(Order.class)
* Order order = DB.find(Order.class)
* .setId(1)
* .fetch("details")
* .findOne();
@@ -1089,7 +1059,7 @@ public interface Query<T> {
* </p>
* <pre>{@code
*
* PagedList<Order> pagedList = Ebean.find(Order.class)
* PagedList<Order> pagedList = DB.find(Order.class)
* .setFirstRow(50)
* .setMaxRows(20)
* .findPagedList();
@@ -1114,11 +1084,9 @@ public interface Query<T> {
* // a query with a named parameter
* String oql = "find order where status = :orderStatus";
*
* Query<Order> query = ebeanServer.find(Order.class, oql);
*
* // bind the named parameter
* query.bind("orderStatus", OrderStatus.NEW);
* List<Order> list = query.findList();
* List<Order> list = DB.find(Order.class, oql)
* .setParameter("orderStatus", OrderStatus.NEW)
* .findList();
*
* }</pre>
*
@@ -1136,12 +1104,9 @@ public interface Query<T> {
* // a query with a positioned parameter
* String oql = "where status = ? order by id desc";
*
* Query<Order> query = ebeanServer.createQuery(Order.class, oql);
*
* // bind the parameter
* query.setParameter(1, OrderStatus.NEW);
*
* List<Order> list = query.findList();
* List<Order> list = DB.createQuery(Order.class, oql)
* .setParameter(1, OrderStatus.NEW)
* .findList();
*
* }</pre>
*
@@ -1158,8 +1123,7 @@ public interface Query<T> {
* </p>
* <pre>{@code
*
* Order order =
* ebeanServer.find(Order.class)
* Order order = DB.find(Order.class)
* .setId(1)
* .fetch("details")
* .findOne();
@@ -1180,8 +1144,7 @@ public interface Query<T> {
* Add a single Expression to the where clause returning the query.
* <pre>{@code
*
* List<Order> newOrders =
* ebeanServer.find(Order.class)
* List<Order> newOrders = DB.find(Order.class)
* .where().eq("status", Order.NEW)
* .findList();
* ...
@@ -1196,8 +1159,7 @@ public interface Query<T> {
* where clause.
* <pre>{@code
*
* List<Order> orders =
* ebeanServer.find(Order.class)
* List<Order> orders = DB.find(Order.class)
* .where()
* .eq("status", Order.NEW)
* .ilike("customer.name","rob%")
@@ -1243,10 +1205,7 @@ public interface Query<T> {
* </p>
* <pre>{@code
*
* List<Customer> list =
* ebeanServer.find(Customer.class)
* // .fetch("orders", new FetchConfig().lazy())
* // .fetch("orders", new FetchConfig().query())
* List<Customer> list = DB.find(Customer.class)
* .fetch("orders")
* .where().ilike("name", "rob%")
* .filterMany("orders").eq("status", Order.Status.NEW).gt("orderDate", lastWeek)
@@ -1260,8 +1219,7 @@ public interface Query<T> {
* </p>
*
* @param propertyName the name of the many property that you want to have a filter on.
* @return the expression list that you add filter expressions for the many
* to.
* @return the expression list that you add filter expressions for the many to.
*/
ExpressionList<T> filterMany(String propertyName);
@@ -1375,7 +1333,7 @@ public interface Query<T> {
* <pre>{@code
*
* List<Customer> customers =
* Ebean.find(Customer.class)
* DB.find(Customer.class)
* .setDistinct(true)
* .select("name")
* .findList();
@@ -1391,7 +1349,7 @@ public interface Query<T> {
*
* List<CountedValue<Order.Status>> orderStatusCount =
*
* Ebean.find(Order.class)
* DB.find(Order.class)
* .select("status")
* .where()
* .gt("orderDate", LocalDate.now().minusMonths(3))
@@ -1447,10 +1405,8 @@ public interface Query<T> {
*
* // Assuming sku is unique for products...
*
* Map<String,Product> productMap =
* ebeanServer.find(Product.class)
* // use sku for keys...
* .setMapKey("sku")
* Map<String,Product> productMap = DB.find(Product.class)
* .setMapKey("sku") // sku map keys...
* .findMap();
*
* }</pre>
+3 -3
View File
@@ -87,7 +87,7 @@ package io.ebean;
* // .columnMapping("sum(d.order_qty*d.unit_price)", "totalAmount")
* .create();
*
* List<OrderAggregate> list = Ebean.find(OrderAggregate.class)
* List<OrderAggregate> list = DB.find(OrderAggregate.class)
* .setRawSql(rawSql)
* .where().gt("order.id", 0)
* .having().gt("totalAmount", 20)
@@ -114,7 +114,7 @@ package io.ebean;
* .columnMappingIgnore("'ignoreMe'")
* .create();
*
* List<OrderAggregate> orders = Ebean.find(OrderAggregate.class)
* List<OrderAggregate> orders = DB.find(OrderAggregate.class)
* .setRawSql(rawSql)
* .fetch("order", "status,orderDate", new FetchConfig().query())
* .fetch("order.customer", "name")
@@ -146,7 +146,7 @@ package io.ebean;
* .tableAliasMapping("p", "details.product")
* .create();
*
* List<Order> ordersFromRaw = Ebean.find(Order.class)
* List<Order> ordersFromRaw = DB.find(Order.class)
* .setRawSql(rawSql)
* .setParameter("maxOrderId", 2)
* .setParameter("productId", 1)
+1 -1
View File
@@ -13,7 +13,7 @@ import java.sql.SQLException;
*
* String sql = "select id, name, status from o_customer order by name desc";
*
* Ebean.createSqlQuery(sql)
* DB.sqlQuery(sql)
* .findEachRow((resultSet, rowNum) -> {
*
* // read directly from ResultSet
+1 -1
View File
@@ -40,7 +40,7 @@ import java.sql.SQLException;
*
* String sql = "select id, name, status from o_customer where name = ?";
*
* CustomerDto rob = Ebean.createSqlQuery(sql)
* CustomerDto rob = DB.sqlQuery(sql)
* .setParameter(1, "Rob")
* .findOne(CUSTOMER_MAPPER);
*
+4 -16
View File
@@ -13,20 +13,8 @@ import java.util.Map;
* <h3>Example of simple use</h3>
* <pre>{@code
*
* EbeanServer server = Ebean.getDefaultServer();
* server.script().run("/scripts/test-script.sql");
*
* }</pre>
*
*
* <h3>Example using place holders in the script</h3>
* <pre>{@code
*
* Map<String,String> placeholders = new HashMap<>();
* placeholders.put("tableName", "e_basic");
*
* EbeanServer server = Ebean.getDefaultServer();
* server.script().run("/scripts/test-script.sql");
* Database database = DB.getDefault();
* database.script().run("/scripts/test-script.sql");
*
* }</pre>
*/
@@ -45,8 +33,8 @@ public interface ScriptRunner {
* Map<String,String> placeholders = new HashMap<>();
* placeholders.put("tableName", "e_basic");
*
* EbeanServer server = Ebean.getDefaultServer();
* server.script().run("/scripts/test-script.sql");
* Database database = DB.getDefault();
* database.script().run("/scripts/test-script.sql", placeholders);
*
* }</pre>
*/
+24 -25
View File
@@ -10,34 +10,30 @@ import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* Query object for performing native SQL queries that return SqlRow's.
* <p>
* Firstly note that you can use your own sql queries with <em>entity beans</em>
* by using the SqlSelect annotation. This should be your first approach when
* wanting to use your own SQL queries.
* </p>
* <p>
* If ORM Mapping is too tight and constraining for your problem then SqlQuery
* could be a good approach.
* </p>
* Query object for performing native SQL queries that return SqlRow or directly read
* ResultSet using a RowMapper.
* <p>
* The returned SqlRow objects are similar to a LinkedHashMap with some type
* conversion support added.
* </p>
* <p>
* Refer to {@link DtoQuery} for native sql queries returning DTO beans.
* </p>
* <p>
* Refer to {@link Database#findNative(Class, String)} for native sql queries returning entity beans.
* </p>
*
* <pre>{@code
*
* // its typically a good idea to use a named query
* // and put the sql in the orm.xml instead of in your code
* // example using named parameters
*
* String sql = "select id, name from customer where name like :name and status_code = :status";
*
* SqlQuery sqlQuery = Ebean.createSqlQuery(sql);
* sqlQuery.setParameter("name", "Acme%");
* sqlQuery.setParameter("status", "ACTIVE");
*
* // execute the query returning a List of MapBean objects
* List<SqlRow> list = sqlQuery.findList();
* List<SqlRow> list =
* DB.sqlQuery(sql)
* .setParameter("name", "Acme%")
* .setParameter("status", "ACTIVE")
* .findList();
*
* }</pre>
*/
@@ -104,7 +100,7 @@ public interface SqlQuery extends Serializable {
*
* String sql = "select id, name, status from customer order by name desc";
*
* Ebean.createSqlQuery(sql)
* DB.sqlQuery(sql)
* .findEachRow((resultSet, rowNum) -> {
*
* // read directly from ResultSet
@@ -134,7 +130,7 @@ public interface SqlQuery extends Serializable {
*
* String sql = "select max(unit_price) from o_order_detail where order_qty > ?";
*
* BigDecimal maxPrice = Ebean.createSqlQuery(sql)
* BigDecimal maxPrice = DB.sqlQuery(sql)
* .setParameter(1, 2)
* .findSingleAttribute(BigDecimal.class);
*
@@ -176,9 +172,10 @@ public interface SqlQuery extends Serializable {
* " order by (unit_price * order_qty) desc";
*
* //
* List<BigDecimal> lineAmounts = Ebean.createSqlQuery(sql)
* .setParameter(1, 3)
* .findSingleAttributeList(BigDecimal.class);
* List<BigDecimal> lineAmounts =
* DB.sqlQuery(sql)
* .setParameter(1, 3)
* .findSingleAttributeList(BigDecimal.class);
*
* }</pre>
*
@@ -204,14 +201,16 @@ public interface SqlQuery extends Serializable {
*
* String sql = "select id, name from customer where name like ? and status = ?";
*
* Ebean.createSqlQuery(sql)
* List<SqlRow> list =
* DB.sqlQuery(sql)
* .setParams("Rob", Status.NEW)
* .findList();
*
*
* // is the same as ...
*
* Ebean.createSqlQuery(sql)
* List<SqlRow> list =
* DB.sqlQuery(sql)
* .setParameter(1, "Rob")
* .setParameter(2, "Status.NEW)
* .findList();
+28 -14
View File
@@ -16,20 +16,33 @@ package io.ebean;
* notify Ebean of external changes and enable Ebean to maintain it's "L2"
* server cache.
* </p>
* <p>
*
* <pre>{@code
*
* // example that uses 'named' parameters
* // example using 'positioned' parameters
*
* String s = "UPDATE f_topic set post_count = :count where id = :id";
* String sql = "insert into audit_log (group, title, description) values (?, ?, ?);
*
* SqlUpdate update = Ebean.createSqlUpdate(s);
* update.setParameter("id", 1);
* update.setParameter("count", 50);
* int rows =
* DB.sqlUpdate(sql)
* .setParams("login", "new user", "user rob was created")
* .executeNow();
*
* int modifiedCount = update.execute();
* }</pre>
*
* String msg = "There were " + modifiedCount + " rows updated";
* <pre>{@code
*
* // example using 'named' parameters
*
* String sql = "update topic set post_count = :count where id = :id";
*
* int rows =
* DB.sqlUpdate(sql)
* .setParameter("id", 1)
* .setParameter("count", 50)
* .execute();
*
* String msg = "There were " + rows + " rows updated";
*
* }</pre>
* <p>
@@ -37,9 +50,10 @@ package io.ebean;
* <pre>{@code
*
* String sql = "insert into audit_log (id, description, modified_description) values (?,?,?)";
* SqlUpdate insert = Ebean.createSqlUpdate(sql);
*
* try (Transaction txn = Ebean.beginTransaction()) {
* SqlUpdate insert = DB.sqlUpdate(sql);
*
* try (Transaction txn = DB.beginTransaction()) {
* txn.setBatchMode(true);
*
* insert.setNextParameter(10000);
@@ -65,7 +79,7 @@ package io.ebean;
* </p>
* <pre>{@code
*
* try (Transaction txn = Ebean.beginTransaction()) {
* try (Transaction txn = DB.beginTransaction()) {
*
* insert.setNextParameter(10000);
* insert.setNextParameter("hello");
@@ -220,20 +234,20 @@ public interface SqlUpdate {
/**
* Set one of more positioned parameters.
* <p>
* This is a convenient alternative to multiple calls setParameter().
* This is a convenient alternative to multiple setParameter() calls.
*
* <pre>{@code
*
* String sql = "insert into audit_log (id, name, version) values (?,?,?)";
*
* Ebean.createSqlUpdate(sql)
* DB.sqlUpdate(sql)
* .setParams(UUID.randomUUID(), "Hello", 1)
* .executeNow();
*
*
* // is the same as ...
*
* Ebean.createSqlUpdate(sql)
* DB.sqlUpdate(sql)
* .setParameter(1, UUID.randomUUID())
* .setParameter(2, "Hello")
* .setParameter(3, 1)
+8 -9
View File
@@ -14,18 +14,17 @@ import java.sql.Connection;
public interface Transaction extends AutoCloseable {
/**
* Return the current transaction (of the default server) or null if there is
* Return the current transaction (of the default database) or null if there is
* no current transaction in scope.
* <p>
* This is the same as <code>Ebean.currentTransaction()</code>
* This is the same as <code>DB.currentTransaction()</code>
* </p>
* <p>
* This returns the current transaction for the 'default server'. If you are using
* multiple EbeanServer's then use {@link EbeanServer#currentTransaction()}.
* This returns the current transaction for the default database.
* </p>
*
* @see Ebean#currentTransaction()
* @see EbeanServer#currentTransaction()
* @see DB#currentTransaction()
* @see Database#currentTransaction()
*/
static Transaction current() {
return Ebean.currentTransaction();
@@ -244,7 +243,7 @@ public interface Transaction extends AutoCloseable {
*
* // assume Customer has L2 bean caching enabled ...
*
* try (Transaction transaction = ebeanServer.beginTransaction()) {
* try (Transaction transaction = DB.beginTransaction()) {
*
* // this uses L2 bean cache as the transaction
* // ... is considered "query only" at this point
@@ -366,13 +365,13 @@ public interface Transaction extends AutoCloseable {
* // inserts into a table called sp_test
* cs.addModification("sp_test", true, false, false);
*
* try (Transaction txn = ebeanServer.beginTransaction()) {
* try (Transaction txn = DB.beginTransaction()) {
* txn.setBatchMode(true);
* txn.setBatchSize(10);
*
* for (int i = 0; i < da.length;) {
* cs.setParameter(1, da[i]);
* ebeanServer.execute(cs);
* DB.execute(cs);
* }
*
* // Note: commit implicitly flushes
+1 -1
View File
@@ -41,7 +41,7 @@ package io.ebean;
* <p>
* <pre>{@code
*
* Update<Topic> update = Ebean.createUpdate(Topic.class, "incrementPostCount");
* Update<Topic> update = DB.createUpdate(Topic.class, "incrementPostCount");
* update.setParameter("id", 1);
* int rows = update.execute();
*
+6 -12
View File
@@ -12,8 +12,7 @@ package io.ebean;
* <p>
* <pre>{@code
*
* int rows = ebeanServer
* .update(Customer.class)
* int rows = DB.update(Customer.class)
* .set("status", Customer.Status.ACTIVE)
* .set("updtime", new Timestamp(System.currentTimeMillis()))
* .where()
@@ -39,8 +38,7 @@ package io.ebean;
* <p>
* <pre>{@code
*
* int rows = ebeanServer
* .update(Customer.class)
* int rows = DB.update(Customer.class)
* .set("status", Customer.Status.ACTIVE)
* .set("updtime", new Timestamp(System.currentTimeMillis()))
* .where()
@@ -73,8 +71,7 @@ public interface UpdateQuery<T> {
* <p>
* <pre>{@code
*
* int rows = ebeanServer
* .update(Customer.class)
* int rows = DB.update(Customer.class)
* .set("status", Customer.Status.ACTIVE)
* .set("updtime", new Timestamp(System.currentTimeMillis()))
* .where()
@@ -93,8 +90,7 @@ public interface UpdateQuery<T> {
* <p>
* <pre>{@code
*
* int rows = ebeanServer
* .update(Customer.class)
* int rows = DB.update(Customer.class)
* .setNull("notes")
* .where()
* .gt("id", 1000)
@@ -114,8 +110,7 @@ public interface UpdateQuery<T> {
* <p>
* <pre>{@code
*
* int rows = ebeanServer
* .update(Customer.class)
* int rows = DB.update(Customer.class)
* .setRaw("status = coalesce(status, 'A')")
* .where()
* .gt("id", 1000)
@@ -134,8 +129,7 @@ public interface UpdateQuery<T> {
* </p>
* <pre>{@code
*
* int rows = ebeanServer
* .update(Customer.class)
* int rows = DB.update(Customer.class)
* .setRaw("status = coalesce(status, ?)", Customer.Status.ACTIVE)
* .where()
* .gt("id", 1000)
@@ -9,7 +9,7 @@ package io.ebean.bean;
public interface BeanCollectionLoader {
/**
* Return the name of the associated EbeanServer.
* Return the name of the associated Database.
*/
String getName();
+1 -1
View File
@@ -9,7 +9,7 @@ package io.ebean.bean;
public interface BeanLoader {
/**
* Return the name of the associated EbeanServer.
* Return the name of the associated Database.
*/
String getName();
@@ -20,7 +20,7 @@ abstract class AbstractBeanCollection<E> implements BeanCollection<E> {
protected boolean disableLazyLoad;
/**
* The EbeanServer this is associated with. (used for lazy fetch).
* The Database this is associated with. (used for lazy fetch).
*/
protected transient BeanCollectionLoader loader;
@@ -1,7 +1,7 @@
package io.ebean.config;
/**
* Used to provide some automatic configuration early in the creation of an EbeanServer.
* Used to provide some automatic configuration early in the creation of a Database.
*/
public interface AutoConfigure {
@@ -1,7 +1,7 @@
package io.ebean.config;
/**
* Defines the AutoTune behaviour for a EbeanServer.
* Defines the AutoTune behaviour for a Database.
*/
public class AutoTuneConfig {
@@ -3,7 +3,7 @@ package io.ebean.config;
import java.util.Properties;
/**
* Configuration for the container that holds the EbeanServer instances.
* Configuration for the container that holds the Database instances.
* <p>
* Provides configuration for cluster communication (if clustering is used). The cluster communication is
* used to invalidate appropriate parts of the L2 cache across the cluster.
@@ -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 {
}
@@ -140,7 +140,7 @@ public class DbMigrationConfig {
* <p>
* The default of "dbmigration" is reasonable in most cases. You may look to set this
* to be something like "dbmigration/myapp" where myapp gives it a unique resource path
* in the case there are multiple EbeanServer applications in the single classpath.
* in the case there are multiple Database applications in the single classpath.
* </p>
*/
public void setMigrationPath(String migrationPath) {
@@ -47,6 +47,11 @@ public class PlatformConfig {
*/
private DbUuid dbUuid = DbUuid.AUTO_VARCHAR;
/**
* Set to true to force InetAddress to map to Varchar (for Postgres rather than INET)
*/
private boolean databaseInetAddressVarchar;
/**
* Modify the default mapping of standard types such as default precision for DECIMAL etc.
*/
@@ -181,6 +186,20 @@ public class PlatformConfig {
this.idType = idType;
}
/**
* Return true if InetAddress should map to varchar column (rather than Postgres INET).
*/
public boolean isDatabaseInetAddressVarchar() {
return databaseInetAddressVarchar;
}
/**
* Set to true to force InetAddress to map to varchar column.
*/
public void setDatabaseInetAddressVarchar(boolean databaseInetAddressVarchar) {
this.databaseInetAddressVarchar = databaseInetAddressVarchar;
}
/**
* Add a custom type mapping.
* <p>
@@ -235,6 +254,7 @@ public class PlatformConfig {
databaseSequenceBatchSize = p.getInt("databaseSequenceBatchSize", databaseSequenceBatchSize);
databaseBooleanTrue = p.get("databaseBooleanTrue", databaseBooleanTrue);
databaseBooleanFalse = p.get("databaseBooleanFalse", databaseBooleanFalse);
databaseInetAddressVarchar = p.getBoolean("databaseInetAddressVarchar", databaseInetAddressVarchar);
DbUuid dbUuid = p.getEnum(DbUuid.class, "dbuuid", null);
if (dbUuid != null) {
+35 -39
View File
@@ -1,7 +1,7 @@
package io.ebean.config;
import com.fasterxml.jackson.core.JsonFactory;
import io.ebean.EbeanServerFactory;
import io.ebean.DatabaseFactory;
import io.ebean.PersistenceContextScope;
import io.ebean.Query;
import io.ebean.Transaction;
@@ -44,30 +44,30 @@ import java.util.Properties;
import java.util.ServiceLoader;
/**
* The configuration used for creating a EbeanServer.
* The configuration used for creating a Database.
* <p>
* Used to programmatically construct an EbeanServer and optionally register it
* with the Ebean singleton.
* Used to programmatically construct a Database and optionally register it
* with the DB singleton.
* </p>
* <p>
* If you just use Ebean without this programmatic configuration Ebean will read
* the ebean.properties file and take the configuration from there. This usually
* If you just use DB without this programmatic configuration DB 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
*
* ServerConfig c = new ServerConfig();
* ServerConfig config = new ServerConfig();
*
* // read the ebean.properties and load
* // those settings into this serverConfig object
* c.loadFromProperties();
* config.loadFromProperties();
*
* // explicitly register the entity beans to avoid classpath scanning
* c.addClass(Customer.class);
* c.addClass(User.class);
* config.addClass(Customer.class);
* config.addClass(User.class);
*
* EbeanServer server = EbeanServerFactory.create(c);
* Database database = DatabaseFactory.create(config);
*
* }</pre>
*
@@ -78,12 +78,12 @@ import java.util.ServiceLoader;
*
* @author emcgreal
* @author rbygrave
* @see EbeanServerFactory
* @see DatabaseFactory
*/
public class ServerConfig {
/**
* The EbeanServer name.
* The Database name.
*/
private String name = "db";
@@ -106,12 +106,12 @@ public class ServerConfig {
private String resourceDirectory;
/**
* Set to true to register this EbeanServer with the Ebean singleton.
* Set to true to register this Database with the DB singleton.
*/
private boolean register = true;
/**
* Set to true if this is the default/primary server.
* Set to true if this is the default/primary database.
*/
private boolean defaultServer = true;
@@ -150,7 +150,7 @@ public class ServerConfig {
private DocStoreConfig docStoreConfig = new DocStoreConfig();
/**
* Set to true when the EbeanServer only uses Document store.
* Set to true when the Database only uses Document store.
*/
private boolean docStoreOnly;
@@ -350,7 +350,7 @@ public class ServerConfig {
/**
* Behaviour of updates in JDBC batch to by default include all properties.
*/
private boolean updateAllPropertiesInBatch = true;
private boolean updateAllPropertiesInBatch;
/**
* Default behaviour for updates when cascade save on a O2M or M2M to delete any missing children.
@@ -522,7 +522,7 @@ public class ServerConfig {
private boolean idGeneratorAutomatic = true;
/**
* Construct a Server Configuration for programmatically creating an EbeanServer.
* Construct a Database Configuration for programmatically creating an Database.
*/
public ServerConfig() {
@@ -693,14 +693,14 @@ public class ServerConfig {
}
/**
* Return the name of the EbeanServer.
* Return the name of the Database.
*/
public String getName() {
return name;
}
/**
* Set the name of the EbeanServer.
* Set the name of the Database.
*/
public void setName(String name) {
this.name = name;
@@ -709,8 +709,8 @@ public class ServerConfig {
/**
* Return the container / clustering configuration.
* <p/>
* The container holds all the EbeanServer instances and provides clustering communication
* services to all the EbeanServer instances.
* The container holds all the Database instances and provides clustering communication
* services to all the Database instances.
*/
public ContainerConfig getContainerConfig() {
return containerConfig;
@@ -719,8 +719,8 @@ public class ServerConfig {
/**
* Set the container / clustering configuration.
* <p/>
* The container holds all the EbeanServer instances and provides clustering communication
* services to all the EbeanServer instances.
* The container holds all the Database instances and provides clustering communication
* services to all the Database instances.
*/
public void setContainerConfig(ContainerConfig containerConfig) {
this.containerConfig = containerConfig;
@@ -760,8 +760,8 @@ public class ServerConfig {
}
/**
* Set false if you do not want this EbeanServer to be registered as the "default" server
* with the Ebean singleton.
* Set false if you do not want this Database to be registered as the "default" database
* with the DB singleton.
* <p>
* This is only used when {@link #setRegister(boolean)} is also true.
* </p>
@@ -1547,14 +1547,14 @@ public class ServerConfig {
}
/**
* Return true if this EbeanServer is a Document store only instance (has no JDBC DB).
* Return true if this Database is a Document store only instance (has no JDBC DB).
*/
public boolean isDocStoreOnly() {
return docStoreOnly;
}
/**
* Set to true if this EbeanServer is Document store only instance (has no JDBC DB).
* Set to true if this Database is Document store only instance (has no JDBC DB).
*/
public void setDocStoreOnly(boolean docStoreOnly) {
this.docStoreOnly = docStoreOnly;
@@ -1954,16 +1954,16 @@ public class ServerConfig {
}
/**
* Return true if the EbeanServer instance should be created in offline mode.
* Return true if the Database instance should be created in offline mode.
*/
public boolean isDbOffline() {
return dbOffline;
}
/**
* Set to true if the EbeanServer instance should be created in offline mode.
* Set to true if the Database instance should be created in offline mode.
* <p>
* Typically used to create an EbeanServer instance for DDL Migration generation
* Typically used to create an Database instance for DDL Migration generation
* without requiring a real DataSource / Database to connect to.
* </p>
*/
@@ -2214,7 +2214,7 @@ public class ServerConfig {
/**
* Set to true to disable the class path search even for the case where no entity bean classes
* have been registered. This can be used to start an EbeanServer instance just to use the
* have been registered. This can be used to start an Database instance just to use the
* SQL functions such as SqlQuery, SqlUpdate etc.
*/
public void setDisableClasspathSearch(boolean disableClasspathSearch) {
@@ -2328,8 +2328,7 @@ public class ServerConfig {
*
* // assume Customer has L2 bean caching enabled ...
*
* Transaction transaction = Ebean.beginTransaction();
* try {
* try (Transaction transaction = DB.beginTransaction()) {
*
* // this uses L2 bean cache as the transaction
* // ... is considered "query only" at this point
@@ -2337,7 +2336,7 @@ public class ServerConfig {
*
* // transaction no longer "query only" once
* // ... a bean has been saved etc
* Ebean.save(someBean);
* DB.save(someBean);
*
* // will NOT use L2 bean cache as the transaction
* // ... is no longer considered "query only"
@@ -2356,9 +2355,6 @@ public class ServerConfig {
* transaction.setSkipCache(true);
* Customer.find.byId(99); // skips l2 bean cache
*
*
* } finally {
* transaction.end();
* }
*
* }</pre>
@@ -2426,7 +2422,7 @@ public class ServerConfig {
}
/**
* Return true if the ebeanServer should collection query statistics by ObjectGraphNode.
* Return true if query statistics should be collected by ObjectGraphNode.
*/
public boolean isCollectQueryStatsByNode() {
return collectQueryStatsByNode;
@@ -27,6 +27,9 @@ public class DbPlatformTypeMapping {
private static final DbPlatformType BOOLEAN_LOGICAL = new BooleanLogicalType();
private static final DbPlatformType INET_NATIVE = new DbPlatformType("inet", false);
private static final DbPlatformType INET_VARCHAR = new DbPlatformType("varchar", 50);
private static final DbPlatformType UUID_NATIVE = new DbPlatformType("uuid", false);
@SuppressWarnings("unused")
private static final DbPlatformType UUID_PLACEHOLDER = new DbPlatformType("uuidPlaceholder");
@@ -106,6 +109,7 @@ public class DbPlatformTypeMapping {
put(DbType.JSONBLOB, new DbPlatformType("jsonblob"));
put(DbType.JSONVARCHAR, new DbPlatformType("jsonvarchar", 1000));
put(DbType.UUID, UUID_NATIVE);
put(DbType.INET, INET_NATIVE);
} else {
put(DbType.VARCHAR, new DbPlatformType("varchar", 255));
@@ -121,6 +125,7 @@ public class DbPlatformTypeMapping {
put(DbType.JSONVARCHAR, JSON_VARCHAR_PLACEHOLDER);
// default to native UUID and override on platform configure()
put(DbType.UUID, UUID_NATIVE);
put(DbType.INET, INET_VARCHAR);
}
}
@@ -35,6 +35,8 @@ public enum DbType {
ARRAY(Types.ARRAY),
UUID(ExtraDbTypes.UUID),
INET(ExtraDbTypes.INET),
CDIR(ExtraDbTypes.CDIR),
POINT(ExtraDbTypes.POINT),
POLYGON(ExtraDbTypes.POLYGON),
@@ -40,6 +40,9 @@ public interface ExtraDbTypes {
*/
int JSONBlob = 5005;
int INET = 5020;
int CDIR = 5021;
/**
* Geo Point
*/
@@ -60,6 +60,7 @@ public class PostgresPlatform extends DatabasePlatform {
DbPlatformType dbBytea = new DbPlatformType("bytea", false);
dbTypeMap.put(DbType.UUID, new DbPlatformType("uuid", false));
dbTypeMap.put(DbType.INET, new DbPlatformType("inet", false));
dbTypeMap.put(DbType.HSTORE, new DbPlatformType("hstore", false));
dbTypeMap.put(DbType.JSON, new DbPlatformType("json", false));
dbTypeMap.put(DbType.JSONB, new DbPlatformType("jsonb", false));
+2 -2
View File
@@ -1,10 +1,10 @@
<HTML>
<HEAD>
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
<TITLE>Configuration settings for EbeanServer construction</TITLE>
<TITLE>Configuration settings for Database construction</TITLE>
</HEAD>
<Body BGCOLOR="#ffffff">
Configuration settings for EbeanServer construction
Configuration settings for Database construction
</Body>
</HTML>
@@ -97,6 +97,8 @@ class Loader {
if (fileName != null) {
loadWithExtensionCheck(fileName);
}
} else {
loadWithExtensionCheck(fileName);
}
}
@@ -9,7 +9,7 @@ package io.ebean.event;
* <p>
* Note that getTransaction() on the PersistRequest returns the transaction used
* for the insert, update, delete or fetch. To explicitly use this same
* transaction you should use this transaction via methods on EbeanServer.
* transaction you should use this transaction via methods on Database.
* </p>
* <pre>{@code
*
@@ -1,6 +1,6 @@
package io.ebean.event;
import io.ebean.EbeanServer;
import io.ebean.Database;
/**
* Fired after a bean is constructed, but not yet loaded from database.
@@ -9,7 +9,7 @@ import io.ebean.EbeanServer;
* properties will get unload. Use {@link BeanPostLoad} instead.
* <p>
* it's intended to do some dependency-injection here.
* If you plan to use this feature you should use {@link EbeanServer#createEntityBean(Class)}
* If you plan to use this feature you should use {@link Database#createEntityBean(Class)}
* to create new beans.
* </p>
*/
@@ -32,7 +32,7 @@ public interface BeanPostConstructListener {
void postConstruct(Object bean);
/**
* Called after {@link EbeanServer#createEntityBean(Class)}. Only for new beans.
* Called after {@link Database#createEntityBean(Class)}. Only for new beans.
* intended to set default values here.
*/
void postCreate(Object bean);
@@ -3,7 +3,7 @@ package io.ebean.meta;
import java.util.List;
/**
* Provides access to the meta data in EbeanServer such as query execution statistics.
* Provides access to the meta data in Database such as query execution statistics.
*/
public interface MetaInfoManager {
@@ -1,4 +1,4 @@
/**
* Meta data that can be retrieved for the EbeanServer.
* Meta data that can be retrieved for a Database instance.
*/
package io.ebean.meta;
+10 -116
View File
@@ -3,130 +3,24 @@
<title>Ebean API</title>
</head>
<body BGCOLOR="#ffffff">
Ebean Object Relational Mapping (start at
<a href='com/avaje/ebean/EbeanServer.html'>EbeanServer</a> or <a href='com/avaje/ebean/Ebean.html'>Ebean</a>).
Ebean Object Relational Mapping -
<a href='io/ebean/Database.html'>Database</a> or <a href='io/ebean/DB.html'>DB</a>).
<h3>Ebean</h3>
<h4><a href='io/ebean/Database.html'>Database</a></h4>
<p>
Provides the main API for fetching and persisting beans with Ebean.
Database provides the main API for fetching and persisting beans.
</p>
<h4><a href='io/ebean/DB.html'>DB</a></h4>
<p>
For a full description of the query language refer to <a href="com/avaje/ebean/Query.html">Query</a>.
DB holds a registry of Database instances by name.
</p>
<h4><a href='https://ebean.io/docs/query'>Query</a></h4>
<p>
&nbsp;
Review the documentation for the query capabilities.
</p>
<div id="overviewexamples">
<h3>
EXAMPLE 1: Simple fetch
</h3>
<pre>{@code
// fetch order 10
Order order = Ebean.find(Order.class, 10);
}</pre>
<h3>
EXAMPLE 2: Fetch an Object with associations
</h3>
<pre>{@code
// fetch Customer 7 including their billing and shipping addresses
Customer customer = Ebean.find(Customer.class)
.fetch("billingAddress");
.fetch("shippingAddress");
.setId(7)
.findOne();
Address billAddr = customer.getBillingAddress();
Address shipAddr = customer.getShippingAddress();
}</pre>
<h3>
EXAMPLE 3: Fetch a list of Objects with associations
</h3>
<pre>{@code
// Note: This example shows a "Partial Object".
// For the product objects associated with the
// order details only the product id and name is
// fetched (the product objects are partially populated).
// fetch orders for customer.id = 2
List<Order> orderList = Ebean.find(Order.class);
.fetch("customer")
.fetch("customer.shippingAddress")
.fetch("details")
.fetch("details.product","name")
.where().eq("customer.id",2)
.findList();
// Note: Only the product id and name is fetched for the
// product details. This is referred to as a
// "Partial Object" (one that is partially populated).
// code that traverses the object graph...
Order order = orderList.get(0);
Customer customer = order.getCustomer();
Address shipAddr = customer.getShippingAddress();
List<OrderDetail> details = order.getDetails();
OrderDetail detail = details.get(0);
Product product = detail.getProduct();
String productName = product.getName();
}</pre>
<h3>
EXAMPLE 4: Create and save an Order
</h3>
<pre>{@code
// get a Customer reference so we don't hit the database
Customer custRef = Ebean.getReference(Customer.class, 7);
// create a new Order object
Order newOrder = new Order();
newOrder.setStatus(Order.Status.NEW);
newOrder.setCustomer(custRef);
ArrayList orderLines = new ArrayList();
newOrder.setLines(orderLines);
...
// add a line to the order
Product prodRef = Ebean.getReference(Product.class, 41);
OrderLine line = new OrderLine();
line.setProduct(prodRef);
line.setQuantity(10);
orderLines.add(line);
...
// save the order and its lines in a single transaction
// NB: assumes CascadeType.PERSIST is set on the order lines association
Ebean.save(newOrder);
}</pre>
<h3>
EXAMPLE 5: Use another database
</h3>
<pre>{@code
// Get access to the Human Resources EbeanServer/Database
EbeanServer hrServer = Ebean.getServer("HR");
// fetch contact 3 from the HR database
Contact contact = hrServer.find(Contact.class, 3);
contact.setStatus(Contact.Status.INACTIVE);
...
// save the contact back to the HR database
hrServer.save(contact);
}</pre>
</div>
</body>
+22 -60
View File
@@ -3,29 +3,38 @@
<TITLE>Ebean core API</TITLE>
</HEAD>
<Body BGCOLOR="#ffffff">
Core API (see <a href="EbeanServer.html">EbeanServer</a> and <a href="Ebean.html">Ebean</a>).
Core API (see <a href="Database.html">Database</a>, <a href="DB.html">DB</a> and <a href="Query.html">Query</a>).
<h3>Ebean</h3>
<h3>Database</h3>
<p>
Provides the main API for fetching and persisting beans with eBean.
Provides the main API for fetching and persisting beans. We can obtain the "default database"
via <code>DB.getDefault()</code> or just use methods on DB.
</p>
<pre>{@code
// EXAMPLE 1: Simple fetch
//========================
// fetch order 10
Order order = Ebean.find(Order.class, 10);
// Example find by id
Order order = DB.find(Order.class, 10);
// Example save
// EXAMPLE 2: Fetch an Object with associations
//=============================================
Customer customer = DB.getReference(Customer.class, 42);
// fetch Customer 7 including their billing and shipping addresses
Customer customer =
Ebean.find(Customer.class)
.setId(7)
Order newOrder = new Order();
newOrder.setStatus(Order.Status.NEW);
newOrder.setCustomer(customer);
...
DB.save(newOrder);
// Example: Eagerly fetching associations
// fetch Customer 42 including their billing and shipping addresses
Customer customer = DB.find(Customer.class)
.setId(42)
.fetch("billingAddress")
.fetch("shippingAddress")
.findOne();
@@ -33,53 +42,6 @@ Customer customer =
Address billAddr = customer.getBillingAddress();
Address shipAddr = customer.getShippingAddress();
// EXAMPLE 3: Create and save an Order
//=====================================
// get a Customer reference so we don't hit the database
Customer custRef = Ebean.getReference(Customer.class, 7);
// create a new Order object
Order newOrder = new Order();
newOrder.setStatus(Order.Status.NEW);
newOrder.setCustomer(custRef);
ArrayList orderLines = new ArrayList();
newOrder.setLines(orderLines);
...
// add a line to the order
Product prodRef = Ebean.getReference(Product.class, 41);
OrderLine line = new OrderLine();
line.setProduct(prodRef);
line.setQuantity(10);
orderLines.add(line);
...
// save the order and its lines in a single transaction
// NB: assumes CascadeType.PERSIST is set on the order lines association
Ebean.save(newOrder);
// EXAMPLE 4: Use another database
//=================================
// Get access to the Human Resources EbeanServer/Database
EbeanServer hrServer = Ebean.getServer(&quot;HR&quot;);
// fetch contact 3 from the HR database
Contact contact = hrServer.find(Contact.class, 3);
contact.setStatus(Contact.Status.INACTIVE);
...
// save the contact back to the HR database
hrServer.save(contact);
}</pre>
</Body>
+1 -1
View File
@@ -1,7 +1,7 @@
package io.ebean.plugin;
/**
* A 'plugin' that wants to be configured on startup so it can use features of the EbeanServer itself.
* A 'plugin' that wants to be configured on startup so it can use features of the Database itself.
*/
public interface Plugin {
+3 -3
View File
@@ -8,7 +8,7 @@ import javax.sql.DataSource;
import java.util.List;
/**
* Extensions to EbeanServer API made available to plugins.
* Extensions to Database API made available to plugins.
*/
public interface SpiServer extends EbeanServer {
@@ -43,12 +43,12 @@ public interface SpiServer extends EbeanServer {
BeanType<?> getBeanTypeForQueueId(String queueId);
/**
* Return the associated DataSource for this EbeanServer instance.
* Return the associated DataSource for this Database instance.
*/
DataSource getDataSource();
/**
* Return the associated read only DataSource for this EbeanServer instance (can be null).
* Return the associated read only DataSource for this Database instance (can be null).
*/
DataSource getReadOnlyDataSource();
@@ -2,7 +2,7 @@
* Provides a API for plugins.
* <p>
* Plugins can get and read meta data about the entity beans and enhance or utilise the
* functionality of the EbeanServer.
* functionality of the Database.
* </p>
*/
package io.ebean.plugin;
@@ -4,7 +4,7 @@ import io.ebean.EbeanServer;
import io.ebean.config.ServerConfig;
/**
* Creates the EbeanServer implementations. This is used internally by the EbeanServerFactory and is not currently
* Creates the Database implementations. This is used internally by the EbeanServerFactory and is not currently
* exposed as public API.
*/
public interface SpiContainer {
@@ -20,7 +20,7 @@ import java.util.Locale;
*
* FileReader reader = new FileReader(f);
*
* CsvReader&lt;Customer&gt; csvReader = Ebean.createCsvReader(Customer.class);
* CsvReader<Customer> csvReader = DB.createCsvReader(Customer.class);
*
* csvReader.setPersistBatchSize(20);
*
@@ -10,7 +10,7 @@
* <pre>{@code
* // find some customers ...
*
* List<Customer> list = Ebean.find(Customer.class)
* List<Customer> list = DB.find(Customer.class)
* .select("id, name, status, shippingAddress")
* .fetch("billingAddress","line1, city")
* .fetch("billingAddress.country", "*")
@@ -18,7 +18,7 @@
* .order().desc("id")
* .findList();
*
* JsonContext json = Ebean.json();
* JsonContext json = DB.json();
*
* // output as a JSON string
* String jsonOutput = json.toJson(list);
@@ -41,6 +41,14 @@ public class BindParams implements Serializable {
public BindParams() {
}
/**
* Reset positioned parameters (usually due to bind parameter expansion).
*/
public void reset() {
bindHash = null;
positionedParameters.clear();
}
public int queryBindHash() {
int hc = namedParameters.hashCode();
for (Param positionedParameter : positionedParameters) {
@@ -171,8 +179,7 @@ public class BindParams implements Serializable {
}
private Param getParam(String name) {
Param p = namedParameters.computeIfAbsent(name, k -> new Param());
return p;
return namedParameters.computeIfAbsent(name, k -> new Param());
}
private Param getParam(int position) {
@@ -4,6 +4,11 @@ import io.ebean.SqlUpdate;
public interface SpiSqlUpdate extends SqlUpdate {
/**
* Return the sql taking into account bind parameter expansion.
*/
String getBaseSql();
/**
* Return the Bind parameters.
*/
@@ -33,12 +33,12 @@ class LastMigration {
*/
static String lastVersion(File migDirectory, File modelDir) {
List<String> fileNames = new ArrayList<>();
List<MigrationVersion> versions = new ArrayList<>();
File[] sqlFiles = migDirectory.listFiles(pathname -> includeSqlFile(pathname.getName().toLowerCase()));
if (sqlFiles != null) {
for (File file : sqlFiles) {
fileNames.add(trim(file.getName()));
versions.add(trimAndParse(file.getName()));
}
}
@@ -46,14 +46,14 @@ class LastMigration {
File[] xmlFiles = modelDir.listFiles(pathname -> includeModelFile(pathname.getName().toLowerCase()));
if (xmlFiles != null) {
for (File file : xmlFiles) {
fileNames.add(trim(file.getName()));
versions.add(trimAndParse(file.getName()));
}
}
}
Collections.sort(fileNames);
if (!fileNames.isEmpty()) {
return fileNames.get(fileNames.size() - 1);
Collections.sort(versions);
if (!versions.isEmpty()) {
return versions.get(versions.size() - 1).asString();
}
return null;
}
@@ -69,23 +69,14 @@ class LastMigration {
return lowerFileName.endsWith(MODEL_XML);
}
private static String trim(String name) {
name = name.toLowerCase();
char c = name.charAt(0);
if (c == 'v') {
name = name.substring(1);
}
int p = name.indexOf("__");
if (p > -1) {
name = name.substring(0, p);
}
private static MigrationVersion trimAndParse(String name) {
if (name.endsWith(SQL)) {
name = name.substring(0, name.length() - 4);
}
if (name.endsWith(MODEL_XML)) {
name = name.substring(0, name.length() - 10);
}
return name;
return MigrationVersion.parse(name);
}
}
@@ -1083,15 +1083,25 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer {
}
@Override
public SqlQuery createSqlQuery(String sql) {
public SqlQuery sqlQuery(String sql) {
return new DefaultRelationalQuery(this, sql.trim());
}
@Override
public SqlUpdate createSqlUpdate(String sql) {
public SqlQuery createSqlQuery(String sql) {
return sqlQuery(sql);
}
@Override
public SqlUpdate sqlUpdate(String sql) {
return new DefaultSqlUpdate(this, sql.trim());
}
@Override
public SqlUpdate createSqlUpdate(String sql) {
return sqlUpdate(sql);
}
@Override
public CallableSql createCallableSql(String sql) {
return new DefaultCallableSql(this, sql.trim());
@@ -9,6 +9,7 @@ import io.ebeaninternal.api.SpiSqlUpdate;
import io.ebeaninternal.api.SpiTransaction;
import java.io.Serializable;
import java.util.Collection;
/**
* A SQL Update Delete or Insert statement that can be executed. For the times
@@ -35,9 +36,14 @@ public final class DefaultSqlUpdate implements Serializable, SpiSqlUpdate {
private final BindParams bindParams;
/**
* The sql update or delete statement.
* The original sql update or delete statement.
*/
private final String sql;
private final String origSql;
/**
* The sql taking into account bind parameter expansion.
*/
private String baseSql;
/**
* The actual sql with named parameters converted.
@@ -66,6 +72,8 @@ public final class DefaultSqlUpdate implements Serializable, SpiSqlUpdate {
*/
private int addPos;
private int bindExpansion;
private boolean getGeneratedKeys;
private Object generatedKey;
@@ -89,7 +97,8 @@ public final class DefaultSqlUpdate implements Serializable, SpiSqlUpdate {
*/
public DefaultSqlUpdate(SpiEbeanServer server, String sql, BindParams bindParams) {
this.server = server;
this.sql = sql;
this.origSql = sql;
this.baseSql = sql;
this.bindParams = bindParams;
}
@@ -221,11 +230,21 @@ public final class DefaultSqlUpdate implements Serializable, SpiSqlUpdate {
@Override
public void setGeneratedSql(String generatedSql) {
this.generatedSql = generatedSql;
this.baseSql = origSql;
if (bindExpansion > 0) {
bindParams.reset();
bindExpansion = 0;
}
}
@Override
public String getSql() {
return sql;
return origSql;
}
@Override
public String getBaseSql() {
return baseSql;
}
@Override
@@ -253,21 +272,47 @@ public final class DefaultSqlUpdate implements Serializable, SpiSqlUpdate {
return this;
}
private SqlUpdate setParamWithBindExpansion(int position, Collection values, String bindLiteral) {
StringBuilder sqlExpand = new StringBuilder(values.size() * 2);
position = position + bindExpansion;
int offset = 0;
for (Object val : values) {
if (offset > 0) {
sqlExpand.append(",");
}
sqlExpand.append("?");
bindParams.setParameter(position + offset++, val);
}
bindExpansion += (offset - 1);
baseSql = baseSql.replace(bindLiteral, sqlExpand.toString());
return this;
}
@Override
public SqlUpdate setParameter(int position, Object value) {
bindParams.setParameter(position, value);
if (value instanceof Collection) {
String bindLiteral = "?" + position;
int pos = baseSql.indexOf(bindLiteral);
if (pos > -1) {
return setParamWithBindExpansion(position, (Collection) value, bindLiteral);
}
}
bindParams.setParameter(bindExpansion + position, value);
return this;
}
@Override
public SqlUpdate setNull(int position, int jdbcType) {
bindParams.setNullParameter(position, jdbcType);
bindParams.setNullParameter(bindExpansion + position, jdbcType);
return this;
}
@Override
public SqlUpdate setNullParameter(int position, int jdbcType) {
bindParams.setNullParameter(position, jdbcType);
bindParams.setNullParameter(bindExpansion + position, jdbcType);
return this;
}
@@ -27,6 +27,7 @@ import io.ebeaninternal.server.persist.BatchedSqlException;
import io.ebeaninternal.server.persist.DeleteMode;
import io.ebeaninternal.server.persist.Flags;
import io.ebeaninternal.server.persist.PersistExecute;
import io.ebeaninternal.server.persist.SaveManyBeans;
import io.ebeaninternal.server.transaction.BeanPersistIdMap;
import io.ebeanservice.docstore.api.DocStoreUpdate;
import io.ebeanservice.docstore.api.DocStoreUpdateContext;
@@ -174,7 +175,7 @@ public final class PersistRequestBean<T> extends PersistRequest implements BeanP
private int pendingPostUpdateNotify;
/**
* Set to true when post execute has occured (so includes batch flush).
* Set to true when post execute has occurred (so includes batch flush).
*/
private boolean postExecute;
@@ -183,6 +184,11 @@ public final class PersistRequestBean<T> extends PersistRequest implements BeanP
*/
private boolean complete;
/**
* Many to many intersection table changes that are held for later batch processing.
*/
private List<SaveManyBeans> saveManyIntersections;
public PersistRequestBean(SpiEbeanServer server, T bean, Object parentBean, BeanManager<T> mgr, SpiTransaction t,
PersistExecute persistExecute, PersistRequest.Type type, int flags) {
@@ -955,6 +961,13 @@ public final class PersistRequestBean<T> extends PersistRequest implements BeanP
if (isLogSummary()) {
logSummary();
}
saveQueuedManyIntersection();
}
private void saveQueuedManyIntersection() {
if (saveManyIntersections != null) {
saveManyIntersections.forEach(SaveManyBeans::saveIntersectionBatch);
}
}
/**
@@ -1119,6 +1132,7 @@ public final class PersistRequestBean<T> extends PersistRequest implements BeanP
updatedManysOnly = true;
setNotifyCache();
addPostCommitListeners();
saveQueuedManyIntersection();
}
notifyCacheOnComplete();
postUpdateNotify();
@@ -1454,4 +1468,21 @@ public final class PersistRequestBean<T> extends PersistRequest implements BeanP
public String getSelectLastInsertedId() {
return beanDescriptor.getSelectLastInsertedId(publish);
}
/**
* Return true if the intersection table updates should be queued and batched.
*/
public boolean isQueueManyIntersection() {
return !postExecute;
}
/**
* The intersection table updates to the batch executed later on postExecute.
*/
public void addManyIntersection(SaveManyBeans saveManyIntersection) {
if (this.saveManyIntersections == null) {
this.saveManyIntersections = new ArrayList<>();
}
this.saveManyIntersections.add(saveManyIntersection);
}
}
@@ -3,7 +3,10 @@ package io.ebeaninternal.server.core;
import io.ebeaninternal.api.SpiEbeanServer;
import io.ebeaninternal.api.SpiSqlUpdate;
import io.ebeaninternal.api.SpiTransaction;
import io.ebeaninternal.server.lib.util.Str;
import io.ebeaninternal.server.persist.BatchControl;
import io.ebeaninternal.server.persist.PersistExecute;
import io.ebeaninternal.server.persist.TrimLogSql;
/**
* Persist request specifically for CallableSql.
@@ -24,12 +27,12 @@ public final class PersistRequestUpdateSql extends PersistRequest {
private String tableName;
private String description;
private boolean addBatch;
private boolean forceNoBatch;
private boolean batchThisRequest;
public PersistRequestUpdateSql(SpiEbeanServer server, SpiSqlUpdate sqlUpdate,
SpiTransaction t, PersistExecute persistExecute, boolean forceNoBatch) {
@@ -58,6 +61,25 @@ public final class PersistRequestUpdateSql extends PersistRequest {
return executeOrQueue();
}
/**
* Execute using jdbc batch.
*/
public void executeAddBatch() {
this.addBatch = true;
persistExecute.executeSqlUpdate(this);
}
/**
* Add this request to BatchControl to flush later.
*/
public void addToFlushQueue(boolean early) {
BatchControl control = transaction.getBatchControl();
if (control == null) {
control = persistExecute.createBatchControl(transaction);
}
control.addToFlushQueue(this, early);
}
@Override
public int executeNow() {
return persistExecute.executeSqlUpdate(this);
@@ -104,10 +126,9 @@ public final class PersistRequestUpdateSql extends PersistRequest {
* Specify the type of statement executed. Used to automatically register
* with the transaction event.
*/
public void setType(SqlType sqlType, String tableName, String description) {
public void setType(SqlType sqlType, String tableName) {
this.sqlType = sqlType;
this.tableName = tableName;
this.description = description;
}
/**
@@ -117,6 +138,20 @@ public final class PersistRequestUpdateSql extends PersistRequest {
this.bindLog = bindLog;
}
public void startBind(boolean batchThisRequest) {
this.batchThisRequest = batchThisRequest;
super.startBind(batchThisRequest);
}
/**
* Log the sql bind used with jdbc batch.
*/
public void logSqlBatchBind() {
if (transaction.isLogSql()) {
transaction.logSql(Str.add(" -- bind(", bindLog, ")"));
}
}
/**
* Perform post execute processing.
*/
@@ -125,9 +160,8 @@ public final class PersistRequestUpdateSql extends PersistRequest {
if (startNanos > 0) {
persistExecute.collectSqlUpdate(label, startNanos, rowCount);
}
if (transaction.isLogSummary()) {
String m = description + " table[" + tableName + "] rows[" + rowCount + "] bind[" + bindLog + "]";
transaction.logSummary(m);
if (transaction.isLogSql() && !batchThisRequest) {
transaction.logSql(Str.add(TrimLogSql.trim(updateSql.getGeneratedSql()), "; -- bind(", bindLog, ") rows(", String.valueOf(rowCount), ")"));
}
if (updateSql.isAutoTableMod()) {
@@ -103,6 +103,11 @@ public interface Persister {
*/
void visitMetrics(MetricVisitor visitor);
/**
* Execute or queue the update.
*/
void executeOrQueue(SpiSqlUpdate update, SpiTransaction t, boolean queue);
/**
* Add the statement to JDBC batch for later execution via executeBatch.
*/
@@ -1,8 +1,8 @@
package io.ebeaninternal.server.deploy;
import io.ebean.SqlUpdate;
import io.ebeaninternal.api.BindParams;
import io.ebeaninternal.api.SpiEbeanServer;
import io.ebeaninternal.api.SpiSqlUpdate;
import io.ebeaninternal.server.core.DefaultSqlUpdate;
import io.ebeaninternal.server.expression.DefaultExpressionRequest;
import io.ebeaninternal.server.expression.IdInExpression;
@@ -45,7 +45,7 @@ public class IntersectionRow {
values.put(key, value);
}
public SqlUpdate createInsert(SpiEbeanServer server) {
public SpiSqlUpdate createInsert(SpiEbeanServer server) {
BindParams bindParams = new BindParams();
@@ -73,7 +73,7 @@ public class IntersectionRow {
return new DefaultSqlUpdate(server, sb.toString(), bindParams);
}
public SqlUpdate createDelete(SpiEbeanServer server, DeleteMode deleteMode) {
public SpiSqlUpdate createDelete(SpiEbeanServer server, DeleteMode deleteMode) {
BindParams bindParams = new BindParams();
@@ -108,7 +108,7 @@ public class IntersectionRow {
return new DefaultSqlUpdate(server, sb.toString(), bindParams);
}
public SqlUpdate createDeleteChildren(SpiEbeanServer server) {
public SpiSqlUpdate createDeleteChildren(SpiEbeanServer server) {
BindParams bindParams = new BindParams();
@@ -162,6 +162,11 @@ public class DefaultExpressionFactory implements SpiExpressionFactory {
return new SimpleExpression(propertyName, Op.EQ, value);
}
@Override
public Expression eqOrNull(String propertyName, Object value) {
return or(eq(propertyName, value), isNull(propertyName));
}
/**
* Not Equal To - property not equal to the given value.
*/
@@ -221,6 +226,11 @@ public class DefaultExpressionFactory implements SpiExpressionFactory {
return new InRangeExpression(propertyName, value1, value2);
}
@Override
public Expression inRangeWith(String lowProperty, String highProperty, Object value) {
return and(le(lowProperty, value), gtOrNull(highProperty, value));
}
/**
* Between - property between the two given values.
*/
@@ -245,6 +255,14 @@ public class DefaultExpressionFactory implements SpiExpressionFactory {
return new SimpleExpression(propertyName, Op.GT, value);
}
/**
* Greater Than or null - property greater than the given value or null.
*/
@Override
public Expression gtOrNull(String propertyName, Object value) {
return or(gt(propertyName, value), isNull(propertyName));
}
/**
* Greater Than or Equal to - property greater than or equal to the given
* value.
@@ -254,6 +272,14 @@ public class DefaultExpressionFactory implements SpiExpressionFactory {
return new SimpleExpression(propertyName, Op.GT_EQ, value);
}
/**
* Less Than or null - property less than the given value or null.
*/
@Override
public Expression ltOrNull(String propertyName, Object value) {
return or(lt(propertyName, value), isNull(propertyName));
}
/**
* Less Than - property less than the given value.
*/
@@ -429,6 +455,16 @@ public class DefaultExpressionFactory implements SpiExpressionFactory {
return new InExpression(propertyName, values, false);
}
/**
* In where null or empty values means that no predicate is added to the query.
* <p>
* That is, only add the IN predicate if the values are not null or empty.
*/
@Override
public Expression inOrEmpty(String propertyName, Collection<?> values) {
return new InExpression(propertyName, values, false, true);
}
/**
* In - property has a value in the array of values.
*/
@@ -529,7 +565,7 @@ public class DefaultExpressionFactory implements SpiExpressionFactory {
*/
@Override
public Expression raw(String raw, Object value) {
return new RawExpression(raw, new Object[]{value});
return RawExpressionBuilder.buildSingle(raw, value);
}
/**
@@ -541,7 +577,7 @@ public class DefaultExpressionFactory implements SpiExpressionFactory {
*/
@Override
public Expression raw(String raw, Object[] values) {
return new RawExpression(raw, values);
return RawExpressionBuilder.build(raw, values);
}
/**
@@ -764,6 +764,12 @@ public class DefaultExpressionList<T> implements SpiExpressionList<T> {
return this;
}
@Override
public ExpressionList<T> eqOrNull(String propertyName, Object value) {
add(expr.eqOrNull(propertyName, value));
return this;
}
@Override
public ExpressionList<T> ieq(String propertyName, String value) {
add(expr.ieq(propertyName, value));
@@ -794,6 +800,12 @@ public class DefaultExpressionList<T> implements SpiExpressionList<T> {
return this;
}
@Override
public ExpressionList<T> inRangeWith(String lowProperty, String highProperty, Object value) {
add(expr.inRangeWith(lowProperty, highProperty, value));
return this;
}
@Override
public ExpressionList<T> inRange(String propertyName, Object value1, Object value2) {
add(expr.inRange(propertyName, value1, value2));
@@ -836,6 +848,12 @@ public class DefaultExpressionList<T> implements SpiExpressionList<T> {
return this;
}
@Override
public ExpressionList<T> gtOrNull(String propertyName, Object value) {
add(expr.gtOrNull(propertyName, value));
return this;
}
@Override
public ExpressionList<T> icontains(String propertyName, String value) {
add(expr.icontains(propertyName, value));
@@ -894,6 +912,14 @@ public class DefaultExpressionList<T> implements SpiExpressionList<T> {
return this;
}
@Override
public ExpressionList<T> inOrEmpty(String propertyName, Collection<?> values) {
if (notEmpty(values)) {
add(expr.in(propertyName, values));
}
return this;
}
@Override
public ExpressionList<T> in(String propertyName, Object... values) {
add(expr.in(propertyName, values));
@@ -990,6 +1016,12 @@ public class DefaultExpressionList<T> implements SpiExpressionList<T> {
return this;
}
@Override
public ExpressionList<T> ltOrNull(String propertyName, Object value) {
add(expr.ltOrNull(propertyName, value));
return this;
}
@Override
public ExpressionList<T> not(Expression exp) {
add(expr.not(exp));
@@ -1044,6 +1076,18 @@ public class DefaultExpressionList<T> implements SpiExpressionList<T> {
return this;
}
@Override
public ExpressionList<T> rawOrEmpty(String raw, Collection<?> values) {
if (notEmpty(values)) {
add(expr.raw(raw, values));
}
return this;
}
private boolean notEmpty(Collection<?> values) {
return values != null && !values.isEmpty();
}
@Override
public ExpressionList<T> startsWith(String propertyName, String value) {
add(expr.startsWith(propertyName, value));
@@ -17,8 +17,16 @@ import java.util.List;
class InExpression extends AbstractExpression {
private static final String SQL_TRUE = "1=1";
private static final String SQL_FALSE = "1=0";
private final boolean not;
/**
* Set to true when adding "1=1" predicate (due to null or empty sourceValues).
*/
private final boolean empty;
private final Collection<?> sourceValues;
private List<Object> bindValues;
@@ -26,18 +34,27 @@ class InExpression extends AbstractExpression {
private boolean multiValueSupported;
InExpression(String propertyName, Collection<?> sourceValues, boolean not) {
this(propertyName, sourceValues, not, false);
}
InExpression(String propertyName, Collection<?> sourceValues, boolean not, boolean orEmpty) {
super(propertyName);
this.sourceValues = sourceValues;
this.not = not;
this.empty = orEmpty && (sourceValues == null || sourceValues.isEmpty());
}
InExpression(String propertyName, Object[] array, boolean not) {
super(propertyName);
this.sourceValues = Arrays.asList(array);
this.not = not;
this.empty = false;
}
private List<Object> values() {
if (empty || sourceValues == null) {
return Collections.emptyList();
}
List<Object> vals = new ArrayList<>(sourceValues.size());
for (Object sourceValue : sourceValues) {
assert sourceValue != null : "null is not allowed in in-queries";
@@ -48,8 +65,8 @@ class InExpression extends AbstractExpression {
@Override
public boolean naturalKey(NaturalKeyQueryData<?> data) {
// can't use naturalKey cache for NOT IN
if (not) {
// can't use naturalKey cache for NOT IN or when "empty"
if (not || empty) {
return false;
}
List<Object> copy = data.matchIn(propName, bindValues);
@@ -70,11 +87,16 @@ class InExpression extends AbstractExpression {
@Override
public void writeDocQuery(DocQueryContext context) throws IOException {
context.writeIn(propName, values().toArray(), not);
if (!empty) {
context.writeIn(propName, values().toArray(), not);
}
}
@Override
public void addBindValues(SpiExpressionRequest request) {
if (empty) {
return;
}
for (Object value : bindValues) {
if (value == null) {
throw new NullPointerException("null values in 'in(...)' queries must be handled separately!");
@@ -108,10 +130,12 @@ class InExpression extends AbstractExpression {
@Override
public void addSql(SpiExpressionRequest request) {
if (empty) {
request.append(SQL_TRUE);
return;
}
if (bindValues.isEmpty()) {
String expr = not ? "1=1" : "1=0";
request.append(expr);
request.append(not ? SQL_TRUE : SQL_FALSE);
return;
}
@@ -142,10 +166,14 @@ class InExpression extends AbstractExpression {
builder.append("In[");
}
builder.append(propName);
builder.append(" ?");
if (!multiValueSupported) {
// query plan specific to the number of parameters in the IN clause
builder.append(bindValues.size());
if (empty) {
builder.append("empty");
} else {
builder.append(" ?");
if (!multiValueSupported) {
// query plan specific to the number of parameters in the IN clause
builder.append(bindValues.size());
}
}
builder.append("]");
}
@@ -280,6 +280,11 @@ class JunctionExpression<T> implements SpiJunction<T>, SpiExpression, Expression
return exprList.and(expOne, expTwo);
}
@Override
public ExpressionList<T> inRangeWith(String lowProperty, String highProperty, Object value) {
return exprList.inRangeWith(lowProperty, highProperty, value);
}
@Override
public ExpressionList<T> inRange(String propertyName, Object value1, Object value2) {
return exprList.inRange(propertyName, value1, value2);
@@ -310,6 +315,11 @@ class JunctionExpression<T> implements SpiJunction<T>, SpiExpression, Expression
return exprList.eq(propertyName, value);
}
@Override
public ExpressionList<T> eqOrNull(String propertyName, Object value) {
return exprList.eqOrNull(propertyName, value);
}
@Override
public ExpressionList<T> exampleLike(Object example) {
return exprList.exampleLike(example);
@@ -597,6 +607,11 @@ class JunctionExpression<T> implements SpiJunction<T>, SpiExpression, Expression
return exprList.gt(propertyName, value);
}
@Override
public ExpressionList<T> gtOrNull(String propertyName, Object value) {
return exprList.gtOrNull(propertyName, value);
}
@Override
public ExpressionList<T> having() {
throw new IllegalStateException("having() not allowed on Junction expression list");
@@ -657,6 +672,11 @@ class JunctionExpression<T> implements SpiJunction<T>, SpiExpression, Expression
return exprList.in(propertyName, values);
}
@Override
public ExpressionList<T> inOrEmpty(String propertyName, Collection<?> values) {
return exprList.inOrEmpty(propertyName, values);
}
@Override
public ExpressionList<T> in(String propertyName, Object... values) {
return exprList.in(propertyName, values);
@@ -732,6 +752,11 @@ class JunctionExpression<T> implements SpiJunction<T>, SpiExpression, Expression
return exprList.lt(propertyName, value);
}
@Override
public ExpressionList<T> ltOrNull(String propertyName, Object value) {
return exprList.ltOrNull(propertyName, value);
}
@Override
public ExpressionList<T> ne(String propertyName, Object value) {
return exprList.ne(propertyName, value);
@@ -782,6 +807,11 @@ class JunctionExpression<T> implements SpiJunction<T>, SpiExpression, Expression
return exprList.raw(raw, values);
}
@Override
public ExpressionList<T> rawOrEmpty(String raw, Collection<?> values) {
return exprList.rawOrEmpty(raw, values);
}
@Override
public ExpressionList<T> raw(String raw) {
return exprList.raw(raw);
@@ -12,9 +12,9 @@ import java.util.Collection;
class RawExpression extends NonPrepareExpression {
private final String sql;
final String sql;
private final Object[] values;
final Object[] values;
RawExpression(String sql, Object[] values) {
this.sql = sql;
@@ -0,0 +1,86 @@
package io.ebeaninternal.server.expression;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
class RawExpressionBuilder {
private static final String BP_1 = "?1";
private static final String[] BP = {BP_1, "?2", "?3", "?4", "?5", "?6", "?7", "?8",
"?9", "?10", "?11", "?12", "?13", "?14", "?15", "?16", "?17", "?18", "?19", "?20"};
/**
* Build RawExpression taking into account parameter expansion.
*/
static RawExpression buildSingle(String raw, Object value) {
if (isExpand(value, raw, BP_1)) {
Collection val = (Collection) value;
raw = raw.replace(BP_1, expand(val));
return new RawExpression(raw, val.toArray());
}
return new RawExpression(raw, new Object[]{value});
}
/**
* Build RawExpression for multiple bind values taking into account parameter expansion.
*/
static RawExpression build(String raw, Object[] values) {
for (int i = 0; i < values.length; i++) {
if (isExpand(values[i], raw, match(i))) {
return new RawExpressionBuilder(raw, values).build();
}
}
return new RawExpression(raw, values);
}
/**
* Return true if this value is a collection that should be expanded.
*/
private static boolean isExpand(Object value, String raw, String bindMatch) {
return value instanceof Collection && raw.contains(bindMatch);
}
private static String match(int i) {
if (i < 20) {
return BP[i];
}
return "?" + (i + 1);
}
private static String expand(Collection values) {
StringBuilder sqlExpand = new StringBuilder(values.size() * 2);
for (int i = 0; i < values.size(); i++) {
if (i > 0) {
sqlExpand.append(",");
}
sqlExpand.append("?");
}
return sqlExpand.toString();
}
private final String expanded;
private final List<Object> params = new ArrayList<>();
private RawExpressionBuilder(String raw, Object[] values) {
for (int i = 0; i < values.length; i++) {
String match = match(i);
if (!isExpand(values[i], raw, match)) {
params.add(values[i]);
} else {
Collection val = (Collection) values[i];
params.addAll(val);
raw = raw.replace(match, expand(val));
}
}
this.expanded = raw;
}
private RawExpression build() {
return new RawExpression(expanded, params.toArray());
}
}
@@ -15,14 +15,16 @@ public class Str {
// determine a decent buffer size
int len = 16 + s0.length() + s1.length();
for (String arg1 : args) {
len += arg1.length();
len += (arg1 == null) ? 0 : arg1.length();
}
// append all the strings into the buffer
StringBuilder sb = new StringBuilder(len);
sb.append(s0).append(s1);
for (String arg : args) {
sb.append(arg);
if (arg != null) {
sb.append(arg);
}
}
return sb.toString();
}
@@ -3,6 +3,7 @@ package io.ebeaninternal.server.persist;
import io.ebeaninternal.api.SpiTransaction;
import io.ebeaninternal.server.core.PersistRequest;
import io.ebeaninternal.server.core.PersistRequestBean;
import io.ebeaninternal.server.core.PersistRequestUpdateSql;
import io.ebeaninternal.server.deploy.BeanDescriptor;
import io.ebeaninternal.server.deploy.BeanPropertyAssocOne;
@@ -10,6 +11,7 @@ import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Controls the batch ordering of persist requests.
@@ -67,6 +69,10 @@ public final class BatchControl {
* Size of the largest buffer.
*/
private int bufferMax;
private int topCounter;
private Queue earlyQueue;
private Queue lateQueue;
/**
* Create for a given transaction, PersistExecute, default size and getGeneratedKeys.
@@ -224,14 +230,14 @@ public final class BatchControl {
* Flush without resetting the topOrder (maintains the depth info).
*/
public void flush() throws BatchedSqlException {
flush(false);
flushBuffer(false);
}
/**
* Flush with a reset the topOrder (fully empty the batch).
*/
public void flushReset() throws BatchedSqlException {
flush(true);
flushBuffer(true);
}
/**
@@ -241,12 +247,25 @@ public final class BatchControl {
pstmtHolder.clear();
beanHoldMap.clear();
maxDepth = 0;
topCounter = 0;
}
private void flushBuffer(boolean resetTop) throws BatchedSqlException {
flushInternal(resetTop);
flushQueue(earlyQueue);
flushQueue(lateQueue);
}
private void flushQueue(Queue queue) throws BatchedSqlException {
if (queue != null && queue.flush() && !pstmtHolder.isEmpty()) {
flushPstmtHolder();
}
}
/**
* execute all the requests currently queued or batched.
*/
private void flush(boolean resetTop) throws BatchedSqlException {
private void flushInternal(boolean resetTop) throws BatchedSqlException {
try {
bufferMax = 0;
@@ -302,10 +321,8 @@ public final class BatchControl {
if (maybe != -1) {
beanDepth = maybe;
} else {
// we can't be certain of the relative ordering for this type so
// flush and reset the batch as we are changing the type of our top level
// bean so just keep it simple and flush and reset the top
flushReset();
// additional "top level" bean type ordered by save() order
beanDepth += ++topCounter;
}
}
@@ -367,4 +384,43 @@ public final class BatchControl {
public int[] execute(String key, boolean getGeneratedKeys) throws SQLException {
return pstmtHolder.execute(key, getGeneratedKeys);
}
/**
* Add a SqlUpdate request to execute after flush.
*/
public void addToFlushQueue(PersistRequestUpdateSql request, boolean early) {
if (early) {
// add it to the early queue
if (earlyQueue == null) {
earlyQueue = new Queue();
}
earlyQueue.add(request);
} else {
// add it to the late queue
if (lateQueue == null) {
lateQueue = new Queue();
}
lateQueue.add(request);
}
}
private static class Queue {
private final List<PersistRequestUpdateSql> queue = new ArrayList<>();
boolean flush() {
if (queue.isEmpty()) {
return false;
}
for (PersistRequestUpdateSql request : queue) {
request.executeAddBatch();
}
queue.clear();
return true;
}
void add(PersistRequestUpdateSql request) {
queue.add(request);
}
}
}
@@ -9,6 +9,7 @@ import io.ebeaninternal.server.expression.platform.DbExpressionHandler;
import io.ebeaninternal.server.persist.platform.MultiValueBind;
import io.ebeaninternal.server.type.DataBind;
import io.ebeaninternal.server.type.DataReader;
import io.ebeaninternal.server.type.PostgresHelper;
import io.ebeaninternal.server.type.RsetDataReader;
import io.ebeaninternal.server.type.ScalarType;
import io.ebeaninternal.server.type.TypeManager;
@@ -374,6 +375,11 @@ public class Binder {
b.setObject(data);
break;
case DbPlatformType.INET:
// data is always a String at this point
b.setObject(PostgresHelper.asInet(data.toString()));
break;
case java.sql.Types.OTHER:
b.setObject(data, dataType);
break;
@@ -141,12 +141,24 @@ public final class DefaultPersister implements Persister {
}
}
@Override
public void executeOrQueue(SpiSqlUpdate update, SpiTransaction t, boolean queue) {
if (queue) {
addToFlushQueue(update, t, false);
} else {
executeSqlUpdate(update, t);
}
}
private void addToFlushQueue(SpiSqlUpdate update, SpiTransaction t, boolean early) {
new PersistRequestUpdateSql(server, update, t, persistExecute).addToFlushQueue(early);
}
/**
* Execute the updateSql.
*/
@Override
public int executeSqlUpdate(SqlUpdate updSql, Transaction t) {
return executeOrQueue(new PersistRequestUpdateSql(server, (SpiSqlUpdate) updSql, (SpiTransaction) t, persistExecute));
}
@@ -958,12 +970,19 @@ public final class DefaultPersister implements Persister {
}
}
void deleteAssocManyIntersection(EntityBean bean, BeanPropertyAssocMany<?> many, Transaction t, boolean publish) {
void deleteManyIntersection(EntityBean bean, BeanPropertyAssocMany<?> many, SpiTransaction t, boolean publish, boolean queue) {
// delete all intersection rows for this bean
SpiSqlUpdate sqlDelete = deleteAllIntersection(bean, many, publish);
if (queue) {
addToFlushQueue(sqlDelete, t, true);
} else {
executeSqlUpdate(sqlDelete, t);
}
}
private SpiSqlUpdate deleteAllIntersection(EntityBean bean, BeanPropertyAssocMany<?> many, boolean publish) {
IntersectionRow intRow = many.buildManyToManyDeleteChildren(bean, publish);
SqlUpdate sqlDelete = intRow.createDeleteChildren(server);
executeSqlUpdate(sqlDelete, t);
return intRow.createDeleteChildren(server);
}
/**
@@ -1012,7 +1031,7 @@ public final class DefaultPersister implements Persister {
if (many.hasJoinTable()) {
if (deleteMode.isHard()) {
// delete associated rows from intersection table (but not during soft delete)
deleteAssocManyIntersection(parentBean, many, t, request.isPublish());
deleteManyIntersection(parentBean, many, t, request.isPublish(), false);
}
} else {
@@ -87,23 +87,16 @@ class ExeUpdateSql {
SpiSqlUpdate updateSql = request.getUpdateSql();
SpiTransaction t = request.getTransaction();
String sql = updateSql.getSql();
BindParams bindParams = updateSql.getBindParams();
// process named parameters if required
String sql = updateSql.getBaseSql();
sql = BindParamsParser.parse(bindParams, sql);
updateSql.setGeneratedSql(sql);
boolean logSql = request.isLogSql();
PreparedStatement pstmt;
if (batchThisRequest) {
pstmt = pstmtFactory.getPstmt(t, logSql, sql, request);
pstmt = pstmtFactory.getPstmt(t, request.isLogSql(), sql, request);
} else {
if (logSql) {
t.logSql(TrimLogSql.trim(sql));
}
pstmt = pstmtFactory.getPstmt(t, sql, request.isGetGeneratedKeys());
}
@@ -117,9 +110,13 @@ class ExeUpdateSql {
}
request.setBindLog(bindLog);
updateSql.setGeneratedSql(sql);
// derive the statement type (for TransactionEvent)
parseUpdate(sql, request);
if (batchThisRequest) {
request.logSqlBatchBind();
}
return pstmt;
}
@@ -127,16 +124,16 @@ class ExeUpdateSql {
private void determineType(String word1, String word2, String word3, PersistRequestUpdateSql request) {
if (word1.equalsIgnoreCase("UPDATE")) {
request.setType(SqlType.SQL_UPDATE, word2, "UpdateSql");
request.setType(SqlType.SQL_UPDATE, word2);
} else if (word1.equalsIgnoreCase("DELETE")) {
request.setType(SqlType.SQL_DELETE, word3, "DeleteSql");
request.setType(SqlType.SQL_DELETE, word3);
} else if (word1.equalsIgnoreCase("INSERT")) {
request.setType(SqlType.SQL_INSERT, word3, "InsertSql");
request.setType(SqlType.SQL_INSERT, word3);
} else {
request.setType(SqlType.SQL_UNKNOWN, null, "UnknownSql");
request.setType(SqlType.SQL_UNKNOWN, null);
}
}
@@ -160,7 +157,7 @@ class ExeUpdateSql {
if (spaceCount < 2) {
// unknown so no automatic L2 cache invalidation performed (so it should instead)
// be done explicitly via the server.externalModification() method
request.setType(SqlType.SQL_UNKNOWN, null, "UnknownSql");
request.setType(SqlType.SQL_UNKNOWN, null);
} else {
// try to determine if it is insert, update or delete and the table involved
@@ -1,9 +1,9 @@
package io.ebeaninternal.server.persist;
import io.ebean.SqlUpdate;
import io.ebean.bean.BeanCollection;
import io.ebean.bean.EntityBean;
import io.ebean.bean.EntityBeanIntercept;
import io.ebeaninternal.api.SpiSqlUpdate;
import io.ebeaninternal.server.core.PersistRequest;
import io.ebeaninternal.server.core.PersistRequestBean;
import io.ebeaninternal.server.deploy.BeanCollectionUtil;
@@ -24,7 +24,7 @@ import java.util.Set;
/**
* Saves the details for a OneToMany or ManyToMany relationship (entity beans).
*/
class SaveManyBeans extends SaveManyBase {
public class SaveManyBeans extends SaveManyBase {
private static final Logger log = LoggerFactory.getLogger(SaveManyBeans.class);
@@ -244,14 +244,29 @@ class SaveManyBeans extends SaveManyBase {
if (value == null) {
return;
}
if (request.isQueueManyIntersection()) {
// queue/delay until bean persist request is flushed
this.deleteMissing = deleteMissingChildren;
request.addManyIntersection(this);
} else {
saveAssocManyIntersection(deleteMissingChildren, false);
}
}
/**
* Push intersection table changes onto batch flush queue.
*/
public void saveIntersectionBatch() {
saveAssocManyIntersection(deleteMissing, true);
}
private void saveAssocManyIntersection(boolean deleteMissingChildren, boolean queue) {
//SpiTransaction t = saveManyPropRequest.getTransaction();
boolean vanillaCollection = !(value instanceof BeanCollection<?>);
if (vanillaCollection || deleteMissingChildren) {
// delete all intersection rows and then treat all
// beans in the collection as additions
persister.deleteAssocManyIntersection(parentBean, many, transaction, publish);
persister.deleteManyIntersection(parentBean, many, transaction, publish, queue);
}
Collection<?> deletions = null;
@@ -287,10 +302,6 @@ class SaveManyBeans extends SaveManyBase {
transaction.depth(+1);
if (additions != null && !additions.isEmpty()) {
// ensure any cascade batch has been flushed prior
// to inserting into the intersection table
transaction.flushBatch();
for (Object other : additions) {
EntityBean otherBean = (EntityBean) other;
// the object from the 'other' side of the ManyToMany
@@ -309,24 +320,20 @@ class SaveManyBeans extends SaveManyBase {
} else {
// build a intersection row for 'insert'
IntersectionRow intRow = many.buildManyToManyMapBean(parentBean, otherBean, publish);
SqlUpdate sqlInsert = intRow.createInsert(server);
persister.executeSqlUpdate(sqlInsert, transaction);
SpiSqlUpdate sqlInsert = intRow.createInsert(server);
persister.executeOrQueue(sqlInsert, transaction, queue);
}
}
}
}
if (deletions != null && !deletions.isEmpty()) {
// ensure any cascade batch has been flushed prior
// to inserting into the intersection table
transaction.flushBatch();
for (Object other : deletions) {
EntityBean otherDelete = (EntityBean) other;
// the object from the 'other' side of the ManyToMany
// build a intersection row for 'delete'
IntersectionRow intRow = many.buildManyToManyMapBean(parentBean, otherDelete, publish);
SqlUpdate sqlDelete = intRow.createDelete(server, DeleteMode.HARD);
persister.executeSqlUpdate(sqlDelete, transaction);
SpiSqlUpdate sqlDelete = intRow.createDelete(server, DeleteMode.HARD);
persister.executeOrQueue(sqlDelete, transaction, queue);
}
}
@@ -82,8 +82,8 @@ abstract class AbstractMultiValueBind extends MultiValueBind {
//case NCLOB:
case NCHAR:
case NVARCHAR:
return "varchar";
case ExtraDbTypes.UUID: // Db Native UUID
case ExtraDbTypes.UUID: // Postgres cast to uuid[]
case ExtraDbTypes.INET: // Postgres cast to inet[]
return "varchar";
default:
@@ -14,6 +14,9 @@ public class PostgresMultiValueBind extends AbstractMultiValueBind {
if (dbType == ExtraDbTypes.UUID) {
return (not) ? " != all(?::uuid[])" : " = any(?::uuid[])";
}
if (dbType == ExtraDbTypes.INET) {
return (not) ? " != all(?::inet[])" : " = any(?::inet[])";
}
String arrayType = getArrayType(dbType);
if (arrayType == null) {
return super.getInExpression(not, type, size);
@@ -334,6 +334,24 @@ public final class ConvertInetAddresses {
return ip.getHostAddress();
}
/**
* Return the host address without the square brackets around IPv6 addresses.
*/
public static String toHostAddress(InetAddress ip) {
return ip.getHostAddress();
}
/**
* Parse the IPv4 or IPv6 address without quare brackets around IPv6 addresses.
*/
public static InetAddress fromHost(String hostAddr) {
if (hostAddr.startsWith("[")) {
// IPv6 address
hostAddr = hostAddr.substring(1, hostAddr.length() - 1);
}
return forString(hostAddr);
}
/**
* Returns an InetAddress representing the literal IPv4 or IPv6 host
* portion of a URL, encoded in the format specified by RFC 3986 section 3.2.2.
@@ -14,6 +14,8 @@ import io.ebean.config.ScalarTypeConverter;
import io.ebean.config.ServerConfig;
import io.ebean.config.dbplatform.DatabasePlatform;
import io.ebean.config.dbplatform.DbPlatformType;
import io.ebean.types.Cdir;
import io.ebean.types.Inet;
import io.ebean.util.AnnotationUtil;
import io.ebeaninternal.api.ExtraTypeFactory;
import io.ebeaninternal.dbmigration.DbOffline;
@@ -37,6 +39,8 @@ import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
@@ -128,7 +132,6 @@ public final class DefaultTypeManager implements TypeManager {
private final ScalarType<?> dateType = new ScalarTypeDate();
private final ScalarType<?> inetAddressType = new ScalarTypeInetAddress();
private final ScalarType<?> urlType = new ScalarTypeURL();
private final ScalarType<?> uriType = new ScalarTypeURI();
private final ScalarType<?> localeType = new ScalarTypeLocale();
@@ -660,11 +663,10 @@ public final class DefaultTypeManager implements TypeManager {
DbEnumValue dbValue = AnnotationUtil.findAnnotation(method, DbEnumValue.class);
if (dbValue != null) {
boolean integerValues = DbEnumType.INTEGER == dbValue.storage();
return createEnumScalarTypeDbValue(enumType, method, integerValues);
return createEnumScalarTypeDbValue(enumType, method, integerValues, dbValue.length());
}
}
// look for EnumValue annotations instead
return createEnumScalarType2(enumType);
}
@@ -675,7 +677,7 @@ public final class DefaultTypeManager implements TypeManager {
* Return null if the EnumValue annotations are not present/used.
* </p>
*/
private ScalarTypeEnum<?> createEnumScalarTypeDbValue(Class<? extends Enum<?>> enumType, Method method, boolean integerType) {
private ScalarTypeEnum<?> createEnumScalarTypeDbValue(Class<? extends Enum<?>> enumType, Method method, boolean integerType, int length) {
Map<String, String> nameValueMap = new LinkedHashMap<>();
@@ -693,7 +695,7 @@ public final class DefaultTypeManager implements TypeManager {
return null;
}
return createEnumScalarType(enumType, nameValueMap, integerType, 0);
return createEnumScalarType(enumType, nameValueMap, integerType, length);
}
/**
@@ -975,8 +977,21 @@ public final class DefaultTypeManager implements TypeManager {
addType(UUID.class, uuidType);
}
if (offlineMigrationGeneration || (postgres && !config.getPlatformConfig().isDatabaseInetAddressVarchar())) {
addInetAddressType(new ScalarTypeInetAddressPostgres());
} else {
addInetAddressType(new ScalarTypeInetAddress());
}
if (offlineMigrationGeneration || postgres) {
addType(Cdir.class, new ScalarTypeCdir.Postgres());
addType(Inet.class, new ScalarTypeInet.Postgres());
} else {
addType(Cdir.class, new ScalarTypeCdir.Varchar());
addType(Inet.class, new ScalarTypeInet.Varchar());
}
addType(File.class, fileType);
addType(InetAddress.class, inetAddressType);
addType(Locale.class, localeType);
addType(Currency.class, currencyType);
addType(TimeZone.class, timeZoneType);
@@ -1063,4 +1078,10 @@ public final class DefaultTypeManager implements TypeManager {
nativeMap.put(Types.TIMESTAMP, timestampType);
}
private void addInetAddressType(ScalarType scalarType) {
addType(InetAddress.class, scalarType);
addType(Inet4Address.class, scalarType);
addType(Inet6Address.class, scalarType);
}
}
@@ -16,6 +16,12 @@ public class PostgresHelper {
*/
public static final String JSONB_TYPE = "jsonb";
public static final String INET_TYPE = "inet";
public static Object asInet(String value) throws SQLException {
return asObject(INET_TYPE, value);
}
/**
* Construct and return Postgres specific PG object.
*/
@@ -0,0 +1,30 @@
package io.ebeaninternal.server.type;
import io.ebeanservice.docstore.api.mapping.DocPropertyType;
import java.sql.Array;
import java.sql.SQLException;
abstract class ScalarTypeArrayBase<T> extends ScalarTypeJsonCollection<T> {
ScalarTypeArrayBase(Class<T> type, int dbType, DocPropertyType docPropertyType) {
super(type, dbType, docPropertyType);
}
@Override
public T read(DataReader reader) throws SQLException {
Array array = reader.getArray();
if (array == null) {
return null;
} else {
try {
return fromArray((Object[]) array.getArray());
} finally {
array.free();
}
}
}
protected abstract T fromArray(Object[] array1);
}
@@ -11,7 +11,6 @@ import io.ebeanservice.docstore.api.mapping.DocPropertyType;
import javax.persistence.PersistenceException;
import java.io.IOException;
import java.lang.reflect.Type;
import java.sql.Array;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
@@ -22,7 +21,7 @@ import java.util.UUID;
* Type mapped for DB ARRAY type (Postgres only effectively).
*/
@SuppressWarnings("rawtypes")
public class ScalarTypeArrayList extends ScalarTypeJsonCollection<List> implements ScalarTypeArray {
public class ScalarTypeArrayList extends ScalarTypeArrayBase<List> implements ScalarTypeArray {
private static ScalarTypeArrayList UUID = new ScalarTypeArrayList("uuid", DocPropertyType.UUID, ArrayElementConverter.UUID);
private static ScalarTypeArrayList LONG = new ScalarTypeArrayList("bigint", DocPropertyType.LONG, ArrayElementConverter.LONG);
@@ -101,7 +100,8 @@ public class ScalarTypeArrayList extends ScalarTypeJsonCollection<List> implemen
}
@SuppressWarnings("unchecked")
private List fromArray(Object[] array1) {
@Override
protected List fromArray(Object[] array1) {
List list = new ArrayList(array1.length);
for (Object element : array1) {
list.add(converter.toElement(element));
@@ -113,16 +113,6 @@ public class ScalarTypeArrayList extends ScalarTypeJsonCollection<List> implemen
return converter.toDbArray(value.toArray());
}
@Override
public List read(DataReader reader) throws SQLException {
Array array = reader.getArray();
if (array == null) {
return null;
} else {
return fromArray((Object[]) array.getArray());
}
}
@Override
public void bind(DataBind bind, List value) throws SQLException {
if (value == null) {
@@ -11,7 +11,6 @@ import io.ebeanservice.docstore.api.mapping.DocPropertyType;
import javax.persistence.PersistenceException;
import java.io.IOException;
import java.lang.reflect.Type;
import java.sql.Array;
import java.sql.SQLException;
import java.sql.Types;
import java.util.LinkedHashSet;
@@ -21,7 +20,7 @@ import java.util.UUID;
/**
* Type mapped for DB ARRAY type (Postgres only effectively).
*/
public class ScalarTypeArraySet<T> extends ScalarTypeJsonCollection<Set<T>> implements ScalarTypeArray {
public class ScalarTypeArraySet<T> extends ScalarTypeArrayBase<Set<T>> implements ScalarTypeArray {
private static final ScalarTypeArraySet<UUID> UUID = new ScalarTypeArraySet<>("uuid", DocPropertyType.UUID, ArrayElementConverter.UUID);
private static final ScalarTypeArraySet<Long> LONG = new ScalarTypeArraySet<>("bigint", DocPropertyType.LONG, ArrayElementConverter.LONG);
@@ -100,7 +99,8 @@ public class ScalarTypeArraySet<T> extends ScalarTypeJsonCollection<Set<T>> impl
return arrayType + "[]";
}
private Set<T> fromArray(Object[] array1) {
@Override
protected Set<T> fromArray(Object[] array1) {
Set<T> set = new LinkedHashSet<>();
for (Object element : array1) {
set.add(converter.toElement(element));
@@ -112,16 +112,6 @@ public class ScalarTypeArraySet<T> extends ScalarTypeJsonCollection<Set<T>> impl
return converter.toDbArray(value.toArray());
}
@Override
public Set<T> read(DataReader reader) throws SQLException {
Array array = reader.getArray();
if (array == null) {
return null;
} else {
return fromArray((Object[]) array.getArray());
}
}
@Override
public void bind(DataBind bind, Set<T> value) throws SQLException {
if (value == null) {
@@ -0,0 +1,71 @@
package io.ebeaninternal.server.type;
import io.ebean.config.dbplatform.ExtraDbTypes;
import io.ebean.types.Cdir;
import java.sql.SQLException;
import java.sql.Types;
/**
* ScalarType for Cdir to Varchar or Postgres CDIR.
*/
public abstract class ScalarTypeCdir extends ScalarTypeBaseVarchar<Cdir> {
ScalarTypeCdir() {
super(Cdir.class, false, ExtraDbTypes.INET);
}
@Override
public abstract void bind(DataBind b, Cdir value) throws SQLException;
@Override
public Cdir convertFromDbString(String dbValue) {
return parse(dbValue);
}
@Override
public String convertToDbString(Cdir beanValue) {
return formatValue(beanValue);
}
@Override
public String formatValue(Cdir value) {
return value.getAddress();
}
@Override
public Cdir parse(String value) {
return new Cdir(value);
}
/**
* Cdir to Varchar.
*/
public static class Varchar extends ScalarTypeCdir {
@Override
public void bind(DataBind b, Cdir value) throws SQLException {
if (value == null) {
b.setNull(Types.VARCHAR);
} else {
b.setString(convertToDbString(value));
}
}
}
/**
* Cdir to Postgres CDIR.
*/
public static class Postgres extends ScalarTypeCdir {
@Override
public void bind(DataBind b, Cdir value) throws SQLException {
if (value == null) {
b.setNull(Types.OTHER);
} else {
String strValue = convertToDbString(value);
b.setObject(PostgresHelper.asInet(strValue));
}
}
}
}
@@ -0,0 +1,79 @@
package io.ebeaninternal.server.type;
import io.ebean.config.dbplatform.ExtraDbTypes;
import io.ebean.types.Inet;
import java.sql.SQLException;
import java.sql.Types;
/**
* ScalarType for Inet to Varchar or Postgres INET.
*/
public abstract class ScalarTypeInet extends ScalarTypeBaseVarchar<Inet> {
ScalarTypeInet(int jdbcType) {
super(Inet.class, false, jdbcType);
}
@Override
public abstract void bind(DataBind b, Inet value) throws SQLException;
@Override
public Inet convertFromDbString(String dbValue) {
return parse(dbValue);
}
@Override
public String convertToDbString(Inet beanValue) {
return formatValue(beanValue);
}
@Override
public String formatValue(Inet value) {
return value.getAddress();
}
@Override
public Inet parse(String value) {
return new Inet(value);
}
/**
* Inet to Varchar.
*/
public static class Varchar extends ScalarTypeInet {
Varchar() {
super(Types.VARCHAR);
}
@Override
public void bind(DataBind b, Inet value) throws SQLException {
if (value == null) {
b.setNull(Types.VARCHAR);
} else {
b.setString(convertToDbString(value));
}
}
}
/**
* Inet to Postgres INET.
*/
public static class Postgres extends ScalarTypeInet {
Postgres() {
super(ExtraDbTypes.INET);
}
@Override
public void bind(DataBind b, Inet value) throws SQLException {
if (value == null) {
b.setNull(Types.OTHER);
} else {
String strValue = convertToDbString(value);
b.setObject(PostgresHelper.asInet(strValue));
}
}
}
}
@@ -0,0 +1,57 @@
package io.ebeaninternal.server.type;
import io.ebean.config.dbplatform.ExtraDbTypes;
import io.ebean.text.TextException;
import java.net.InetAddress;
import java.sql.SQLException;
import java.sql.Types;
/**
* ScalarType for InetAddress to Postgres INET.
*/
public class ScalarTypeInetAddressPostgres extends ScalarTypeBaseVarchar<InetAddress> {
public ScalarTypeInetAddressPostgres() {
super(InetAddress.class, false, ExtraDbTypes.INET);
}
@Override
public void bind(DataBind b, InetAddress value) throws SQLException {
if (value == null) {
b.setNull(Types.OTHER);
} else {
String strValue = convertToDbString(value);
b.setObject(PostgresHelper.asInet(strValue));
}
}
@Override
public InetAddress convertFromDbString(String dbValue) {
try {
return parse(dbValue);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Error with InetAddresses [" + dbValue + "] " + e);
}
}
@Override
public String convertToDbString(InetAddress beanValue) {
return formatValue(beanValue);
}
@Override
public String formatValue(InetAddress v) {
return ConvertInetAddresses.toHostAddress(v);
}
@Override
public InetAddress parse(String value) {
try {
return ConvertInetAddresses.fromHost(value);
} catch (IllegalArgumentException e) {
throw new TextException("Error with InetAddresses [{}]", value, e);
}
}
}
+10
View File
@@ -94,6 +94,16 @@ public abstract class BaseTestCase {
return trimSql(query.getGeneratedSql(), columns);
}
protected void assertSqlBind(List<String> sql, int i) {
assertThat(sql.get(i)).contains("-- bind");
}
protected void assertSqlBind(List<String> sql, int from, int to) {
for (int i = from; i <= to; i++) {
assertThat(sql.get(i)).contains("-- bind");
}
}
protected String trimSql(String sql) {
if (sql.contains(" c1,")) {
@@ -24,7 +24,7 @@ public class DtoQueryFromOrmTest extends BaseTestCase {
@AfterClass
public static void reportStats() {
BasicMetricVisitor basic = Ebean.getDefaultServer().getMetaInfoManager().visitBasic();
BasicMetricVisitor basic = DB.getDefault().getMetaInfoManager().visitBasic();
for (MetaQueryMetric metric : basic.getDtoQueryMetrics()) {
System.out.println(metric);
}
@@ -143,7 +143,7 @@ public class DtoQueryFromOrmTest extends BaseTestCase {
if (isSqlServer()) {
assertThat(sql.get(0)).contains("select top 10 t0.email, " + concat("t0.last_name", ", ", "t0.first_name")
+ " fullName from contact t0 where t0.email is not null and t0.last_name is not null order by t0.last_name");
+ " fullName from contact t0 where t0.email is not null and t0.last_name is not null order by t0.last_name");
} else {
assertThat(sql.get(0)).contains("select t0.email, " + concat("t0.last_name", ", ", "t0.first_name")
@@ -175,7 +175,7 @@ public class DtoQueryFromOrmTest extends BaseTestCase {
if (isSqlServer()) {
assertThat(sql.get(0)).contains("select top 10 t0.id, t0.email, "
+ concat("t0.last_name", ", ", "t0.first_name")
+ " fullName from contact t0 where t0.email is not null and t0.last_name is not null order by t0.last_name");
+ " fullName from contact t0 where t0.email is not null and t0.last_name is not null order by t0.last_name");
} else {
assertThat(sql.get(0)).contains("select t0.id, t0.email, " + concat("t0.last_name", ", ", "t0.first_name")
+ " fullName from contact t0 where t0.email is not null and t0.last_name is not null order by t0.last_name");
+1 -1
View File
@@ -130,7 +130,7 @@ public class DtoQueryTest extends BaseTestCase {
List<Integer> ids = Arrays.asList(1, 2);
List<SqlRow> list = server().createSqlQuery("select id, name from o_customer where id = any(?)")
List<SqlRow> list = DB.sqlQuery("select id, name from o_customer where id = any(?)")
.setParameter(1, ids)
.findList();
@@ -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()

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