From 6839f869f54023e6dea87e18afd20f367e019377 Mon Sep 17 00:00:00 2001 From: Rob Bygrave Date: Mon, 14 Sep 2020 18:30:51 +1200 Subject: [PATCH] #2049 - Migrate to DatabaseConfig from ServerConfig (#2057) --- src/main/java/io/ebean/DatabaseFactory.java | 82 +- .../java/io/ebean/EbeanServerFactory.java | 81 +- .../ebean/cache/ServerCacheNotifyPlugin.java | 4 +- .../io/ebean/cache/ServerCachePlugin.java | 4 +- .../java/io/ebean/config/AutoConfigure.java | 4 +- .../java/io/ebean/config/DatabaseConfig.java | 3154 ++++++++++++++++- .../ebean/config/DatabaseConfigProvider.java | 39 + .../java/io/ebean/config/ServerConfig.java | 3113 +--------------- .../io/ebean/config/ServerConfigProvider.java | 4 +- .../io/ebean/dbmigration/DbMigration.java | 4 +- .../io/ebean/event/ServerConfigStartup.java | 6 +- src/main/java/io/ebean/plugin/SpiServer.java | 4 +- .../java/io/ebean/service/SpiContainer.java | 8 +- .../ebeaninternal/api/ExtraTypeFactory.java | 4 +- .../io/ebeaninternal/api/SpiEbeanServer.java | 5 +- .../dbmigration/DdlGenerator.java | 22 +- .../dbmigration/DefaultDbMigration.java | 6 +- .../ddlgeneration/BaseDdlHandler.java | 10 +- .../platform/AbstractHanaDdl.java | 6 +- .../ddlgeneration/platform/BaseTableDdl.java | 14 +- .../ddlgeneration/platform/ClickHouseDdl.java | 6 +- .../platform/ClickHouseDdlHandler.java | 6 +- .../platform/ClickHouseTableDdl.java | 6 +- .../platform/DbTriggerBasedHistoryDdl.java | 12 +- .../platform/HanaDdlHandler.java | 6 +- .../platform/HanaHistoryDdl.java | 10 +- .../ddlgeneration/platform/HanaTableDdl.java | 10 +- .../platform/MariaDbHistoryDdl.java | 4 +- .../platform/NoHistorySupportDdl.java | 4 +- .../ddlgeneration/platform/PlatformDdl.java | 11 +- .../platform/PlatformHistoryDdl.java | 4 +- .../platform/SqlServerHistoryDdl.java | 8 +- .../dbmigration/model/PlatformDdlWriter.java | 8 +- .../service/AutoTuneServiceFactory.java | 7 +- .../service/DefaultAutoTuneService.java | 8 +- .../server/cache/CacheManagerOptions.java | 10 +- .../cache/DefaultServerCachePlugin.java | 4 +- .../server/core/ClassPathScanners.java | 9 +- .../server/core/DatabasePlatformFactory.java | 14 +- .../server/core/DefaultContainer.java | 111 +- .../server/core/DefaultServer.java | 11 +- .../server/core/InitDataSource.java | 8 +- .../server/core/InternalConfigXmlRead.java | 6 +- .../server/core/InternalConfiguration.java | 9 +- .../core/bootup/BootupClassPathSearch.java | 16 +- .../server/core/bootup/BootupClasses.java | 21 +- .../server/deploy/BeanDescriptor.java | 4 +- .../server/deploy/BeanDescriptorManager.java | 10 +- .../server/deploy/BeanDescriptorMap.java | 4 +- .../deploy/BeanLifecycleAdapterFactory.java | 4 +- .../GeneratedPropertyFactory.java | 4 +- .../deploy/meta/DeployBeanDescriptor.java | 8 +- .../deploy/meta/DeployBeanObtainJackson.java | 11 +- .../server/deploy/parse/DeployUtil.java | 18 +- .../deploy/parse/ReadAnnotationConfig.java | 12 +- .../server/deploy/parse/ReadAnnotations.java | 4 +- .../server/query/CQueryEngine.java | 4 +- .../TransactionManagerOptions.java | 6 +- .../server/type/DefaultTypeFactory.java | 6 +- .../server/type/DefaultTypeManager.java | 28 +- ...nServerFactory_ServerConfigStart_Test.java | 13 +- .../platform/PlatformDdl_AlterColumnTest.java | 3 +- .../model/basic/MyEBasicConfigStartup.java | 4 +- 63 files changed, 3551 insertions(+), 3495 deletions(-) create mode 100644 src/main/java/io/ebean/config/DatabaseConfigProvider.java diff --git a/src/main/java/io/ebean/DatabaseFactory.java b/src/main/java/io/ebean/DatabaseFactory.java index bde3dfc10..108ababc1 100644 --- a/src/main/java/io/ebean/DatabaseFactory.java +++ b/src/main/java/io/ebean/DatabaseFactory.java @@ -2,6 +2,13 @@ package io.ebean; import io.ebean.config.ContainerConfig; import io.ebean.config.DatabaseConfig; +import io.ebean.service.SpiContainer; +import io.ebean.service.SpiContainerFactory; + +import javax.persistence.PersistenceException; +import java.util.Iterator; +import java.util.Properties; +import java.util.ServiceLoader; /** * Creates Database instances. @@ -23,6 +30,12 @@ import io.ebean.config.DatabaseConfig; */ public class DatabaseFactory { + private static SpiContainer container; + + static { + EbeanVersion.getVersion(); + } + /** * Initialise the container with clustering configuration. *

@@ -30,28 +43,44 @@ public class DatabaseFactory { * ContainerConfig on the ServerConfig when creating the first Database instance. */ public static synchronized void initialiseContainer(ContainerConfig containerConfig) { - EbeanServerFactory.initialiseContainer(containerConfig); + getContainer(containerConfig); } /** - * Create using ebean.properties to configure the database. + * Create using properties to configure the database. */ public static synchronized Database create(String name) { - return EbeanServerFactory.create(name); + // construct based on loading properties files + return getContainer(null).createServer(name); } /** - * Create using the ServerConfig object to configure the database. + * Create using the DatabaseConfig object to configure the database. */ public static synchronized Database create(DatabaseConfig config) { - return EbeanServerFactory.create(config); + if (config.getName() == null) { + throw new PersistenceException("The name is null (it is required)"); + } + Database server = createInternal(config); + if (config.isRegister()) { + DbPrimary.setSkip(true); + DbContext.getInstance().register(server, config.isDefaultServer()); + } + return server; } /** - * Create using the ServerConfig additionally specifying a classLoader to use as the context class loader. + * Create using the DatabaseConfig 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); + ClassLoader currentContextLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(classLoader); + try { + return DatabaseFactory.create(config); + } finally { + // set the currentContextLoader back + Thread.currentThread().setContextClassLoader(currentContextLoader); + } } /** @@ -61,7 +90,44 @@ public class DatabaseFactory { *

*/ public static synchronized void shutdown() { - EbeanServerFactory.shutdown(); + container.shutdown(); } + private static Database createInternal(DatabaseConfig config) { + return getContainer(config.getContainerConfig()).createServer(config); + } + + /** + * Get the EbeanContainer initialising it if necessary. + * + * @param containerConfig the configuration controlling clustering communication + */ + private static SpiContainer getContainer(ContainerConfig containerConfig) { + + // thread safe in that all calling methods are synchronized + if (container != null) { + return container; + } + + if (containerConfig == null) { + // effectively load configuration from ebean.properties + Properties properties = DbPrimary.getProperties(); + containerConfig = new ContainerConfig(); + containerConfig.loadFromProperties(properties); + } + container = createContainer(containerConfig); + return container; + } + + /** + * Create the container instance using the configuration. + */ + protected static SpiContainer createContainer(ContainerConfig containerConfig) { + + Iterator factories = ServiceLoader.load(SpiContainerFactory.class).iterator(); + if (factories.hasNext()) { + return factories.next().create(containerConfig); + } + throw new IllegalStateException("Service loader didn't find a SpiContainerFactory?"); + } } diff --git a/src/main/java/io/ebean/EbeanServerFactory.java b/src/main/java/io/ebean/EbeanServerFactory.java index 4003382bc..ed98effd6 100644 --- a/src/main/java/io/ebean/EbeanServerFactory.java +++ b/src/main/java/io/ebean/EbeanServerFactory.java @@ -33,13 +33,6 @@ import java.util.ServiceLoader; @Deprecated public class EbeanServerFactory { - - private static SpiContainer container; - - static { - EbeanVersion.getVersion(); // initalizes the version class and logs the version. - } - /** * Initialise the container with clustering configuration. *

@@ -47,53 +40,28 @@ public class EbeanServerFactory { * ContainerConfig on the ServerConfig when creating the first EbeanServer instance. */ public static synchronized void initialiseContainer(ContainerConfig containerConfig) { - getContainer(containerConfig); + DatabaseFactory.initialiseContainer(containerConfig); } /** * Create using ebean.properties to configure the database. */ public static synchronized EbeanServer create(String name) { - - // construct based on loading properties files - // and if invoked by Ebean then it handles registration - SpiContainer serverFactory = getContainer(null); - return serverFactory.createServer(name); + return (EbeanServer)DatabaseFactory.create(name); } /** * Create using the ServerConfig object to configure the database. */ public static synchronized EbeanServer create(ServerConfig config) { - - if (config.getName() == null) { - throw new PersistenceException("The name is null (it is required)"); - } - - EbeanServer server = createInternal(config); - - if (config.isRegister()) { - DbPrimary.setSkip(true); - Ebean.register(server, config.isDefaultServer()); - } - - return server; + return (EbeanServer)DatabaseFactory.create(config); } /** * Create using the ServerConfig additionally specifying a classLoader to use as the context class loader. */ public static synchronized EbeanServer createWithContextClassLoader(ServerConfig config, ClassLoader classLoader) { - - ClassLoader currentContextLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(classLoader); - try { - return EbeanServerFactory.create(config); - - } finally { - // set the currentContextLoader back - Thread.currentThread().setContextClassLoader(currentContextLoader); - } + return (EbeanServer)DatabaseFactory.createWithContextClassLoader(config, classLoader); } /** @@ -103,46 +71,7 @@ public class EbeanServerFactory { *

*/ public static synchronized void shutdown() { - container.shutdown(); + DatabaseFactory.shutdown(); } - - private static EbeanServer createInternal(ServerConfig config) { - - return getContainer(config.getContainerConfig()).createServer(config); - } - - /** - * Get the EbeanContainer initialising it if necessary. - * - * @param containerConfig the configuration controlling clustering communication - */ - private static SpiContainer getContainer(ContainerConfig containerConfig) { - - // thread safe in that all calling methods are synchronized - if (container != null) { - return container; - } - - if (containerConfig == null) { - // effectively load configuration from ebean.properties - Properties properties = DbPrimary.getProperties(); - containerConfig = new ContainerConfig(); - containerConfig.loadFromProperties(properties); - } - container = createContainer(containerConfig); - return container; - } - - /** - * Create the container instance using the configuration. - */ - protected static SpiContainer createContainer(ContainerConfig containerConfig) { - - Iterator factories = ServiceLoader.load(SpiContainerFactory.class).iterator(); - if (factories.hasNext()) { - return factories.next().create(containerConfig); - } - throw new IllegalStateException("Service loader didn't find a SpiContainerFactory?"); - } } diff --git a/src/main/java/io/ebean/cache/ServerCacheNotifyPlugin.java b/src/main/java/io/ebean/cache/ServerCacheNotifyPlugin.java index 2e87a067c..2d232190c 100644 --- a/src/main/java/io/ebean/cache/ServerCacheNotifyPlugin.java +++ b/src/main/java/io/ebean/cache/ServerCacheNotifyPlugin.java @@ -1,6 +1,6 @@ package io.ebean.cache; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; /** * Plugin that provides a ServerCacheNotify implementation. @@ -13,5 +13,5 @@ public interface ServerCacheNotifyPlugin { /** * Create a ServerCacheNotify implementation given the server configuration. */ - ServerCacheNotify create(ServerConfig serverConfig); + ServerCacheNotify create(DatabaseConfig serverConfig); } diff --git a/src/main/java/io/ebean/cache/ServerCachePlugin.java b/src/main/java/io/ebean/cache/ServerCachePlugin.java index 86990d2fd..4050de876 100644 --- a/src/main/java/io/ebean/cache/ServerCachePlugin.java +++ b/src/main/java/io/ebean/cache/ServerCachePlugin.java @@ -1,7 +1,7 @@ package io.ebean.cache; import io.ebean.BackgroundExecutor; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; /** * The plugin interface that creates a ServerCacheFactory. @@ -11,5 +11,5 @@ public interface ServerCachePlugin { /** * Create the ServerCacheFactory given the server config and background executor service. */ - ServerCacheFactory create(ServerConfig config, BackgroundExecutor executor); + ServerCacheFactory create(DatabaseConfig config, BackgroundExecutor executor); } diff --git a/src/main/java/io/ebean/config/AutoConfigure.java b/src/main/java/io/ebean/config/AutoConfigure.java index 525d3ac8b..1f6f3e767 100644 --- a/src/main/java/io/ebean/config/AutoConfigure.java +++ b/src/main/java/io/ebean/config/AutoConfigure.java @@ -8,11 +8,11 @@ public interface AutoConfigure { /** * Perform configuration for the ServerConfig prior to properties load. */ - void preConfigure(ServerConfig serverConfig); + void preConfigure(DatabaseConfig serverConfig); /** * Provide some configuration the ServerConfig prior to server creation but after properties have been applied. */ - void postConfigure(ServerConfig serverConfig); + void postConfigure(DatabaseConfig serverConfig); } diff --git a/src/main/java/io/ebean/config/DatabaseConfig.java b/src/main/java/io/ebean/config/DatabaseConfig.java index f314c73e0..e39baaad8 100644 --- a/src/main/java/io/ebean/config/DatabaseConfig.java +++ b/src/main/java/io/ebean/config/DatabaseConfig.java @@ -1,6 +1,47 @@ package io.ebean.config; +import com.fasterxml.jackson.core.JsonFactory; +import io.avaje.config.Config; import io.ebean.DatabaseFactory; +import io.ebean.PersistenceContextScope; +import io.ebean.Query; +import io.ebean.Transaction; +import io.ebean.annotation.Encrypted; +import io.ebean.annotation.PersistBatch; +import io.ebean.annotation.Platform; +import io.ebean.cache.ServerCachePlugin; +import io.ebean.config.dbplatform.DatabasePlatform; +import io.ebean.config.dbplatform.DbEncrypt; +import io.ebean.config.dbplatform.DbType; +import io.ebean.config.dbplatform.IdType; +import io.ebean.datasource.DataSourceConfig; +import io.ebean.event.BeanFindController; +import io.ebean.event.BeanPersistController; +import io.ebean.event.BeanPersistListener; +import io.ebean.event.BeanPostConstructListener; +import io.ebean.event.BeanPostLoad; +import io.ebean.event.BeanQueryAdapter; +import io.ebean.event.BulkTableEventListener; +import io.ebean.event.ServerConfigStartup; +import io.ebean.event.changelog.ChangeLogListener; +import io.ebean.event.changelog.ChangeLogPrepare; +import io.ebean.event.changelog.ChangeLogRegister; +import io.ebean.event.readaudit.ReadAuditLogger; +import io.ebean.event.readaudit.ReadAuditPrepare; +import io.ebean.migration.MigrationRunner; +import io.ebean.util.StringHelper; + +import javax.persistence.EnumType; +import javax.sql.DataSource; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.ServiceLoader; /** * The configuration used for creating a Database. @@ -39,6 +80,3117 @@ import io.ebean.DatabaseFactory; * @author rbygrave * @see DatabaseFactory */ -public class DatabaseConfig extends ServerConfig { +public class DatabaseConfig { + + /** + * The Database name. + */ + private String name = "db"; + + /** + * Typically configuration type objects that are passed by this ServerConfig + * to plugins. For example - IgniteConfiguration passed to Ignite plugin. + */ + private final Map serviceObject = new HashMap<>(); + + private ContainerConfig containerConfig; + + /** + * The underlying properties that were used during configuration. + */ + private Properties properties; + + /** + * The resource directory. + */ + private String resourceDirectory; + + /** + * Set to true to register this Database with the DB singleton. + */ + private boolean register = true; + + /** + * Set to true if this is the default/primary database. + */ + private boolean defaultServer = true; + + /** + * Set this to true to disable class path search. + */ + private boolean disableClasspathSearch; + + private TenantMode tenantMode = TenantMode.NONE; + + private String tenantPartitionColumn = "tenant_id"; + + private CurrentTenantProvider currentTenantProvider; + + private TenantDataSourceProvider tenantDataSourceProvider; + + private TenantSchemaProvider tenantSchemaProvider; + + private TenantCatalogProvider tenantCatalogProvider; + + /** + * When true will load entity classes via ModuleInfoLoader. + *

+ * NB: ModuleInfoLoader implementations are generated by querybean generator. + * Having this on and registering entity classes means we don't need to manually + * write that code or use classpath scanning to find entity classes. + */ + private boolean loadModuleInfo = true; + + /** + * List of interesting classes such as entities, embedded, ScalarTypes, + * Listeners, Finders, Controllers etc. + */ + private List> classes = new ArrayList<>(); + + /** + * The packages that are searched for interesting classes. Only used when + * classes is empty/not explicitly specified. + */ + private List packages = new ArrayList<>(); + + /** + * Configuration for the ElasticSearch integration. + */ + private DocStoreConfig docStoreConfig = new DocStoreConfig(); + + /** + * Set to true when the Database only uses Document store. + */ + private boolean docStoreOnly; + + /** + * This is used to populate @WhoCreated, @WhoModified and + * support other audit features (who executed a query etc). + */ + private CurrentUserProvider currentUserProvider; + + /** + * Config controlling the AutoTune behaviour. + */ + private AutoTuneConfig autoTuneConfig = new AutoTuneConfig(); + + /** + * The JSON format used for DateTime types. Default to millis. + */ + private JsonConfig.DateTime jsonDateTime = JsonConfig.DateTime.ISO8601; + + /** + * The JSON format used for Date types. Default to millis. + */ + private JsonConfig.Date jsonDate = JsonConfig.Date.ISO8601; + + /** + * For writing JSON specify if null values or empty collections should be excluded. + * By default all values are included. + */ + private JsonConfig.Include jsonInclude = JsonConfig.Include.ALL; + + /** + * The database platform name. Used to imply a DatabasePlatform to use. + */ + private String databasePlatformName; + + /** + * The database platform. + */ + private DatabasePlatform databasePlatform; + + /** + * JDBC fetchSize hint when using findList. Defaults to 0 leaving it up to the JDBC driver. + */ + private int jdbcFetchSizeFindList; + + /** + * JDBC fetchSize hint when using findEach/findEachWhile. Defaults to 100. Note that this does + * not apply to MySql as that gets special treatment (forward only etc). + */ + private int jdbcFetchSizeFindEach = 100; + + /** + * Suffix appended to the base table to derive the view that contains the union + * of the base table and the history table in order to support asOf queries. + */ + private String asOfViewSuffix = "_with_history"; + + /** + * Column used to support history and 'As of' queries. This column is a timestamp range + * or equivalent. + */ + private String asOfSysPeriod = "sys_period"; + + /** + * Suffix appended to the base table to derive the view that contains the union + * of the base table and the history table in order to support asOf queries. + */ + private String historyTableSuffix = "_history"; + + /** + * Use for transaction scoped batch mode. + */ + private PersistBatch persistBatch = PersistBatch.NONE; + + /** + * Use for cascade persist JDBC batch mode. INHERIT means use the platform default + * which is ALL except for SQL Server where it is NONE (as getGeneratedKeys isn't + * supported on SQL Server with JDBC batch). + */ + private PersistBatch persistBatchOnCascade = PersistBatch.INHERIT; + + private int persistBatchSize = 20; + + private EnumType defaultEnumType = EnumType.ORDINAL; + + private boolean disableLazyLoading; + + /** + * The default batch size for lazy loading + */ + private int lazyLoadBatchSize = 10; + + /** + * The default batch size for 'query joins'. + */ + private int queryBatchSize = 100; + + private boolean eagerFetchLobs; + + /** + * Timezone used to get/set Timestamp values via JDBC. + */ + private String dataTimeZone; + + private boolean ddlGenerate; + + private boolean ddlRun; + + private boolean ddlExtra = true; + + private boolean ddlCreateOnly; + + private String ddlInitSql; + + private String ddlSeedSql; + + /** + * When true L2 bean cache use is skipped after a write has occurred on a transaction. + */ + private boolean skipCacheAfterWrite = true; + + private boolean useJtaTransactionManager; + + /** + * The external transaction manager (like Spring). + */ + private ExternalTransactionManager externalTransactionManager; + + /** + * The data source (if programmatically provided). + */ + private DataSource dataSource; + + /** + * The read only data source (can be null). + */ + private DataSource readOnlyDataSource; + + /** + * The data source config. + */ + private DataSourceConfig dataSourceConfig = new DataSourceConfig(); + + /** + * When true create a read only DataSource using readOnlyDataSourceConfig defaulting values from dataSourceConfig. + * I believe this will default to true in some future release (as it has a nice performance benefit). + *

+ * autoReadOnlyDataSource is an unfortunate name for this config option but I haven't come up with a better one. + */ + private boolean autoReadOnlyDataSource; + + /** + * Optional configuration for a read only data source. + */ + private DataSourceConfig readOnlyDataSourceConfig = new DataSourceConfig(); + + /** + * Optional - the database schema that should be used to own the tables etc. + */ + private String dbSchema; + + /** + * The db migration config (migration resource path etc). + */ + private DbMigrationConfig migrationConfig = new DbMigrationConfig(); + + /** + * The ClassLoadConfig used to detect Joda, Java8, Jackson etc and create plugin instances given a className. + */ + private ClassLoadConfig classLoadConfig = new ClassLoadConfig(); + + /** + * The data source JNDI name if using a JNDI DataSource. + */ + private String dataSourceJndiName; + + /** + * The naming convention. + */ + private NamingConvention namingConvention = new UnderscoreNamingConvention(); + + /** + * Behaviour of updates in JDBC batch to by default include all properties. + */ + private boolean updateAllPropertiesInBatch; + + /** + * Database platform configuration. + */ + private PlatformConfig platformConfig = new PlatformConfig(); + + /** + * The UUID version to use. + */ + private UuidVersion uuidVersion = UuidVersion.VERSION4; + + /** + * The UUID state file (for Version 1 UUIDs). By default, the file is created in + * ${HOME}/.ebean/${servername}-uuid.state + */ + private String uuidStateFile; + + /** + * The clock used for setting the timestamps (e.g. @UpdatedTimestamp) on objects. + */ + private Clock clock = Clock.systemUTC(); + + private List idGenerators = new ArrayList<>(); + private List findControllers = new ArrayList<>(); + private List persistControllers = new ArrayList<>(); + private List postLoaders = new ArrayList<>(); + private List postConstructListeners = new ArrayList<>(); + private List persistListeners = new ArrayList<>(); + private List queryAdapters = new ArrayList<>(); + private List bulkTableEventListeners = new ArrayList<>(); + private List configStartupListeners = new ArrayList<>(); + + /** + * By default inserts are included in the change log. + */ + private boolean changeLogIncludeInserts = true; + + private ChangeLogPrepare changeLogPrepare; + + private ChangeLogListener changeLogListener; + + private ChangeLogRegister changeLogRegister; + + private boolean changeLogAsync = true; + + private ReadAuditLogger readAuditLogger; + + private ReadAuditPrepare readAuditPrepare; + + private EncryptKeyManager encryptKeyManager; + + private EncryptDeployManager encryptDeployManager; + + private Encryptor encryptor; + + private boolean dbOffline; + + private DbEncrypt dbEncrypt; + + private ServerCachePlugin serverCachePlugin; + + /** + * The default PersistenceContextScope used if one is not explicitly set on a query. + */ + private PersistenceContextScope persistenceContextScope = PersistenceContextScope.TRANSACTION; + + private JsonFactory jsonFactory; + + private boolean localTimeWithNanos; + + private boolean durationWithNanos; + + private int maxCallStack = 5; + + private boolean transactionRollbackOnChecked = true; + + // configuration for the background executor service (thread pool) + + private int backgroundExecutorSchedulePoolSize = 1; + private int backgroundExecutorShutdownSecs = 30; + + // defaults for the L2 bean caching + + private int cacheMaxSize = 10000; + private int cacheMaxIdleTime = 600; + private int cacheMaxTimeToLive = 60 * 60 * 6; + + // defaults for the L2 query caching + + private int queryCacheMaxSize = 1000; + private int queryCacheMaxIdleTime = 600; + private int queryCacheMaxTimeToLive = 60 * 60 * 6; + private Object objectMapper; + + /** + * Set to true if you want eq("someProperty", null) to generate 1=1 rather than "is null" sql expression. + */ + private boolean expressionEqualsWithNullAsNoop; + + /** + * Set to true to use native ILIKE expression (if support by database platform / like Postgres). + */ + private boolean expressionNativeIlike; + + private String jodaLocalTimeMode; + + /** + * Time to live for query plans - defaults to 5 minutes. + */ + private int queryPlanTTLSeconds = 60 * 5; + + /** + * Set to true to globally disable L2 caching (typically for performance testing). + */ + private boolean disableL2Cache; + + private String enabledL2Regions; + + /** + * Set to true to effectively disable L2 cache plugins. + */ + private boolean localOnlyL2Cache; + + /** + * Should the javax.validation.constraints.NotNull enforce a notNull column in DB. + * If set to false, use io.ebean.annotation.NotNull or Column(nullable=true). + */ + private boolean useJavaxValidationNotNull = true; + + /** + * Generally we want to perform L2 cache notification in the background and not impact + * the performance of executing transactions. + */ + private boolean notifyL2CacheInForeground; + + /** + * Set to true to support query plan capture. + */ + private boolean collectQueryPlans; + + /** + * The default threshold in micros for collecting query plans. + */ + private long collectQueryPlanThresholdMicros = Long.MAX_VALUE; + + /** + * The time in millis used to determine when a query is alerted for being slow. + */ + private long slowQueryMillis; + + /** + * The listener for processing slow query events. + */ + private SlowQueryListener slowQueryListener; + + private ProfilingConfig profilingConfig = new ProfilingConfig(); + + /** + * Controls the default order by id setting of queries. See {@link Query#orderById(boolean)} + */ + private boolean defaultOrderById; + + /** + * The mappingLocations for searching xml mapping. + */ + private List mappingLocations = new ArrayList<>(); + + /** + * When true we do not need explicit GeneratedValue mapping. + */ + private boolean idGeneratorAutomatic = true; + + private boolean dumpMetricsOnShutdown; + + private String dumpMetricsOptions; + + /** + * Construct a Database Configuration for programmatically creating an Database. + */ + public DatabaseConfig() { + } + + /** + * Get the clock used for setting the timestamps (e.g. @UpdatedTimestamp) on objects. + */ + public Clock getClock() { + return clock; + } + + /** + * Set the clock used for setting the timestamps (e.g. @UpdatedTimestamp) on objects. + */ + public void setClock(final Clock clock) { + this.clock = clock; + } + + /** + * Return the slow query time in millis. + */ + public long getSlowQueryMillis() { + return slowQueryMillis; + } + + /** + * Set the slow query time in millis. + */ + public void setSlowQueryMillis(long slowQueryMillis) { + this.slowQueryMillis = slowQueryMillis; + } + + /** + * Return the slow query event listener. + */ + public SlowQueryListener getSlowQueryListener() { + return slowQueryListener; + } + + /** + * Set the slow query event listener. + */ + public void setSlowQueryListener(SlowQueryListener slowQueryListener) { + this.slowQueryListener = slowQueryListener; + } + + + /** + * Deprecated - look to have explicit order by. Sets the default orderById setting for queries. + */ + @Deprecated + public void setDefaultOrderById(boolean defaultOrderById) { + this.defaultOrderById = defaultOrderById; + } + + /** + * Returns the default orderById setting for queries. + */ + public boolean isDefaultOrderById() { + return defaultOrderById; + } + + /** + * Put a service object into configuration such that it can be passed to a plugin. + *

+ * For example, put IgniteConfiguration in to be passed to the Ignite plugin. + */ + public void putServiceObject(String key, Object configObject) { + serviceObject.put(key, configObject); + } + + /** + * Return the service object given the key. + */ + public Object getServiceObject(String key) { + return serviceObject.get(key); + } + + /** + * Put a service object into configuration such that it can be passed to a plugin. + * + *

{@code
+   *
+   *   JedisPool jedisPool = ..
+   *
+   *   serverConfig.putServiceObject(jedisPool);
+   *
+   * }
+ */ + public void putServiceObject(Object configObject) { + String key = serviceObjectKey(configObject); + serviceObject.put(key, configObject); + } + + private String serviceObjectKey(Object configObject) { + return serviceObjectKey(configObject.getClass()); + } + + private String serviceObjectKey(Class cls) { + String simpleName = cls.getSimpleName(); + return Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1); + } + + /** + * Used by plugins to obtain service objects. + * + *
{@code
+   *
+   *   JedisPool jedisPool = serverConfig.getServiceObject(JedisPool.class);
+   *
+   * }
+ * + * @param cls The type of the service object to obtain + * @return The service object given the class type + */ + @SuppressWarnings("unchecked") + public

P getServiceObject(Class

cls) { + return (P) serviceObject.get(serviceObjectKey(cls)); + } + + /** + * Return the Jackson JsonFactory to use. + *

+ * If not set a default implementation will be used. + */ + public JsonFactory getJsonFactory() { + return jsonFactory; + } + + /** + * Set the Jackson JsonFactory to use. + *

+ * If not set a default implementation will be used. + */ + public void setJsonFactory(JsonFactory jsonFactory) { + this.jsonFactory = jsonFactory; + } + + /** + * Return the JSON format used for DateTime types. + */ + public JsonConfig.DateTime getJsonDateTime() { + return jsonDateTime; + } + + /** + * Set the JSON format to use for DateTime types. + */ + public void setJsonDateTime(JsonConfig.DateTime jsonDateTime) { + this.jsonDateTime = jsonDateTime; + } + + /** + * Return the JSON format used for Date types. + */ + public JsonConfig.Date getJsonDate() { + return jsonDate; + } + + /** + * Set the JSON format to use for Date types. + */ + public void setJsonDate(JsonConfig.Date jsonDate) { + this.jsonDate = jsonDate; + } + + /** + * Return the JSON include mode used when writing JSON. + */ + public JsonConfig.Include getJsonInclude() { + return jsonInclude; + } + + /** + * Set the JSON include mode used when writing JSON. + *

+ * Set to NON_NULL or NON_EMPTY to suppress nulls or null and empty collections respectively. + */ + public void setJsonInclude(JsonConfig.Include jsonInclude) { + this.jsonInclude = jsonInclude; + } + + /** + * Return the name of the Database. + */ + public String getName() { + return name; + } + + /** + * Set the name of the Database. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Return the container / clustering configuration. + *

+ * The container holds all the Database instances and provides clustering communication + * services to all the Database instances. + */ + public ContainerConfig getContainerConfig() { + return containerConfig; + } + + /** + * Set the container / clustering configuration. + *

+ * 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; + } + + /** + * Return true if this server should be registered with the Ebean singleton + * when it is created. + *

+ * By default this is set to true. + */ + public boolean isRegister() { + return register; + } + + /** + * Set to false if you do not want this server to be registered with the Ebean + * singleton when it is created. + *

+ * By default this is set to true. + */ + public void setRegister(boolean register) { + this.register = register; + } + + /** + * Return true if this server should be registered as the "default" server + * with the Ebean singleton. + *

+ * This is only used when {@link #setRegister(boolean)} is also true. + */ + public boolean isDefaultServer() { + return defaultServer; + } + + /** + * Set false if you do not want this Database to be registered as the "default" database + * with the DB singleton. + *

+ * This is only used when {@link #setRegister(boolean)} is also true. + */ + public void setDefaultServer(boolean defaultServer) { + this.defaultServer = defaultServer; + } + + /** + * Return the CurrentUserProvider. This is used to populate @WhoCreated, @WhoModified and + * support other audit features (who executed a query etc). + */ + public CurrentUserProvider getCurrentUserProvider() { + return currentUserProvider; + } + + /** + * Set the CurrentUserProvider. This is used to populate @WhoCreated, @WhoModified and + * support other audit features (who executed a query etc). + */ + public void setCurrentUserProvider(CurrentUserProvider currentUserProvider) { + this.currentUserProvider = currentUserProvider; + } + + /** + * Return the tenancy mode used. + */ + public TenantMode getTenantMode() { + return tenantMode; + } + + /** + * Set the tenancy mode to use. + */ + public void setTenantMode(TenantMode tenantMode) { + this.tenantMode = tenantMode; + } + + /** + * Return the column name used for TenantMode.PARTITION. + */ + public String getTenantPartitionColumn() { + return tenantPartitionColumn; + } + + /** + * Set the column name used for TenantMode.PARTITION. + */ + public void setTenantPartitionColumn(String tenantPartitionColumn) { + this.tenantPartitionColumn = tenantPartitionColumn; + } + + /** + * Return the current tenant provider. + */ + public CurrentTenantProvider getCurrentTenantProvider() { + return currentTenantProvider; + } + + /** + * Set the current tenant provider. + */ + public void setCurrentTenantProvider(CurrentTenantProvider currentTenantProvider) { + this.currentTenantProvider = currentTenantProvider; + } + + /** + * Return the tenancy datasource provider. + */ + public TenantDataSourceProvider getTenantDataSourceProvider() { + return tenantDataSourceProvider; + } + + /** + * Set the tenancy datasource provider. + */ + public void setTenantDataSourceProvider(TenantDataSourceProvider tenantDataSourceProvider) { + this.tenantDataSourceProvider = tenantDataSourceProvider; + } + + /** + * Return the tenancy schema provider. + */ + public TenantSchemaProvider getTenantSchemaProvider() { + return tenantSchemaProvider; + } + + /** + * Set the tenancy schema provider. + */ + public void setTenantSchemaProvider(TenantSchemaProvider tenantSchemaProvider) { + this.tenantSchemaProvider = tenantSchemaProvider; + } + + /** + * Return the tenancy catalog provider. + */ + public TenantCatalogProvider getTenantCatalogProvider() { + return tenantCatalogProvider; + } + + /** + * Set the tenancy catalog provider. + */ + public void setTenantCatalogProvider(TenantCatalogProvider tenantCatalogProvider) { + this.tenantCatalogProvider = tenantCatalogProvider; + } + + /** + * Return the PersistBatch mode to use by default at the transaction level. + *

+ * When INSERT or ALL is used then save(), delete() etc do not execute immediately but instead go into + * a JDBC batch execute buffer that is flushed. The buffer is flushed if a query is executed, transaction ends + * or the batch size is meet. + */ + public PersistBatch getPersistBatch() { + return persistBatch; + } + + /** + * Set the JDBC batch mode to use at the transaction level. + *

+ * When INSERT or ALL is used then save(), delete() etc do not execute immediately but instead go into + * a JDBC batch execute buffer that is flushed. The buffer is flushed if a query is executed, transaction ends + * or the batch size is meet. + */ + public void setPersistBatch(PersistBatch persistBatch) { + this.persistBatch = persistBatch; + } + + /** + * Return the JDBC batch mode to use per save(), delete(), insert() or update() request. + *

+ * This makes sense when a save() or delete() cascades and executes multiple child statements. The best case + * for this is when saving a master/parent bean this cascade inserts many detail/child beans. + *

+ * This only takes effect when the persistBatch mode at the transaction level does not take effect. + */ + public PersistBatch getPersistBatchOnCascade() { + return persistBatchOnCascade; + } + + /** + * Set the JDBC batch mode to use per save(), delete(), insert() or update() request. + *

+ * This makes sense when a save() or delete() etc cascades and executes multiple child statements. The best caase + * for this is when saving a master/parent bean this cascade inserts many detail/child beans. + *

+ * This only takes effect when the persistBatch mode at the transaction level does not take effect. + */ + public void setPersistBatchOnCascade(PersistBatch persistBatchOnCascade) { + this.persistBatchOnCascade = persistBatchOnCascade; + } + + /** + * Deprecated, please migrate to using setPersistBatch(). + *

+ * Set to true if you what to use JDBC batching for persisting and deleting beans. + *

+ * With this Ebean will batch up persist requests and use the JDBC batch api. + * This is a performance optimisation designed to reduce the network chatter. + *

+ * When true this is equivalent to {@code setPersistBatch(PersistBatch.ALL)} or + * when false to {@code setPersistBatch(PersistBatch.NONE)} + */ + public void setPersistBatching(boolean persistBatching) { + this.persistBatch = (persistBatching) ? PersistBatch.ALL : PersistBatch.NONE; + } + + /** + * Return the batch size used for JDBC batching. This defaults to 20. + */ + public int getPersistBatchSize() { + return persistBatchSize; + } + + /** + * Set the batch size used for JDBC batching. If unset this defaults to 20. + *

+ * You can also set the batch size on the transaction. + * + * @see Transaction#setBatchSize(int) + */ + public void setPersistBatchSize(int persistBatchSize) { + this.persistBatchSize = persistBatchSize; + } + + /** + * Gets the query batch size. This defaults to 100. + * + * @return the query batch size + */ + public int getQueryBatchSize() { + return queryBatchSize; + } + + /** + * Sets the query batch size. This defaults to 100. + * + * @param queryBatchSize the new query batch size + */ + public void setQueryBatchSize(int queryBatchSize) { + this.queryBatchSize = queryBatchSize; + } + + public EnumType getDefaultEnumType() { + return defaultEnumType; + } + + public void setDefaultEnumType(EnumType defaultEnumType) { + this.defaultEnumType = defaultEnumType; + } + + /** + * Return true if lazy loading is disabled on queries by default. + */ + public boolean isDisableLazyLoading() { + return disableLazyLoading; + } + + /** + * Set to true to disable lazy loading by default. + *

+ * It can be turned on per query via {@link Query#setDisableLazyLoading(boolean)}. + */ + public void setDisableLazyLoading(boolean disableLazyLoading) { + this.disableLazyLoading = disableLazyLoading; + } + + /** + * Return the default batch size for lazy loading of beans and collections. + */ + public int getLazyLoadBatchSize() { + return lazyLoadBatchSize; + } + + /** + * Set the default batch size for lazy loading. + *

+ * This is the number of beans or collections loaded when lazy loading is + * invoked by default. + *

+ * The default value is for this is 10 (load 10 beans or collections). + *

+ * You can explicitly control the lazy loading batch size for a given join on + * a query using +lazy(batchSize) or JoinConfig. + */ + public void setLazyLoadBatchSize(int lazyLoadBatchSize) { + this.lazyLoadBatchSize = lazyLoadBatchSize; + } + + /** + * Set the number of sequences to fetch/preallocate when using DB sequences. + *

+ * This is a performance optimisation to reduce the number times Ebean + * requests a sequence to be used as an Id for a bean (aka reduce network + * chatter). + + */ + public void setDatabaseSequenceBatchSize(int databaseSequenceBatchSize) { + platformConfig.setDatabaseSequenceBatchSize(databaseSequenceBatchSize); + } + + /** + * Return the default JDBC fetchSize hint for findList queries. + */ + public int getJdbcFetchSizeFindList() { + return jdbcFetchSizeFindList; + } + + /** + * Set the default JDBC fetchSize hint for findList queries. + */ + public void setJdbcFetchSizeFindList(int jdbcFetchSizeFindList) { + this.jdbcFetchSizeFindList = jdbcFetchSizeFindList; + } + + /** + * Return the default JDBC fetchSize hint for findEach/findEachWhile queries. + */ + public int getJdbcFetchSizeFindEach() { + return jdbcFetchSizeFindEach; + } + + /** + * Set the default JDBC fetchSize hint for findEach/findEachWhile queries. + */ + public void setJdbcFetchSizeFindEach(int jdbcFetchSizeFindEach) { + this.jdbcFetchSizeFindEach = jdbcFetchSizeFindEach; + } + + /** + * Return the ChangeLogPrepare. + *

+ * This is used to set user context information to the ChangeSet in the + * foreground thread prior to the logging occurring in a background thread. + */ + public ChangeLogPrepare getChangeLogPrepare() { + return changeLogPrepare; + } + + /** + * Set the ChangeLogPrepare. + *

+ * This is used to set user context information to the ChangeSet in the + * foreground thread prior to the logging occurring in a background thread. + */ + public void setChangeLogPrepare(ChangeLogPrepare changeLogPrepare) { + this.changeLogPrepare = changeLogPrepare; + } + + /** + * Return the ChangeLogListener which actually performs the logging of change sets + * in the background. + */ + public ChangeLogListener getChangeLogListener() { + return changeLogListener; + } + + /** + * Set the ChangeLogListener which actually performs the logging of change sets + * in the background. + */ + public void setChangeLogListener(ChangeLogListener changeLogListener) { + this.changeLogListener = changeLogListener; + } + + /** + * Return the ChangeLogRegister which controls which ChangeLogFilter is used for each + * bean type and in this way provide fine grained control over which persist requests + * are included in the change log. + */ + public ChangeLogRegister getChangeLogRegister() { + return changeLogRegister; + } + + /** + * Set the ChangeLogRegister which controls which ChangeLogFilter is used for each + * bean type and in this way provide fine grained control over which persist requests + * are included in the change log. + */ + public void setChangeLogRegister(ChangeLogRegister changeLogRegister) { + this.changeLogRegister = changeLogRegister; + } + + /** + * Return true if inserts should be included in the change log by default. + */ + public boolean isChangeLogIncludeInserts() { + return changeLogIncludeInserts; + } + + /** + * Set if inserts should be included in the change log by default. + */ + public void setChangeLogIncludeInserts(boolean changeLogIncludeInserts) { + this.changeLogIncludeInserts = changeLogIncludeInserts; + } + + /** + * Return true (default) if the changelog should be written async. + */ + public boolean isChangeLogAsync() { + return changeLogAsync; + } + + /** + * Sets if the changelog should be written async (default = true). + */ + public void setChangeLogAsync(boolean changeLogAsync) { + this.changeLogAsync = changeLogAsync; + } + + /** + * Return the ReadAuditLogger to use. + */ + public ReadAuditLogger getReadAuditLogger() { + return readAuditLogger; + } + + /** + * Set the ReadAuditLogger to use. If not set the default implementation is used + * which logs the read events in JSON format to a standard named SLF4J logger + * (which can be configured in say logback to log to a separate log file). + */ + public void setReadAuditLogger(ReadAuditLogger readAuditLogger) { + this.readAuditLogger = readAuditLogger; + } + + /** + * Return the ReadAuditPrepare to use. + */ + public ReadAuditPrepare getReadAuditPrepare() { + return readAuditPrepare; + } + + /** + * Set the ReadAuditPrepare to use. + *

+ * It is expected that an implementation is used that read user context information + * (user id, user ip address etc) and sets it on the ReadEvent bean before it is sent + * to the ReadAuditLogger. + */ + public void setReadAuditPrepare(ReadAuditPrepare readAuditPrepare) { + this.readAuditPrepare = readAuditPrepare; + } + + /** + * Return the configuration for profiling. + */ + public ProfilingConfig getProfilingConfig() { + return profilingConfig; + } + + /** + * Set the configuration for profiling. + */ + public void setProfilingConfig(ProfilingConfig profilingConfig) { + this.profilingConfig = profilingConfig; + } + + /** + * Return the DB schema to use. + */ + public String getDbSchema() { + return dbSchema; + } + + /** + * Set the DB schema to use. This specifies to use this schema for: + *

    + *
  • Running Database migrations - Create and use the DB schema
  • + *
  • Testing DDL - Create-all.sql DDL execution creates and uses schema
  • + *
  • Testing Docker - Set default schema on connection URL
  • + *
+ */ + public void setDbSchema(String dbSchema) { + this.dbSchema = dbSchema; + } + + /** + * Return the DB migration configuration. + */ + public DbMigrationConfig getMigrationConfig() { + return migrationConfig; + } + + /** + * Set the DB migration configuration. + */ + public void setMigrationConfig(DbMigrationConfig migrationConfig) { + this.migrationConfig = migrationConfig; + } + + /** + * Return the Geometry SRID. + */ + public int getGeometrySRID() { + return platformConfig.getGeometrySRID(); + } + + /** + * Set the Geometry SRID. + */ + public void setGeometrySRID(int geometrySRID) { + platformConfig.setGeometrySRID(geometrySRID); + } + + /** + * Return the time zone to use when reading/writing Timestamps via JDBC. + *

+ * When set a Calendar object is used in JDBC calls when reading/writing Timestamp objects. + */ + public String getDataTimeZone() { + return System.getProperty("ebean.dataTimeZone", dataTimeZone); + } + + /** + * Set the time zone to use when reading/writing Timestamps via JDBC. + */ + public void setDataTimeZone(String dataTimeZone) { + this.dataTimeZone = dataTimeZone; + } + + /** + * Return the suffix appended to the base table to derive the view that contains the union + * of the base table and the history table in order to support asOf queries. + */ + public String getAsOfViewSuffix() { + return asOfViewSuffix; + } + + /** + * Set the suffix appended to the base table to derive the view that contains the union + * of the base table and the history table in order to support asOf queries. + */ + public void setAsOfViewSuffix(String asOfViewSuffix) { + this.asOfViewSuffix = asOfViewSuffix; + } + + /** + * Return the database column used to support history and 'As of' queries. This column is a timestamp range + * or equivalent. + */ + public String getAsOfSysPeriod() { + return asOfSysPeriod; + } + + /** + * Set the database column used to support history and 'As of' queries. This column is a timestamp range + * or equivalent. + */ + public void setAsOfSysPeriod(String asOfSysPeriod) { + this.asOfSysPeriod = asOfSysPeriod; + } + + /** + * Return the history table suffix (defaults to _history). + */ + public String getHistoryTableSuffix() { + return historyTableSuffix; + } + + /** + * Set the history table suffix. + */ + public void setHistoryTableSuffix(String historyTableSuffix) { + this.historyTableSuffix = historyTableSuffix; + } + + /** + * Return true if we are running in a JTA Transaction manager. + */ + public boolean isUseJtaTransactionManager() { + return useJtaTransactionManager; + } + + /** + * Set to true if we are running in a JTA Transaction manager. + */ + public void setUseJtaTransactionManager(boolean useJtaTransactionManager) { + this.useJtaTransactionManager = useJtaTransactionManager; + } + + /** + * Return the external transaction manager. + */ + public ExternalTransactionManager getExternalTransactionManager() { + return externalTransactionManager; + } + + /** + * Set the external transaction manager. + */ + public void setExternalTransactionManager(ExternalTransactionManager externalTransactionManager) { + this.externalTransactionManager = externalTransactionManager; + } + + /** + * Return the ServerCachePlugin. + */ + public ServerCachePlugin getServerCachePlugin() { + return serverCachePlugin; + } + + /** + * Set the ServerCachePlugin to use. + */ + public void setServerCachePlugin(ServerCachePlugin serverCachePlugin) { + this.serverCachePlugin = serverCachePlugin; + } + + /** + * Return true if LOB's should default to fetch eager. + * By default this is set to false and LOB's must be explicitly fetched. + */ + public boolean isEagerFetchLobs() { + return eagerFetchLobs; + } + + /** + * Set to true if you want LOB's to be fetch eager by default. + * By default this is set to false and LOB's must be explicitly fetched. + */ + public void setEagerFetchLobs(boolean eagerFetchLobs) { + this.eagerFetchLobs = eagerFetchLobs; + } + + /** + * Return the max call stack to use for origin location. + */ + public int getMaxCallStack() { + return maxCallStack; + } + + /** + * Set the max call stack to use for origin location. + */ + public void setMaxCallStack(int maxCallStack) { + this.maxCallStack = maxCallStack; + } + + /** + * Return true if transactions should rollback on checked exceptions. + */ + public boolean isTransactionRollbackOnChecked() { + return transactionRollbackOnChecked; + } + + /** + * Set to true if transactions should by default rollback on checked exceptions. + */ + public void setTransactionRollbackOnChecked(boolean transactionRollbackOnChecked) { + this.transactionRollbackOnChecked = transactionRollbackOnChecked; + } + + /** + * Return the Background executor schedule pool size. Defaults to 1. + */ + public int getBackgroundExecutorSchedulePoolSize() { + return backgroundExecutorSchedulePoolSize; + } + + /** + * Set the Background executor schedule pool size. + */ + public void setBackgroundExecutorSchedulePoolSize(int backgroundExecutorSchedulePoolSize) { + this.backgroundExecutorSchedulePoolSize = backgroundExecutorSchedulePoolSize; + } + + /** + * Return the Background executor shutdown seconds. This is the time allowed for the pool to shutdown nicely + * before it is forced shutdown. + */ + public int getBackgroundExecutorShutdownSecs() { + return backgroundExecutorShutdownSecs; + } + + /** + * Set the Background executor shutdown seconds. This is the time allowed for the pool to shutdown nicely + * before it is forced shutdown. + */ + public void setBackgroundExecutorShutdownSecs(int backgroundExecutorShutdownSecs) { + this.backgroundExecutorShutdownSecs = backgroundExecutorShutdownSecs; + } + + /** + * Return the L2 cache default max size. + */ + public int getCacheMaxSize() { + return cacheMaxSize; + } + + /** + * Set the L2 cache default max size. + */ + public void setCacheMaxSize(int cacheMaxSize) { + this.cacheMaxSize = cacheMaxSize; + } + + /** + * Return the L2 cache default max idle time in seconds. + */ + public int getCacheMaxIdleTime() { + return cacheMaxIdleTime; + } + + /** + * Set the L2 cache default max idle time in seconds. + */ + public void setCacheMaxIdleTime(int cacheMaxIdleTime) { + this.cacheMaxIdleTime = cacheMaxIdleTime; + } + + /** + * Return the L2 cache default max time to live in seconds. + */ + public int getCacheMaxTimeToLive() { + return cacheMaxTimeToLive; + } + + /** + * Set the L2 cache default max time to live in seconds. + */ + public void setCacheMaxTimeToLive(int cacheMaxTimeToLive) { + this.cacheMaxTimeToLive = cacheMaxTimeToLive; + } + + /** + * Return the L2 query cache default max size. + */ + public int getQueryCacheMaxSize() { + return queryCacheMaxSize; + } + + /** + * Set the L2 query cache default max size. + */ + public void setQueryCacheMaxSize(int queryCacheMaxSize) { + this.queryCacheMaxSize = queryCacheMaxSize; + } + + /** + * Return the L2 query cache default max idle time in seconds. + */ + public int getQueryCacheMaxIdleTime() { + return queryCacheMaxIdleTime; + } + + /** + * Set the L2 query cache default max idle time in seconds. + */ + public void setQueryCacheMaxIdleTime(int queryCacheMaxIdleTime) { + this.queryCacheMaxIdleTime = queryCacheMaxIdleTime; + } + + /** + * Return the L2 query cache default max time to live in seconds. + */ + public int getQueryCacheMaxTimeToLive() { + return queryCacheMaxTimeToLive; + } + + /** + * Set the L2 query cache default max time to live in seconds. + */ + public void setQueryCacheMaxTimeToLive(int queryCacheMaxTimeToLive) { + this.queryCacheMaxTimeToLive = queryCacheMaxTimeToLive; + } + + /** + * Return the NamingConvention. + *

+ * If none has been set the default UnderscoreNamingConvention is used. + */ + public NamingConvention getNamingConvention() { + return namingConvention; + } + + /** + * Set the NamingConvention. + *

+ * If none is set the default UnderscoreNamingConvention is used. + */ + public void setNamingConvention(NamingConvention namingConvention) { + this.namingConvention = namingConvention; + } + + /** + * Return true if all DB column and table names should use quoted identifiers. + */ + public boolean isAllQuotedIdentifiers() { + return platformConfig.isAllQuotedIdentifiers(); + } + + /** + * Set to true if all DB column and table names should use quoted identifiers. + */ + public void setAllQuotedIdentifiers(boolean allQuotedIdentifiers) { + platformConfig.setAllQuotedIdentifiers(allQuotedIdentifiers); + if (allQuotedIdentifiers) { + adjustNamingConventionForAllQuoted(); + } + } + + private void adjustNamingConventionForAllQuoted() { + if (namingConvention instanceof UnderscoreNamingConvention) { + // we need to use matching naming convention + this.namingConvention = new MatchingNamingConvention(); + } + } + + /** + * 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 Database is Document store only instance (has no JDBC DB). + */ + public void setDocStoreOnly(boolean docStoreOnly) { + this.docStoreOnly = docStoreOnly; + } + + /** + * Return the configuration for the ElasticSearch integration. + */ + public DocStoreConfig getDocStoreConfig() { + return docStoreConfig; + } + + /** + * Set the configuration for the ElasticSearch integration. + */ + public void setDocStoreConfig(DocStoreConfig docStoreConfig) { + this.docStoreConfig = docStoreConfig; + } + + /** + * Return the constraint naming convention used in DDL generation. + */ + public DbConstraintNaming getConstraintNaming() { + return platformConfig.getConstraintNaming(); + } + + /** + * Set the constraint naming convention used in DDL generation. + */ + public void setConstraintNaming(DbConstraintNaming constraintNaming) { + platformConfig.setConstraintNaming(constraintNaming); + } + + /** + * Return the configuration for AutoTune. + */ + public AutoTuneConfig getAutoTuneConfig() { + return autoTuneConfig; + } + + /** + * Set the configuration for AutoTune. + */ + public void setAutoTuneConfig(AutoTuneConfig autoTuneConfig) { + this.autoTuneConfig = autoTuneConfig; + } + + /** + * Return the DataSource. + */ + public DataSource getDataSource() { + return dataSource; + } + + /** + * Set a DataSource. + */ + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } + + /** + * Return the read only DataSource. + */ + public DataSource getReadOnlyDataSource() { + return readOnlyDataSource; + } + + /** + * Set the read only DataSource. + *

+ * Note that the DataSource is expected to use AutoCommit true mode avoiding the need + * for explicit commit (or rollback). + *

+ * This read only DataSource will be used for implicit query only transactions. It is not + * used if the transaction is created explicitly or if the query is an update or delete query. + */ + public void setReadOnlyDataSource(DataSource readOnlyDataSource) { + this.readOnlyDataSource = readOnlyDataSource; + } + + /** + * Return the configuration to build a DataSource using Ebean's own DataSource + * implementation. + */ + public DataSourceConfig getDataSourceConfig() { + return dataSourceConfig; + } + + /** + * Set the configuration required to build a DataSource using Ebean's own + * DataSource implementation. + */ + public void setDataSourceConfig(DataSourceConfig dataSourceConfig) { + this.dataSourceConfig = dataSourceConfig; + } + + /** + * Return true if Ebean should create a DataSource for use with implicit read only transactions. + */ + public boolean isAutoReadOnlyDataSource() { + return autoReadOnlyDataSource; + } + + /** + * Set to true if Ebean should create a DataSource for use with implicit read only transactions. + */ + public void setAutoReadOnlyDataSource(boolean autoReadOnlyDataSource) { + this.autoReadOnlyDataSource = autoReadOnlyDataSource; + } + + /** + * Return the configuration for the read only DataSource. + *

+ * This is only used if autoReadOnlyDataSource is true. + *

+ * The driver, url, username and password default to the configuration for the main DataSource if they are not + * set on this configuration. This means there is actually no need to set any configuration here and we only + * set configuration for url, username and password etc if it is different from the main DataSource. + */ + public DataSourceConfig getReadOnlyDataSourceConfig() { + return readOnlyDataSourceConfig; + } + + /** + * Set the configuration for the read only DataSource. + */ + public void setReadOnlyDataSourceConfig(DataSourceConfig readOnlyDataSourceConfig) { + this.readOnlyDataSourceConfig = readOnlyDataSourceConfig; + } + + /** + * Return the JNDI name of the DataSource to use. + */ + public String getDataSourceJndiName() { + return dataSourceJndiName; + } + + /** + * Set the JNDI name of the DataSource to use. + *

+ * By default a prefix of "java:comp/env/jdbc/" is used to lookup the + * DataSource. This prefix is not used if dataSourceJndiName starts with + * "java:". + */ + public void setDataSourceJndiName(String dataSourceJndiName) { + this.dataSourceJndiName = dataSourceJndiName; + } + + /** + * Return a value used to represent TRUE in the database. + *

+ * This is used for databases that do not support boolean natively. + *

+ * The value returned is either a Integer or a String (e.g. "1", or "T"). + */ + public String getDatabaseBooleanTrue() { + return platformConfig.getDatabaseBooleanTrue(); + } + + /** + * Set the value to represent TRUE in the database. + *

+ * This is used for databases that do not support boolean natively. + *

+ * The value set is either a Integer or a String (e.g. "1", or "T"). + */ + public void setDatabaseBooleanTrue(String databaseTrue) { + platformConfig.setDatabaseBooleanTrue(databaseTrue); + } + + /** + * Return a value used to represent FALSE in the database. + *

+ * This is used for databases that do not support boolean natively. + *

+ * The value returned is either a Integer or a String (e.g. "0", or "F"). + */ + public String getDatabaseBooleanFalse() { + return platformConfig.getDatabaseBooleanFalse(); + } + + /** + * Set the value to represent FALSE in the database. + *

+ * This is used for databases that do not support boolean natively. + *

+ * The value set is either a Integer or a String (e.g. "0", or "F"). + */ + public void setDatabaseBooleanFalse(String databaseFalse) { + this.platformConfig.setDatabaseBooleanFalse(databaseFalse); + } + + /** + * Return the number of DB sequence values that should be preallocated. + */ + public int getDatabaseSequenceBatchSize() { + return platformConfig.getDatabaseSequenceBatchSize(); + } + + /** + * Set the number of DB sequence values that should be preallocated and cached + * by Ebean. + *

+ * This is only used for DB's that use sequences and is a performance + * optimisation. This reduces the number of times Ebean needs to get a + * sequence value from the Database reducing network chatter. + *

+ * By default this value is 10 so when we need another Id (and don't have one + * in our cache) Ebean will fetch 10 id's from the database. Note that when + * the cache drops to have full (which is 5 by default) Ebean will fetch + * another batch of Id's in a background thread. + */ + public void setDatabaseSequenceBatch(int databaseSequenceBatchSize) { + this.platformConfig.setDatabaseSequenceBatchSize(databaseSequenceBatchSize); + } + + /** + * Return the database platform name (can be null). + *

+ * If null then the platform is determined automatically via the JDBC driver + * information. + */ + public String getDatabasePlatformName() { + return databasePlatformName; + } + + /** + * Explicitly set the database platform name + *

+ * If none is set then the platform is determined automatically via the JDBC + * driver information. + *

+ * This can be used when the Database Platform can not be automatically + * detected from the JDBC driver (possibly 3rd party JDBC driver). It is also + * useful when you want to do offline DDL generation for a database platform + * that you don't have access to. + *

+ * Values are oracle, h2, postgres, mysql, sqlserver16, sqlserver17. + */ + public void setDatabasePlatformName(String databasePlatformName) { + this.databasePlatformName = databasePlatformName; + } + + /** + * Return the database platform to use for this database. + */ + public DatabasePlatform getDatabasePlatform() { + return databasePlatform; + } + + /** + * Explicitly set the database platform to use. + *

+ * If none is set then the platform is determined via the databasePlatformName + * or automatically via the JDBC driver information. + */ + public void setDatabasePlatform(DatabasePlatform databasePlatform) { + this.databasePlatform = databasePlatform; + } + + /** + * Return the preferred DB platform IdType. + */ + public IdType getIdType() { + return platformConfig.getIdType(); + } + + /** + * Set the preferred DB platform IdType. + */ + public void setIdType(IdType idType) { + this.platformConfig.setIdType(idType); + } + + /** + * Return the EncryptKeyManager. + */ + public EncryptKeyManager getEncryptKeyManager() { + return encryptKeyManager; + } + + /** + * Set the EncryptKeyManager. + *

+ * This is required when you want to use encrypted properties. + *

+ * You can also set this in ebean.proprerties: + *

+ *

{@code
+   * # set via ebean.properties
+   * ebean.encryptKeyManager=org.avaje.tests.basic.encrypt.BasicEncyptKeyManager
+   * }
+ */ + public void setEncryptKeyManager(EncryptKeyManager encryptKeyManager) { + this.encryptKeyManager = encryptKeyManager; + } + + /** + * Return the EncryptDeployManager. + *

+ * This is optionally used to programmatically define which columns are + * encrypted instead of using the {@link Encrypted} Annotation. + */ + public EncryptDeployManager getEncryptDeployManager() { + return encryptDeployManager; + } + + /** + * Set the EncryptDeployManager. + *

+ * This is optionally used to programmatically define which columns are + * encrypted instead of using the {@link Encrypted} Annotation. + */ + public void setEncryptDeployManager(EncryptDeployManager encryptDeployManager) { + this.encryptDeployManager = encryptDeployManager; + } + + /** + * Return the Encryptor used to encrypt data on the java client side (as + * opposed to DB encryption functions). + */ + public Encryptor getEncryptor() { + return encryptor; + } + + /** + * Set the Encryptor used to encrypt data on the java client side (as opposed + * to DB encryption functions). + *

+ * Ebean has a default implementation that it will use if you do not set your + * own Encryptor implementation. + */ + public void setEncryptor(Encryptor encryptor) { + this.encryptor = encryptor; + } + + /** + * Return true if the Database instance should be created in offline mode. + */ + public boolean isDbOffline() { + return dbOffline; + } + + /** + * Set to true if the Database instance should be created in offline mode. + *

+ * Typically used to create an Database instance for DDL Migration generation + * without requiring a real DataSource / Database to connect to. + */ + public void setDbOffline(boolean dbOffline) { + this.dbOffline = dbOffline; + } + + /** + * Return the DbEncrypt used to encrypt and decrypt properties. + *

+ * Note that if this is not set then the DbPlatform may already have a + * DbEncrypt set and that will be used. + */ + public DbEncrypt getDbEncrypt() { + return dbEncrypt; + } + + /** + * Set the DbEncrypt used to encrypt and decrypt properties. + *

+ * Note that if this is not set then the DbPlatform may already have a + * DbEncrypt set (H2, MySql, Postgres and Oracle platforms have a DbEncrypt) + */ + public void setDbEncrypt(DbEncrypt dbEncrypt) { + this.dbEncrypt = dbEncrypt; + } + + /** + * Return the configuration for DB types (such as UUID and custom mappings). + */ + public PlatformConfig getPlatformConfig() { + return platformConfig; + } + + /** + * Set the configuration for DB platform (such as UUID and custom mappings). + */ + public void setPlatformConfig(PlatformConfig platformConfig) { + this.platformConfig = platformConfig; + } + + /** + * Set the DB type used to store UUID. + */ + public void setDbUuid(PlatformConfig.DbUuid dbUuid) { + this.platformConfig.setDbUuid(dbUuid); + } + + /** + * Returns the UUID version mode. + */ + public UuidVersion getUuidVersion() { + return uuidVersion; + } + + /** + * Sets the UUID version mode. + */ + public void setUuidVersion(UuidVersion uuidVersion) { + this.uuidVersion = uuidVersion; + } + + /** + * Return the UUID state file. + */ + public String getUuidStateFile() { + if (uuidStateFile == null || uuidStateFile.isEmpty()) { + // by default, add servername... + uuidStateFile = name + "-uuid.state"; + // and store it in the user's home directory + String homeDir = System.getProperty("user.home"); + if (homeDir != null && homeDir.isEmpty()) { + uuidStateFile = homeDir + "/.ebean/" + uuidStateFile; + } + } + return uuidStateFile; + } + + /** + * Set the UUID state file. + */ + public void setUuidStateFile(String uuidStateFile) { + this.uuidStateFile = uuidStateFile; + } + + /** + * Return true if LocalTime should be persisted with nanos precision. + */ + public boolean isLocalTimeWithNanos() { + return localTimeWithNanos; + } + + /** + * Set to true if LocalTime should be persisted with nanos precision. + *

+ * Otherwise it is persisted using java.sql.Time which is seconds precision. + */ + public void setLocalTimeWithNanos(boolean localTimeWithNanos) { + this.localTimeWithNanos = localTimeWithNanos; + } + + /** + * Return true if Duration should be persisted with nanos precision (SQL DECIMAL). + *

+ * Otherwise it is persisted with second precision (SQL INTEGER). + */ + public boolean isDurationWithNanos() { + return durationWithNanos; + } + + /** + * Set to true if Duration should be persisted with nanos precision (SQL DECIMAL). + *

+ * Otherwise it is persisted with second precision (SQL INTEGER). + */ + public void setDurationWithNanos(boolean durationWithNanos) { + this.durationWithNanos = durationWithNanos; + } + + /** + * Set to true to run DB migrations on server start. + *

+ * This is the same as serverConfig.getMigrationConfig().setRunMigration(). We have added this method here + * as it is often the only thing we need to configure for migrations. + */ + public void setRunMigration(boolean runMigration) { + migrationConfig.setRunMigration(runMigration); + } + + /** + * Set to true to generate the "create all" DDL on startup. + *

+ * Typically we want this on when we are running tests locally (and often using H2) + * and we want to create the full DB schema from scratch to run tests. + */ + public void setDdlGenerate(boolean ddlGenerate) { + this.ddlGenerate = ddlGenerate; + } + + /** + * Set to true to run the generated "create all DDL" on startup. + *

+ * Typically we want this on when we are running tests locally (and often using H2) + * and we want to create the full DB schema from scratch to run tests. + */ + public void setDdlRun(boolean ddlRun) { + this.ddlRun = ddlRun; + } + + /** + * Set to false if you not want to run the extra-ddl.xml scripts. (default = true) + *

+ * Typically we want this on when we are running tests. + */ + public void setDdlExtra(boolean ddlExtra) { + this.ddlExtra = ddlExtra; + } + + + /** + * Return true if the "drop all ddl" should be skipped. + *

+ * Typically we want to do this when using H2 (in memory) as our test database and the drop statements + * are not required so skipping the drop table statements etc makes it faster with less noise in the logs. + */ + public boolean isDdlCreateOnly() { + return ddlCreateOnly; + } + + /** + * Set to true if the "drop all ddl" should be skipped. + *

+ * Typically we want to do this when using H2 (in memory) as our test database and the drop statements + * are not required so skipping the drop table statements etc makes it faster with less noise in the logs. + */ + public void setDdlCreateOnly(boolean ddlCreateOnly) { + this.ddlCreateOnly = ddlCreateOnly; + } + + /** + * Return SQL script to execute after the "create all" DDL has been run. + *

+ * Typically this is a sql script that inserts test seed data when running tests. + * Place a sql script in src/test/resources that inserts test seed data. + */ + public String getDdlSeedSql() { + return ddlSeedSql; + } + + /** + * Set a SQL script to execute after the "create all" DDL has been run. + *

+ * Typically this is a sql script that inserts test seed data when running tests. + * Place a sql script in src/test/resources that inserts test seed data. + */ + public void setDdlSeedSql(String ddlSeedSql) { + this.ddlSeedSql = ddlSeedSql; + } + + /** + * Return a SQL script to execute before the "create all" DDL has been run. + */ + public String getDdlInitSql() { + return ddlInitSql; + } + + /** + * Set a SQL script to execute before the "create all" DDL has been run. + */ + public void setDdlInitSql(String ddlInitSql) { + this.ddlInitSql = ddlInitSql; + } + + /** + * Return true if the DDL should be generated. + */ + public boolean isDdlGenerate() { + return ddlGenerate; + } + + /** + * Return true if the DDL should be run. + */ + public boolean isDdlRun() { + return ddlRun; + } + + /** + * Return true, if extra-ddl.xml should be executed. + */ + public boolean isDdlExtra() { + return ddlExtra; + } + + /** + * Return true if the class path search should be disabled. + */ + public boolean isDisableClasspathSearch() { + return disableClasspathSearch; + } + + /** + * 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 Database instance just to use the + * SQL functions such as SqlQuery, SqlUpdate etc. + */ + public void setDisableClasspathSearch(boolean disableClasspathSearch) { + this.disableClasspathSearch = disableClasspathSearch; + } + + /** + * Return the mode to use for Joda LocalTime support 'normal' or 'utc'. + */ + public String getJodaLocalTimeMode() { + return jodaLocalTimeMode; + } + + /** + * Set the mode to use for Joda LocalTime support 'normal' or 'utc'. + */ + public void setJodaLocalTimeMode(String jodaLocalTimeMode) { + this.jodaLocalTimeMode = jodaLocalTimeMode; + } + + /** + * Programmatically add classes (typically entities) that this server should + * use. + *

+ * The class can be an Entity, Embedded type, ScalarType, BeanPersistListener, + * BeanFinder or BeanPersistController. + *

+ * If no classes are specified then the classes are found automatically via + * searching the class path. + *

+ * Alternatively the classes can be added via {@link #setClasses(List)}. + * + * @param cls the entity type (or other type) that should be registered by this + * database. + */ + public void addClass(Class cls) { + classes.add(cls); + } + + /** + * Register all the classes (typically entity classes). + */ + public void addAll(List> classList) { + if (classList != null && !classList.isEmpty()) { + classes.addAll(classList); + } + } + + /** + * Add a package to search for entities via class path search. + *

+ * This is only used if classes have not been explicitly specified. + */ + public void addPackage(String packageName) { + packages.add(packageName); + } + + /** + * Return packages to search for entities via class path search. + *

+ * This is only used if classes have not been explicitly specified. + */ + public List getPackages() { + return packages; + } + + /** + * Set packages to search for entities via class path search. + *

+ * This is only used if classes have not been explicitly specified. + */ + public void setPackages(List packages) { + this.packages = packages; + } + + /** + * Set the list of classes (entities, listeners, scalarTypes etc) that should + * be used for this database. + *

+ * If no classes are specified then the classes are found automatically via + * searching the class path. + *

+ * Alternatively the classes can contain added via {@link #addClass(Class)}. + */ + public void setClasses(List> classes) { + this.classes = classes; + } + + /** + * Return the classes registered for this database. Typically this includes + * entities and perhaps listeners. + */ + public List> getClasses() { + return classes; + } + + /** + * Return true if L2 bean cache should be skipped once writes have occurred on a transaction. + *

+ * This defaults to true and means that for "find by id" and "find by natural key" + * queries that normally hit L2 bean cache automatically will not do so after a write/persist + * on the transaction. + *

+ *

{@code
+   *
+   *   // assume Customer has L2 bean caching enabled ...
+   *
+   *   try (Transaction transaction = DB.beginTransaction()) {
+   *
+   *     // this uses L2 bean cache as the transaction
+   *     // ... is considered "query only" at this point
+   *     Customer.find.byId(42);
+   *
+   *     // transaction no longer "query only" once
+   *     // ... a bean has been saved etc
+   *     DB.save(someBean);
+   *
+   *     // will NOT use L2 bean cache as the transaction
+   *     // ... is no longer considered "query only"
+   *     Customer.find.byId(55);
+   *
+   *
+   *
+   *     // explicit control - please use L2 bean cache
+   *
+   *     transaction.setSkipCache(false);
+   *     Customer.find.byId(77); // hit the l2 bean cache
+   *
+   *
+   *     // explicit control - please don't use L2 bean cache
+   *
+   *     transaction.setSkipCache(true);
+   *     Customer.find.byId(99); // skips l2 bean cache
+   *
+   *   }
+   *
+   * }
+ * + * @see Transaction#setSkipCache(boolean) + */ + public boolean isSkipCacheAfterWrite() { + return skipCacheAfterWrite; + } + + /** + * Set to false when we still want to hit the cache after a write has occurred on a transaction. + */ + public void setSkipCacheAfterWrite(boolean skipCacheAfterWrite) { + this.skipCacheAfterWrite = skipCacheAfterWrite; + } + + /** + * Returns true if updates in JDBC batch default to include all properties by default. + */ + public boolean isUpdateAllPropertiesInBatch() { + return updateAllPropertiesInBatch; + } + + /** + * Set to false if by default updates in JDBC batch should not include all properties. + *

+ * This mode can be explicitly set per transaction. + * + * @see Transaction#setUpdateAllLoadedProperties(boolean) + */ + public void setUpdateAllPropertiesInBatch(boolean updateAllPropertiesInBatch) { + this.updateAllPropertiesInBatch = updateAllPropertiesInBatch; + } + + /** + * Returns the resource directory. + */ + public String getResourceDirectory() { + return resourceDirectory; + } + + /** + * Sets the resource directory. + */ + public void setResourceDirectory(String resourceDirectory) { + this.resourceDirectory = resourceDirectory; + } + + /** + * Add a custom type mapping. + *

+ *

{@code
+   *
+   *   // set the default mapping for BigDecimal.class/decimal
+   *   serverConfig.addCustomMapping(DbType.DECIMAL, "decimal(18,6)");
+   *
+   *   // set the default mapping for String.class/varchar but only for Postgres
+   *   serverConfig.addCustomMapping(DbType.VARCHAR, "text", Platform.POSTGRES);
+   *
+   * }
+ * + * @param type The DB type this mapping should apply to + * @param columnDefinition The column definition that should be used + * @param platform Optionally specify the platform this mapping should apply to. + */ + public void addCustomMapping(DbType type, String columnDefinition, Platform platform) { + platformConfig.addCustomMapping(type, columnDefinition, platform); + } + + /** + * Add a custom type mapping that applies to all platforms. + *

+ *

{@code
+   *
+   *   // set the default mapping for BigDecimal/decimal
+   *   serverConfig.addCustomMapping(DbType.DECIMAL, "decimal(18,6)");
+   *
+   *   // set the default mapping for String/varchar
+   *   serverConfig.addCustomMapping(DbType.VARCHAR, "text");
+   *
+   * }
+ * + * @param type The DB type this mapping should apply to + * @param columnDefinition The column definition that should be used + */ + public void addCustomMapping(DbType type, String columnDefinition) { + platformConfig.addCustomMapping(type, columnDefinition); + } + + /** + * Register a BeanQueryAdapter instance. + *

+ * Note alternatively you can use {@link #setQueryAdapters(List)} to set all + * the BeanQueryAdapter instances. + */ + public void add(BeanQueryAdapter beanQueryAdapter) { + queryAdapters.add(beanQueryAdapter); + } + + /** + * Return the BeanQueryAdapter instances. + */ + public List getQueryAdapters() { + return queryAdapters; + } + + /** + * Register all the BeanQueryAdapter instances. + *

+ * Note alternatively you can use {@link #add(BeanQueryAdapter)} to add + * BeanQueryAdapter instances one at a time. + */ + public void setQueryAdapters(List queryAdapters) { + this.queryAdapters = queryAdapters; + } + + /** + * Return the custom IdGenerator instances. + */ + public List getIdGenerators() { + return idGenerators; + } + + /** + * Set the custom IdGenerator instances. + */ + public void setIdGenerators(List idGenerators) { + this.idGenerators = idGenerators; + } + + /** + * Register a customer IdGenerator instance. + */ + public void add(IdGenerator idGenerator) { + idGenerators.add(idGenerator); + } + + /** + * Register a BeanPersistController instance. + *

+ * Note alternatively you can use {@link #setPersistControllers(List)} to set + * all the BeanPersistController instances. + */ + public void add(BeanPersistController beanPersistController) { + persistControllers.add(beanPersistController); + } + + /** + * Register a BeanPostLoad instance. + *

+ * Note alternatively you can use {@link #setPostLoaders(List)} to set + * all the BeanPostLoad instances. + */ + public void add(BeanPostLoad postLoad) { + postLoaders.add(postLoad); + } + + /** + * Register a BeanPostConstructListener instance. + *

+ * Note alternatively you can use {@link #setPostConstructListeners(List)} to set + * all the BeanPostConstructListener instances. + */ + public void add(BeanPostConstructListener listener) { + postConstructListeners.add(listener); + } + + /** + * Return the list of BeanFindController instances. + */ + public List getFindControllers() { + return findControllers; + } + + /** + * Set the list of BeanFindController instances. + */ + public void setFindControllers(List findControllers) { + this.findControllers = findControllers; + } + + /** + * Return the list of BeanPostLoader instances. + */ + public List getPostLoaders() { + return postLoaders; + } + + /** + * Set the list of BeanPostLoader instances. + */ + public void setPostLoaders(List postLoaders) { + this.postLoaders = postLoaders; + } + + /** + * Return the list of BeanPostLoader instances. + */ + public List getPostConstructListeners() { + return postConstructListeners; + } + + /** + * Set the list of BeanPostLoader instances. + */ + public void setPostConstructListeners(List listeners) { + this.postConstructListeners = listeners; + } + + /** + * Return the BeanPersistController instances. + */ + public List getPersistControllers() { + return persistControllers; + } + + /** + * Register all the BeanPersistController instances. + *

+ * Note alternatively you can use {@link #add(BeanPersistController)} to add + * BeanPersistController instances one at a time. + */ + public void setPersistControllers(List persistControllers) { + this.persistControllers = persistControllers; + } + + /** + * Register a BeanPersistListener instance. + *

+ * Note alternatively you can use {@link #setPersistListeners(List)} to set + * all the BeanPersistListener instances. + */ + public void add(BeanPersistListener beanPersistListener) { + persistListeners.add(beanPersistListener); + } + + /** + * Return the BeanPersistListener instances. + */ + public List getPersistListeners() { + return persistListeners; + } + + /** + * Add a BulkTableEventListener + */ + public void add(BulkTableEventListener bulkTableEventListener) { + bulkTableEventListeners.add(bulkTableEventListener); + } + + /** + * Return the list of BulkTableEventListener instances. + */ + public List getBulkTableEventListeners() { + return bulkTableEventListeners; + } + + /** + * Add a ServerConfigStartup. + */ + public void addServerConfigStartup(ServerConfigStartup configStartupListener) { + configStartupListeners.add(configStartupListener); + } + + /** + * Return the list of ServerConfigStartup instances. + */ + public List getServerConfigStartupListeners() { + return configStartupListeners; + } + + /** + * Register all the BeanPersistListener instances. + *

+ * Note alternatively you can use {@link #add(BeanPersistListener)} to add + * BeanPersistListener instances one at a time. + */ + public void setPersistListeners(List persistListeners) { + this.persistListeners = persistListeners; + } + + /** + * Return the default PersistenceContextScope to be used if one is not explicitly set on a query. + *

+ * The PersistenceContextScope can specified on each query via {@link io.ebean + * .Query#setPersistenceContextScope(io.ebean.PersistenceContextScope)}. If it + * is not set on the query this default scope is used. + * + * @see Query#setPersistenceContextScope(PersistenceContextScope) + */ + public PersistenceContextScope getPersistenceContextScope() { + // if somehow null return TRANSACTION scope + return persistenceContextScope == null ? PersistenceContextScope.TRANSACTION : persistenceContextScope; + } + + /** + * Set the PersistenceContext scope to be used if one is not explicitly set on a query. + *

+ * This defaults to {@link PersistenceContextScope#TRANSACTION}. + *

+ * The PersistenceContextScope can specified on each query via {@link io.ebean + * .Query#setPersistenceContextScope(io.ebean.PersistenceContextScope)}. If it + * is not set on the query this scope is used. + * + * @see Query#setPersistenceContextScope(PersistenceContextScope) + */ + public void setPersistenceContextScope(PersistenceContextScope persistenceContextScope) { + this.persistenceContextScope = persistenceContextScope; + } + + /** + * Return the ClassLoadConfig which is used to detect Joda, Java8 types etc and also + * create new instances of plugins given a className. + */ + public ClassLoadConfig getClassLoadConfig() { + return classLoadConfig; + } + + /** + * Set the ClassLoadConfig which is used to detect Joda, Java8 types etc and also + * create new instances of plugins given a className. + */ + public void setClassLoadConfig(ClassLoadConfig classLoadConfig) { + this.classLoadConfig = classLoadConfig; + } + + /** + * Return the service loader using the classLoader defined in ClassLoadConfig. + */ + public ServiceLoader serviceLoad(Class spiService) { + return ServiceLoader.load(spiService, classLoadConfig.getClassLoader()); + } + + /** + * Return the first service using the service loader (or null). + */ + public T service(Class spiService) { + ServiceLoader load = serviceLoad(spiService); + Iterator serviceInstances = load.iterator(); + return serviceInstances.hasNext() ? serviceInstances.next() : null; + } + + /** + * Load settings from ebean.properties. + */ + public void loadFromProperties() { + this.properties = Config.asProperties(); + configureFromProperties(); + } + + /** + * Load the settings from the given properties + */ + public void loadFromProperties(Properties properties) { + // keep the properties used for configuration so that these are available for plugins + this.properties = Config.asConfiguration().eval(properties); + configureFromProperties(); + } + + /** + * Load the settings from the given properties + */ + private void configureFromProperties() { + List autoConfigures = autoConfiguration(); + loadSettings(new PropertiesWrapper("ebean", name, properties, classLoadConfig)); + for (AutoConfigure autoConfigure : autoConfigures) { + autoConfigure.postConfigure(this); + } + } + + /** + * Use a 'plugin' to provide automatic configuration. Intended for automatic testing + * configuration with Docker containers via ebean-test-config. + */ + private List autoConfiguration() { + List list = new ArrayList<>(); + for (AutoConfigure autoConfigure : serviceLoad(AutoConfigure.class)) { + autoConfigure.preConfigure(this); + list.add(autoConfigure); + } + return list; + } + + /** + * Return the properties that we used for configuration and were set via a call to loadFromProperties(). + */ + public Properties getProperties() { + return properties; + } + + /** + * loads the data source settings to preserve existing behaviour. IMHO, if someone has set the datasource config already, + * they don't want the settings to be reloaded and reset. This allows a descending class to override this behaviour and prevent it + * from happening. + * + * @param p - The defined property source passed to load settings + */ + protected void loadDataSourceSettings(PropertiesWrapper p) { + dataSourceConfig.loadSettings(p.properties, name); + readOnlyDataSourceConfig.loadSettings(p.properties, name + "-ro"); + } + + /** + * This is broken out to allow overridden behaviour. + */ + protected void loadDocStoreSettings(PropertiesWrapper p) { + docStoreConfig.loadSettings(p); + } + + /** + * This is broken out to allow overridden behaviour. + */ + protected void loadAutoTuneSettings(PropertiesWrapper p) { + autoTuneConfig.loadSettings(p); + } + + /** + * Load the configuration settings from the properties file. + */ + protected void loadSettings(PropertiesWrapper p) { + + dbSchema = p.get("dbSchema", dbSchema); + if (dbSchema != null) { + migrationConfig.setDefaultDbSchema(dbSchema); + } + profilingConfig.loadSettings(p, name); + migrationConfig.loadSettings(p, name); + platformConfig.loadSettings(p); + if (platformConfig.isAllQuotedIdentifiers()) { + adjustNamingConventionForAllQuoted(); + } + namingConvention = createNamingConvention(p, namingConvention); + if (namingConvention != null) { + namingConvention.loadFromProperties(p); + } + if (autoTuneConfig == null) { + autoTuneConfig = new AutoTuneConfig(); + } + loadAutoTuneSettings(p); + + if (dataSourceConfig == null) { + dataSourceConfig = new DataSourceConfig(); + } + loadDataSourceSettings(p); + + if (docStoreConfig == null) { + docStoreConfig = new DocStoreConfig(); + } + loadDocStoreSettings(p); + + loadModuleInfo = p.getBoolean("loadModuleInfo", loadModuleInfo); + maxCallStack = p.getInt("maxCallStack", maxCallStack); + dumpMetricsOnShutdown = p.getBoolean("dumpMetricsOnShutdown", dumpMetricsOnShutdown); + dumpMetricsOptions = p.get("dumpMetricsOptions", dumpMetricsOptions); + queryPlanTTLSeconds = p.getInt("queryPlanTTLSeconds", queryPlanTTLSeconds); + slowQueryMillis = p.getLong("slowQueryMillis", slowQueryMillis); + collectQueryPlans = p.getBoolean("collectQueryPlans", collectQueryPlans); + collectQueryPlanThresholdMicros = p.getLong("collectQueryPlanThresholdMicros", collectQueryPlanThresholdMicros); + docStoreOnly = p.getBoolean("docStoreOnly", docStoreOnly); + disableL2Cache = p.getBoolean("disableL2Cache", disableL2Cache); + localOnlyL2Cache = p.getBoolean("localOnlyL2Cache", localOnlyL2Cache); + enabledL2Regions = p.get("enabledL2Regions", enabledL2Regions); + notifyL2CacheInForeground = p.getBoolean("notifyL2CacheInForeground", notifyL2CacheInForeground); + useJtaTransactionManager = p.getBoolean("useJtaTransactionManager", useJtaTransactionManager); + useJavaxValidationNotNull = p.getBoolean("useJavaxValidationNotNull", useJavaxValidationNotNull); + autoReadOnlyDataSource = p.getBoolean("autoReadOnlyDataSource", autoReadOnlyDataSource); + idGeneratorAutomatic = p.getBoolean("idGeneratorAutomatic", idGeneratorAutomatic); + + backgroundExecutorSchedulePoolSize = p.getInt("backgroundExecutorSchedulePoolSize", backgroundExecutorSchedulePoolSize); + backgroundExecutorShutdownSecs = p.getInt("backgroundExecutorShutdownSecs", backgroundExecutorShutdownSecs); + disableClasspathSearch = p.getBoolean("disableClasspathSearch", disableClasspathSearch); + currentUserProvider = p.createInstance(CurrentUserProvider.class, "currentUserProvider", currentUserProvider); + databasePlatform = p.createInstance(DatabasePlatform.class, "databasePlatform", databasePlatform); + encryptKeyManager = p.createInstance(EncryptKeyManager.class, "encryptKeyManager", encryptKeyManager); + encryptDeployManager = p.createInstance(EncryptDeployManager.class, "encryptDeployManager", encryptDeployManager); + encryptor = p.createInstance(Encryptor.class, "encryptor", encryptor); + dbEncrypt = p.createInstance(DbEncrypt.class, "dbEncrypt", dbEncrypt); + dbOffline = p.getBoolean("dbOffline", dbOffline); + serverCachePlugin = p.createInstance(ServerCachePlugin.class, "serverCachePlugin", serverCachePlugin); + + String packagesProp = p.get("search.packages", p.get("packages", null)); + packages = getSearchList(packagesProp, packages); + + skipCacheAfterWrite = p.getBoolean("skipCacheAfterWrite", skipCacheAfterWrite); + updateAllPropertiesInBatch = p.getBoolean("updateAllPropertiesInBatch", updateAllPropertiesInBatch); + + if (p.get("batch.mode") != null || p.get("persistBatching") != null) { + throw new IllegalArgumentException("Property 'batch.mode' or 'persistBatching' is being set but no longer used. Please change to use 'persistBatchMode'"); + } + + persistBatch = p.getEnum(PersistBatch.class, "persistBatch", persistBatch); + persistBatchOnCascade = p.getEnum(PersistBatch.class, "persistBatchOnCascade", persistBatchOnCascade); + + int batchSize = p.getInt("batch.size", persistBatchSize); + persistBatchSize = p.getInt("persistBatchSize", batchSize); + + persistenceContextScope = PersistenceContextScope.valueOf(p.get("persistenceContextScope", "TRANSACTION")); + + changeLogAsync = p.getBoolean("changeLogAsync", changeLogAsync); + changeLogIncludeInserts = p.getBoolean("changeLogIncludeInserts", changeLogIncludeInserts); + expressionEqualsWithNullAsNoop = p.getBoolean("expressionEqualsWithNullAsNoop", expressionEqualsWithNullAsNoop); + expressionNativeIlike = p.getBoolean("expressionNativeIlike", expressionNativeIlike); + + dataTimeZone = p.get("dataTimeZone", dataTimeZone); + asOfViewSuffix = p.get("asOfViewSuffix", asOfViewSuffix); + asOfSysPeriod = p.get("asOfSysPeriod", asOfSysPeriod); + historyTableSuffix = p.get("historyTableSuffix", historyTableSuffix); + dataSourceJndiName = p.get("dataSourceJndiName", dataSourceJndiName); + jdbcFetchSizeFindEach = p.getInt("jdbcFetchSizeFindEach", jdbcFetchSizeFindEach); + jdbcFetchSizeFindList = p.getInt("jdbcFetchSizeFindList", jdbcFetchSizeFindList); + databasePlatformName = p.get("databasePlatformName", databasePlatformName); + defaultOrderById = p.getBoolean("defaultOrderById", defaultOrderById); + + uuidVersion = p.getEnum(UuidVersion.class, "uuidVersion", uuidVersion); + uuidStateFile = p.get("uuidStateFile", uuidStateFile); + + localTimeWithNanos = p.getBoolean("localTimeWithNanos", localTimeWithNanos); + jodaLocalTimeMode = p.get("jodaLocalTimeMode", jodaLocalTimeMode); + + defaultEnumType = p.getEnum(EnumType.class, "defaultEnumType", defaultEnumType); + disableLazyLoading = p.getBoolean("disableLazyLoading", disableLazyLoading); + lazyLoadBatchSize = p.getInt("lazyLoadBatchSize", lazyLoadBatchSize); + queryBatchSize = p.getInt("queryBatchSize", queryBatchSize); + + jsonInclude = p.getEnum(JsonConfig.Include.class, "jsonInclude", jsonInclude); + jsonDateTime = p.getEnum(JsonConfig.DateTime.class, "jsonDateTime", jsonDateTime); + jsonDate = p.getEnum(JsonConfig.Date.class, "jsonDate", jsonDate); + + ddlGenerate = p.getBoolean("ddl.generate", ddlGenerate); + ddlRun = p.getBoolean("ddl.run", ddlRun); + ddlExtra = p.getBoolean("ddl.extra", ddlExtra); + ddlCreateOnly = p.getBoolean("ddl.createOnly", ddlCreateOnly); + ddlInitSql = p.get("ddl.initSql", ddlInitSql); + ddlSeedSql = p.get("ddl.seedSql", ddlSeedSql); + + // read tenant-configuration from config: + // tenant.mode = NONE | DB | SCHEMA | CATALOG | PARTITION + String mode = p.get("tenant.mode"); + if (mode != null) { + for (TenantMode value : TenantMode.values()) { + if (value.name().equalsIgnoreCase(mode)) { + tenantMode = value; + break; + } + } + } + + currentTenantProvider = p.createInstance(CurrentTenantProvider.class, "tenant.currentTenantProvider", currentTenantProvider); + tenantCatalogProvider = p.createInstance(TenantCatalogProvider.class, "tenant.catalogProvider", tenantCatalogProvider); + tenantSchemaProvider = p.createInstance(TenantSchemaProvider.class, "tenant.schemaProvider", tenantSchemaProvider); + tenantPartitionColumn = p.get("tenant.partitionColumn", tenantPartitionColumn); + classes = getClasses(p); + + String mappingsProp = p.get("mappingLocations", null); + mappingLocations = getSearchList(mappingsProp, mappingLocations); + } + + private NamingConvention createNamingConvention(PropertiesWrapper properties, NamingConvention namingConvention) { + NamingConvention nc = properties.createInstance(NamingConvention.class, "namingConvention", null); + return (nc != null) ? nc : namingConvention; + } + + /** + * Build the list of classes from the comma delimited string. + * + * @param properties the properties + * @return the classes + */ + private List> getClasses(PropertiesWrapper properties) { + String classNames = properties.get("classes", null); + if (classNames == null) { + return classes; + } + + List> classList = new ArrayList<>(); + String[] split = StringHelper.splitNames(classNames); + for (String cn : split) { + if (!"class".equalsIgnoreCase(cn)) { + try { + classList.add(Class.forName(cn)); + } catch (ClassNotFoundException e) { + String msg = "Error registering class [" + cn + "] from [" + classNames + "]"; + throw new RuntimeException(msg, e); + } + } + } + return classList; + } + + private List getSearchList(String searchNames, List defaultValue) { + if (searchNames != null) { + String[] entries = StringHelper.splitNames(searchNames); + List hitList = new ArrayList<>(entries.length); + Collections.addAll(hitList, entries); + return hitList; + } else { + return defaultValue; + } + } + + /** + * Return the PersistBatch mode to use for 'batchOnCascade' taking into account if the database + * platform supports getGeneratedKeys in batch mode. + */ + public PersistBatch appliedPersistBatchOnCascade() { + if (persistBatchOnCascade == PersistBatch.INHERIT) { + // use the platform default (ALL except SQL Server which has NONE) + return databasePlatform.getPersistBatchOnCascade(); + } + return persistBatchOnCascade; + } + + /** + * Return the Jackson ObjectMapper. + *

+ * Note that this is not strongly typed as Jackson ObjectMapper is an optional dependency. + */ + public Object getObjectMapper() { + return objectMapper; + } + + /** + * Set the Jackson ObjectMapper. + *

+ * Note that this is not strongly typed as Jackson ObjectMapper is an optional dependency. + */ + public void setObjectMapper(Object objectMapper) { + this.objectMapper = objectMapper; + } + + /** + * Return true if eq("someProperty", null) should to generate "1=1" rather than "is null" sql expression. + */ + public boolean isExpressionEqualsWithNullAsNoop() { + return expressionEqualsWithNullAsNoop; + } + + /** + * Set to true if you want eq("someProperty", null) to generate "1=1" rather than "is null" sql expression. + *

+ * Setting this to true has the effect that eq(propertyName, value), ieq(propertyName, value) and + * ne(propertyName, value) have no effect when the value is null. The expression factory adds a NoopExpression + * which will add "1=1" into the SQL rather than "is null". + */ + public void setExpressionEqualsWithNullAsNoop(boolean expressionEqualsWithNullAsNoop) { + this.expressionEqualsWithNullAsNoop = expressionEqualsWithNullAsNoop; + } + + /** + * Return true if native ILIKE expression should be used if supported by the database platform (e.g. Postgres). + */ + public boolean isExpressionNativeIlike() { + return expressionNativeIlike; + } + + /** + * Set to true to use native ILIKE expression if supported by the database platform (e.g. Postgres). + */ + public void setExpressionNativeIlike(boolean expressionNativeIlike) { + this.expressionNativeIlike = expressionNativeIlike; + } + + /** + * Return the enabled L2 cache regions. + */ + public String getEnabledL2Regions() { + return enabledL2Regions; + } + + /** + * Set the enabled L2 cache regions (comma delimited). + */ + public void setEnabledL2Regions(String enabledL2Regions) { + this.enabledL2Regions = enabledL2Regions; + } + + /** + * Return true if L2 cache is disabled. + */ + public boolean isDisableL2Cache() { + return disableL2Cache; + } + + /** + * Set to true to disable L2 caching. Typically useful in performance testing. + */ + public void setDisableL2Cache(boolean disableL2Cache) { + this.disableL2Cache = disableL2Cache; + } + + /** + * Return true to use local only L2 cache. Effectively ignore l2 cache plugin like ebean-redis etc. + */ + public boolean isLocalOnlyL2Cache() { + return localOnlyL2Cache; + } + + /** + * Force the use of local only L2 cache. Effectively ignore l2 cache plugin like ebean-redis etc. + */ + public void setLocalOnlyL2Cache(boolean localOnlyL2Cache) { + this.localOnlyL2Cache = localOnlyL2Cache; + } + + /** + * Returns if we use javax.validation.constraints.NotNull + */ + public boolean isUseJavaxValidationNotNull() { + return useJavaxValidationNotNull; + } + + /** + * Controls if Ebean should ignore &x64;javax.validation.contstraints.NotNull + * with respect to generating a NOT NULL column. + *

+ * Normally when Ebean sees javax NotNull annotation it means that column is defined as NOT NULL. + * Set this to false and the javax NotNull annotation is effectively ignored (and + * we instead use Ebean's own NotNull annotation or JPA Column(nullable=false) annotation. + */ + public void setUseJavaxValidationNotNull(boolean useJavaxValidationNotNull) { + this.useJavaxValidationNotNull = useJavaxValidationNotNull; + } + + /** + * Return true if L2 cache notification should run in the foreground. + */ + public boolean isNotifyL2CacheInForeground() { + return notifyL2CacheInForeground; + } + + /** + * Set this to true to run L2 cache notification in the foreground. + *

+ * In general we don't want to do that as when we use a distributed cache (like Ignite, Hazelcast etc) + * we are making network calls and we prefer to do this in background and not impact the response time + * of the executing transaction. + */ + public void setNotifyL2CacheInForeground(boolean notifyL2CacheInForeground) { + this.notifyL2CacheInForeground = notifyL2CacheInForeground; + } + + /** + * Return the query plan time to live. + */ + public int getQueryPlanTTLSeconds() { + return queryPlanTTLSeconds; + } + + /** + * Set the query plan time to live. + */ + public void setQueryPlanTTLSeconds(int queryPlanTTLSeconds) { + this.queryPlanTTLSeconds = queryPlanTTLSeconds; + } + + /** + * Run the DB migration against the DataSource. + */ + public DataSource runDbMigration(DataSource dataSource) { + if (migrationConfig.isRunMigration()) { + MigrationRunner runner = migrationConfig.createRunner(getClassLoadConfig().getClassLoader(), properties); + runner.run(dataSource); + } + return dataSource; + } + + /** + * Create a new PlatformConfig based of the one held but with overridden properties by reading + * properties with the given path and prefix. + *

+ * Typically used in Db Migration generation for many platform targets that might have different + * configuration for IdType, UUID, quoted identifiers etc. + * + * @param propertiesPath The properties path used for loading and setting properties + * @param platformPrefix The prefix used for loading and setting properties + * @return A copy of the PlatformConfig with overridden properties + */ + public PlatformConfig newPlatformConfig(String propertiesPath, String platformPrefix) { + if (properties == null) { + properties = new Properties(); + } + PropertiesWrapper p = new PropertiesWrapper(propertiesPath, platformPrefix, properties, classLoadConfig); + PlatformConfig config = new PlatformConfig(platformConfig); + config.loadSettings(p); + return config; + } + + /** + * Add a mapping location to search for xml mapping via class path search. + */ + public void addMappingLocation(String mappingLocation) { + if (mappingLocations == null) { + mappingLocations = new ArrayList<>(); + } + mappingLocations.add(mappingLocation); + } + + /** + * Return mapping locations to search for xml mapping via class path search. + */ + public List getMappingLocations() { + return mappingLocations; + } + + /** + * Set mapping locations to search for xml mapping via class path search. + *

+ * This is only used if classes have not been explicitly specified. + */ + public void setMappingLocations(List mappingLocations) { + this.mappingLocations = mappingLocations; + } + + /** + * When false we need explicit @GeneratedValue mapping to assign + * Identity or Sequence generated values. When true Id properties are automatically + * assigned Identity or Sequence without the GeneratedValue mapping. + */ + public boolean isIdGeneratorAutomatic() { + return idGeneratorAutomatic; + } + + /** + * Set to false such that Id properties require explicit @GeneratedValue + * mapping before they are assigned Identity or Sequence generation based on platform. + */ + public void setIdGeneratorAutomatic(boolean idGeneratorAutomatic) { + this.idGeneratorAutomatic = idGeneratorAutomatic; + } + + /** + * Return true if query plan capture is enabled. + */ + public boolean isCollectQueryPlans() { + return collectQueryPlans; + } + + /** + * Set to true to enable query plan capture. + */ + public void setCollectQueryPlans(boolean collectQueryPlans) { + this.collectQueryPlans = collectQueryPlans; + } + + /** + * Return the query plan collection threshold in microseconds. + */ + public long getCollectQueryPlanThresholdMicros() { + return collectQueryPlanThresholdMicros; + } + + /** + * Set the query plan collection threshold in microseconds. + */ + public void setCollectQueryPlanThresholdMicros(long collectQueryPlanThresholdMicros) { + this.collectQueryPlanThresholdMicros = collectQueryPlanThresholdMicros; + } + + /** + * Return true if metrics should be dumped when the server is shutdown. + */ + public boolean isDumpMetricsOnShutdown() { + return dumpMetricsOnShutdown; + } + + /** + * Set to true if metrics should be dumped when the server is shutdown. + */ + public void setDumpMetricsOnShutdown(boolean dumpMetricsOnShutdown) { + this.dumpMetricsOnShutdown = dumpMetricsOnShutdown; + } + + /** + * Return the options for dumping metrics. + */ + public String getDumpMetricsOptions() { + return dumpMetricsOptions; + } + + /** + * Include 'sql' or 'hash' in options such that they are included in the output. + * + * @param dumpMetricsOptions Example "sql,hash", "sql" + */ + public void setDumpMetricsOptions(String dumpMetricsOptions) { + this.dumpMetricsOptions = dumpMetricsOptions; + } + + /** + * Return true if entity classes should be loaded and registered via ModuleInfoLoader. + *

+ * When false we either register entity classes via application code or use classpath + * scanning to find and register entity classes. + */ + public boolean isAutoLoadModuleInfo() { + return loadModuleInfo && classes.isEmpty(); + } + + /** + * Set false to turn off automatic registration of entity beans. + *

+ * When using query beans that also generates a module info class that + * can register the entity bean classes (to avoid classpath scanning). + * This is on by default and setting this to false turns it off. + */ + public void setLoadModuleInfo(boolean loadModuleInfo) { + this.loadModuleInfo = loadModuleInfo; + } + + public enum UuidVersion { + VERSION4, + VERSION1, + VERSION1RND + } } diff --git a/src/main/java/io/ebean/config/DatabaseConfigProvider.java b/src/main/java/io/ebean/config/DatabaseConfigProvider.java new file mode 100644 index 000000000..7ace758e3 --- /dev/null +++ b/src/main/java/io/ebean/config/DatabaseConfigProvider.java @@ -0,0 +1,39 @@ +package io.ebean.config; + +/** + * Provides a ServiceLoader based mechanism to configure a ServerConfig. + *

+ * Provide an implementation and register it via the standard Java ServiceLoader mechanism + * via a file at META-INF/services/io.ebean.config.ServerConfigProvider. + *

+ *

+ * If you are using a DI container like Spring or Guice you are unlikely to use this but instead use a + * spring specific configuration. When we are not using a DI container we may use this mechanism to + * explicitly register the entity beans and avoid classpath scanning. + *

+ *
{@code
+ *
+ * public class EbeanConfigProvider implements DatabaseConfigProvider {
+ *
+ *   ï¼ Override
+ *   public void apply(DatabaseConfig config) {
+ *
+ *     // register the entity bean classes explicitly
+ *     config.addClass(Customer.class);
+ *     config.addClass(User.class);
+ *     ...
+ *   }
+ * }
+ *
+ * }
+ */ +public interface DatabaseConfigProvider { + + /** + * Apply the configuration to the DatabaseConfig. + *

+ * Typically we explicitly register entity bean classes and thus avoid classpath scanning. + *

+ */ + void apply(DatabaseConfig config); +} diff --git a/src/main/java/io/ebean/config/ServerConfig.java b/src/main/java/io/ebean/config/ServerConfig.java index 5e84480b5..92144f5c6 100644 --- a/src/main/java/io/ebean/config/ServerConfig.java +++ b/src/main/java/io/ebean/config/ServerConfig.java @@ -83,3117 +83,6 @@ import java.util.ServiceLoader; * @see DatabaseFactory */ @Deprecated -public class ServerConfig { +public class ServerConfig extends DatabaseConfig { - /** - * The Database name. - */ - private String name = "db"; - - /** - * Typically configuration type objects that are passed by this ServerConfig - * to plugins. For example - IgniteConfiguration passed to Ignite plugin. - */ - private final Map serviceObject = new HashMap<>(); - - private ContainerConfig containerConfig; - - /** - * The underlying properties that were used during configuration. - */ - private Properties properties; - - /** - * The resource directory. - */ - private String resourceDirectory; - - /** - * Set to true to register this Database with the DB singleton. - */ - private boolean register = true; - - /** - * Set to true if this is the default/primary database. - */ - private boolean defaultServer = true; - - /** - * Set this to true to disable class path search. - */ - private boolean disableClasspathSearch; - - private TenantMode tenantMode = TenantMode.NONE; - - private String tenantPartitionColumn = "tenant_id"; - - private CurrentTenantProvider currentTenantProvider; - - private TenantDataSourceProvider tenantDataSourceProvider; - - private TenantSchemaProvider tenantSchemaProvider; - - private TenantCatalogProvider tenantCatalogProvider; - - /** - * When true will load entity classes via ModuleInfoLoader. - *

- * NB: ModuleInfoLoader implementations are generated by querybean generator. - * Having this on and registering entity classes means we don't need to manually - * write that code or use classpath scanning to find entity classes. - */ - private boolean loadModuleInfo = true; - - /** - * List of interesting classes such as entities, embedded, ScalarTypes, - * Listeners, Finders, Controllers etc. - */ - private List> classes = new ArrayList<>(); - - /** - * The packages that are searched for interesting classes. Only used when - * classes is empty/not explicitly specified. - */ - private List packages = new ArrayList<>(); - - /** - * Configuration for the ElasticSearch integration. - */ - private DocStoreConfig docStoreConfig = new DocStoreConfig(); - - /** - * Set to true when the Database only uses Document store. - */ - private boolean docStoreOnly; - - /** - * This is used to populate @WhoCreated, @WhoModified and - * support other audit features (who executed a query etc). - */ - private CurrentUserProvider currentUserProvider; - - /** - * Config controlling the AutoTune behaviour. - */ - private AutoTuneConfig autoTuneConfig = new AutoTuneConfig(); - - /** - * The JSON format used for DateTime types. Default to millis. - */ - private JsonConfig.DateTime jsonDateTime = JsonConfig.DateTime.ISO8601; - - /** - * The JSON format used for Date types. Default to millis. - */ - private JsonConfig.Date jsonDate = JsonConfig.Date.ISO8601; - - /** - * For writing JSON specify if null values or empty collections should be excluded. - * By default all values are included. - */ - private JsonConfig.Include jsonInclude = JsonConfig.Include.ALL; - - /** - * The database platform name. Used to imply a DatabasePlatform to use. - */ - private String databasePlatformName; - - /** - * The database platform. - */ - private DatabasePlatform databasePlatform; - - /** - * JDBC fetchSize hint when using findList. Defaults to 0 leaving it up to the JDBC driver. - */ - private int jdbcFetchSizeFindList; - - /** - * JDBC fetchSize hint when using findEach/findEachWhile. Defaults to 100. Note that this does - * not apply to MySql as that gets special treatment (forward only etc). - */ - private int jdbcFetchSizeFindEach = 100; - - /** - * Suffix appended to the base table to derive the view that contains the union - * of the base table and the history table in order to support asOf queries. - */ - private String asOfViewSuffix = "_with_history"; - - /** - * Column used to support history and 'As of' queries. This column is a timestamp range - * or equivalent. - */ - private String asOfSysPeriod = "sys_period"; - - /** - * Suffix appended to the base table to derive the view that contains the union - * of the base table and the history table in order to support asOf queries. - */ - private String historyTableSuffix = "_history"; - - /** - * Use for transaction scoped batch mode. - */ - private PersistBatch persistBatch = PersistBatch.NONE; - - /** - * Use for cascade persist JDBC batch mode. INHERIT means use the platform default - * which is ALL except for SQL Server where it is NONE (as getGeneratedKeys isn't - * supported on SQL Server with JDBC batch). - */ - private PersistBatch persistBatchOnCascade = PersistBatch.INHERIT; - - private int persistBatchSize = 20; - - private EnumType defaultEnumType = EnumType.ORDINAL; - - private boolean disableLazyLoading; - - /** - * The default batch size for lazy loading - */ - private int lazyLoadBatchSize = 10; - - /** - * The default batch size for 'query joins'. - */ - private int queryBatchSize = 100; - - private boolean eagerFetchLobs; - - /** - * Timezone used to get/set Timestamp values via JDBC. - */ - private String dataTimeZone; - - private boolean ddlGenerate; - - private boolean ddlRun; - - private boolean ddlExtra = true; - - private boolean ddlCreateOnly; - - private String ddlInitSql; - - private String ddlSeedSql; - - /** - * When true L2 bean cache use is skipped after a write has occurred on a transaction. - */ - private boolean skipCacheAfterWrite = true; - - private boolean useJtaTransactionManager; - - /** - * The external transaction manager (like Spring). - */ - private ExternalTransactionManager externalTransactionManager; - - /** - * The data source (if programmatically provided). - */ - private DataSource dataSource; - - /** - * The read only data source (can be null). - */ - private DataSource readOnlyDataSource; - - /** - * The data source config. - */ - private DataSourceConfig dataSourceConfig = new DataSourceConfig(); - - /** - * When true create a read only DataSource using readOnlyDataSourceConfig defaulting values from dataSourceConfig. - * I believe this will default to true in some future release (as it has a nice performance benefit). - *

- * autoReadOnlyDataSource is an unfortunate name for this config option but I haven't come up with a better one. - */ - private boolean autoReadOnlyDataSource; - - /** - * Optional configuration for a read only data source. - */ - private DataSourceConfig readOnlyDataSourceConfig = new DataSourceConfig(); - - /** - * Optional - the database schema that should be used to own the tables etc. - */ - private String dbSchema; - - /** - * The db migration config (migration resource path etc). - */ - private DbMigrationConfig migrationConfig = new DbMigrationConfig(); - - /** - * The ClassLoadConfig used to detect Joda, Java8, Jackson etc and create plugin instances given a className. - */ - private ClassLoadConfig classLoadConfig = new ClassLoadConfig(); - - /** - * The data source JNDI name if using a JNDI DataSource. - */ - private String dataSourceJndiName; - - /** - * The naming convention. - */ - private NamingConvention namingConvention = new UnderscoreNamingConvention(); - - /** - * Behaviour of updates in JDBC batch to by default include all properties. - */ - private boolean updateAllPropertiesInBatch; - - /** - * Database platform configuration. - */ - private PlatformConfig platformConfig = new PlatformConfig(); - - /** - * The UUID version to use. - */ - private UuidVersion uuidVersion = UuidVersion.VERSION4; - - /** - * The UUID state file (for Version 1 UUIDs). By default, the file is created in - * ${HOME}/.ebean/${servername}-uuid.state - */ - private String uuidStateFile; - - /** - * The clock used for setting the timestamps (e.g. @UpdatedTimestamp) on objects. - */ - private Clock clock = Clock.systemUTC(); - - private List idGenerators = new ArrayList<>(); - private List findControllers = new ArrayList<>(); - private List persistControllers = new ArrayList<>(); - private List postLoaders = new ArrayList<>(); - private List postConstructListeners = new ArrayList<>(); - private List persistListeners = new ArrayList<>(); - private List queryAdapters = new ArrayList<>(); - private List bulkTableEventListeners = new ArrayList<>(); - private List configStartupListeners = new ArrayList<>(); - - /** - * By default inserts are included in the change log. - */ - private boolean changeLogIncludeInserts = true; - - private ChangeLogPrepare changeLogPrepare; - - private ChangeLogListener changeLogListener; - - private ChangeLogRegister changeLogRegister; - - private boolean changeLogAsync = true; - - private ReadAuditLogger readAuditLogger; - - private ReadAuditPrepare readAuditPrepare; - - private EncryptKeyManager encryptKeyManager; - - private EncryptDeployManager encryptDeployManager; - - private Encryptor encryptor; - - private boolean dbOffline; - - private DbEncrypt dbEncrypt; - - private ServerCachePlugin serverCachePlugin; - - /** - * The default PersistenceContextScope used if one is not explicitly set on a query. - */ - private PersistenceContextScope persistenceContextScope = PersistenceContextScope.TRANSACTION; - - private JsonFactory jsonFactory; - - private boolean localTimeWithNanos; - - private boolean durationWithNanos; - - private int maxCallStack = 5; - - private boolean transactionRollbackOnChecked = true; - - // configuration for the background executor service (thread pool) - - private int backgroundExecutorSchedulePoolSize = 1; - private int backgroundExecutorShutdownSecs = 30; - - // defaults for the L2 bean caching - - private int cacheMaxSize = 10000; - private int cacheMaxIdleTime = 600; - private int cacheMaxTimeToLive = 60 * 60 * 6; - - // defaults for the L2 query caching - - private int queryCacheMaxSize = 1000; - private int queryCacheMaxIdleTime = 600; - private int queryCacheMaxTimeToLive = 60 * 60 * 6; - private Object objectMapper; - - /** - * Set to true if you want eq("someProperty", null) to generate 1=1 rather than "is null" sql expression. - */ - private boolean expressionEqualsWithNullAsNoop; - - /** - * Set to true to use native ILIKE expression (if support by database platform / like Postgres). - */ - private boolean expressionNativeIlike; - - private String jodaLocalTimeMode; - - /** - * Time to live for query plans - defaults to 5 minutes. - */ - private int queryPlanTTLSeconds = 60 * 5; - - /** - * Set to true to globally disable L2 caching (typically for performance testing). - */ - private boolean disableL2Cache; - - private String enabledL2Regions; - - /** - * Set to true to effectively disable L2 cache plugins. - */ - private boolean localOnlyL2Cache; - - /** - * Should the javax.validation.constraints.NotNull enforce a notNull column in DB. - * If set to false, use io.ebean.annotation.NotNull or Column(nullable=true). - */ - private boolean useJavaxValidationNotNull = true; - - /** - * Generally we want to perform L2 cache notification in the background and not impact - * the performance of executing transactions. - */ - private boolean notifyL2CacheInForeground; - - /** - * Set to true to support query plan capture. - */ - private boolean collectQueryPlans; - - /** - * The default threshold in micros for collecting query plans. - */ - private long collectQueryPlanThresholdMicros = Long.MAX_VALUE; - - /** - * The time in millis used to determine when a query is alerted for being slow. - */ - private long slowQueryMillis; - - /** - * The listener for processing slow query events. - */ - private SlowQueryListener slowQueryListener; - - private ProfilingConfig profilingConfig = new ProfilingConfig(); - - /** - * Controls the default order by id setting of queries. See {@link Query#orderById(boolean)} - */ - private boolean defaultOrderById; - - /** - * The mappingLocations for searching xml mapping. - */ - private List mappingLocations = new ArrayList<>(); - - /** - * When true we do not need explicit GeneratedValue mapping. - */ - private boolean idGeneratorAutomatic = true; - - private boolean dumpMetricsOnShutdown; - - private String dumpMetricsOptions; - - /** - * Construct a Database Configuration for programmatically creating an Database. - */ - public ServerConfig() { - } - - /** - * Get the clock used for setting the timestamps (e.g. @UpdatedTimestamp) on objects. - */ - public Clock getClock() { - return clock; - } - - /** - * Set the clock used for setting the timestamps (e.g. @UpdatedTimestamp) on objects. - */ - public void setClock(final Clock clock) { - this.clock = clock; - } - - /** - * Return the slow query time in millis. - */ - public long getSlowQueryMillis() { - return slowQueryMillis; - } - - /** - * Set the slow query time in millis. - */ - public void setSlowQueryMillis(long slowQueryMillis) { - this.slowQueryMillis = slowQueryMillis; - } - - /** - * Return the slow query event listener. - */ - public SlowQueryListener getSlowQueryListener() { - return slowQueryListener; - } - - /** - * Set the slow query event listener. - */ - public void setSlowQueryListener(SlowQueryListener slowQueryListener) { - this.slowQueryListener = slowQueryListener; - } - - - /** - * Deprecated - look to have explicit order by. Sets the default orderById setting for queries. - */ - @Deprecated - public void setDefaultOrderById(boolean defaultOrderById) { - this.defaultOrderById = defaultOrderById; - } - - /** - * Returns the default orderById setting for queries. - */ - public boolean isDefaultOrderById() { - return defaultOrderById; - } - - /** - * Put a service object into configuration such that it can be passed to a plugin. - *

- * For example, put IgniteConfiguration in to be passed to the Ignite plugin. - */ - public void putServiceObject(String key, Object configObject) { - serviceObject.put(key, configObject); - } - - /** - * Return the service object given the key. - */ - public Object getServiceObject(String key) { - return serviceObject.get(key); - } - - /** - * Put a service object into configuration such that it can be passed to a plugin. - * - *

{@code
-   *
-   *   JedisPool jedisPool = ..
-   *
-   *   serverConfig.putServiceObject(jedisPool);
-   *
-   * }
- */ - public void putServiceObject(Object configObject) { - String key = serviceObjectKey(configObject); - serviceObject.put(key, configObject); - } - - private String serviceObjectKey(Object configObject) { - return serviceObjectKey(configObject.getClass()); - } - - private String serviceObjectKey(Class cls) { - String simpleName = cls.getSimpleName(); - return Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1); - } - - /** - * Used by plugins to obtain service objects. - * - *
{@code
-   *
-   *   JedisPool jedisPool = serverConfig.getServiceObject(JedisPool.class);
-   *
-   * }
- * - * @param cls The type of the service object to obtain - * @return The service object given the class type - */ - @SuppressWarnings("unchecked") - public

P getServiceObject(Class

cls) { - return (P) serviceObject.get(serviceObjectKey(cls)); - } - - /** - * Return the Jackson JsonFactory to use. - *

- * If not set a default implementation will be used. - */ - public JsonFactory getJsonFactory() { - return jsonFactory; - } - - /** - * Set the Jackson JsonFactory to use. - *

- * If not set a default implementation will be used. - */ - public void setJsonFactory(JsonFactory jsonFactory) { - this.jsonFactory = jsonFactory; - } - - /** - * Return the JSON format used for DateTime types. - */ - public JsonConfig.DateTime getJsonDateTime() { - return jsonDateTime; - } - - /** - * Set the JSON format to use for DateTime types. - */ - public void setJsonDateTime(JsonConfig.DateTime jsonDateTime) { - this.jsonDateTime = jsonDateTime; - } - - /** - * Return the JSON format used for Date types. - */ - public JsonConfig.Date getJsonDate() { - return jsonDate; - } - - /** - * Set the JSON format to use for Date types. - */ - public void setJsonDate(JsonConfig.Date jsonDate) { - this.jsonDate = jsonDate; - } - - /** - * Return the JSON include mode used when writing JSON. - */ - public JsonConfig.Include getJsonInclude() { - return jsonInclude; - } - - /** - * Set the JSON include mode used when writing JSON. - *

- * Set to NON_NULL or NON_EMPTY to suppress nulls or null and empty collections respectively. - */ - public void setJsonInclude(JsonConfig.Include jsonInclude) { - this.jsonInclude = jsonInclude; - } - - /** - * Return the name of the Database. - */ - public String getName() { - return name; - } - - /** - * Set the name of the Database. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Return the container / clustering configuration. - *

- * The container holds all the Database instances and provides clustering communication - * services to all the Database instances. - */ - public ContainerConfig getContainerConfig() { - return containerConfig; - } - - /** - * Set the container / clustering configuration. - *

- * 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; - } - - /** - * Return true if this server should be registered with the Ebean singleton - * when it is created. - *

- * By default this is set to true. - */ - public boolean isRegister() { - return register; - } - - /** - * Set to false if you do not want this server to be registered with the Ebean - * singleton when it is created. - *

- * By default this is set to true. - */ - public void setRegister(boolean register) { - this.register = register; - } - - /** - * Return true if this server should be registered as the "default" server - * with the Ebean singleton. - *

- * This is only used when {@link #setRegister(boolean)} is also true. - */ - public boolean isDefaultServer() { - return defaultServer; - } - - /** - * Set false if you do not want this Database to be registered as the "default" database - * with the DB singleton. - *

- * This is only used when {@link #setRegister(boolean)} is also true. - */ - public void setDefaultServer(boolean defaultServer) { - this.defaultServer = defaultServer; - } - - /** - * Return the CurrentUserProvider. This is used to populate @WhoCreated, @WhoModified and - * support other audit features (who executed a query etc). - */ - public CurrentUserProvider getCurrentUserProvider() { - return currentUserProvider; - } - - /** - * Set the CurrentUserProvider. This is used to populate @WhoCreated, @WhoModified and - * support other audit features (who executed a query etc). - */ - public void setCurrentUserProvider(CurrentUserProvider currentUserProvider) { - this.currentUserProvider = currentUserProvider; - } - - /** - * Return the tenancy mode used. - */ - public TenantMode getTenantMode() { - return tenantMode; - } - - /** - * Set the tenancy mode to use. - */ - public void setTenantMode(TenantMode tenantMode) { - this.tenantMode = tenantMode; - } - - /** - * Return the column name used for TenantMode.PARTITION. - */ - public String getTenantPartitionColumn() { - return tenantPartitionColumn; - } - - /** - * Set the column name used for TenantMode.PARTITION. - */ - public void setTenantPartitionColumn(String tenantPartitionColumn) { - this.tenantPartitionColumn = tenantPartitionColumn; - } - - /** - * Return the current tenant provider. - */ - public CurrentTenantProvider getCurrentTenantProvider() { - return currentTenantProvider; - } - - /** - * Set the current tenant provider. - */ - public void setCurrentTenantProvider(CurrentTenantProvider currentTenantProvider) { - this.currentTenantProvider = currentTenantProvider; - } - - /** - * Return the tenancy datasource provider. - */ - public TenantDataSourceProvider getTenantDataSourceProvider() { - return tenantDataSourceProvider; - } - - /** - * Set the tenancy datasource provider. - */ - public void setTenantDataSourceProvider(TenantDataSourceProvider tenantDataSourceProvider) { - this.tenantDataSourceProvider = tenantDataSourceProvider; - } - - /** - * Return the tenancy schema provider. - */ - public TenantSchemaProvider getTenantSchemaProvider() { - return tenantSchemaProvider; - } - - /** - * Set the tenancy schema provider. - */ - public void setTenantSchemaProvider(TenantSchemaProvider tenantSchemaProvider) { - this.tenantSchemaProvider = tenantSchemaProvider; - } - - /** - * Return the tenancy catalog provider. - */ - public TenantCatalogProvider getTenantCatalogProvider() { - return tenantCatalogProvider; - } - - /** - * Set the tenancy catalog provider. - */ - public void setTenantCatalogProvider(TenantCatalogProvider tenantCatalogProvider) { - this.tenantCatalogProvider = tenantCatalogProvider; - } - - /** - * Return the PersistBatch mode to use by default at the transaction level. - *

- * When INSERT or ALL is used then save(), delete() etc do not execute immediately but instead go into - * a JDBC batch execute buffer that is flushed. The buffer is flushed if a query is executed, transaction ends - * or the batch size is meet. - */ - public PersistBatch getPersistBatch() { - return persistBatch; - } - - /** - * Set the JDBC batch mode to use at the transaction level. - *

- * When INSERT or ALL is used then save(), delete() etc do not execute immediately but instead go into - * a JDBC batch execute buffer that is flushed. The buffer is flushed if a query is executed, transaction ends - * or the batch size is meet. - */ - public void setPersistBatch(PersistBatch persistBatch) { - this.persistBatch = persistBatch; - } - - /** - * Return the JDBC batch mode to use per save(), delete(), insert() or update() request. - *

- * This makes sense when a save() or delete() cascades and executes multiple child statements. The best case - * for this is when saving a master/parent bean this cascade inserts many detail/child beans. - *

- * This only takes effect when the persistBatch mode at the transaction level does not take effect. - */ - public PersistBatch getPersistBatchOnCascade() { - return persistBatchOnCascade; - } - - /** - * Set the JDBC batch mode to use per save(), delete(), insert() or update() request. - *

- * This makes sense when a save() or delete() etc cascades and executes multiple child statements. The best caase - * for this is when saving a master/parent bean this cascade inserts many detail/child beans. - *

- * This only takes effect when the persistBatch mode at the transaction level does not take effect. - */ - public void setPersistBatchOnCascade(PersistBatch persistBatchOnCascade) { - this.persistBatchOnCascade = persistBatchOnCascade; - } - - /** - * Deprecated, please migrate to using setPersistBatch(). - *

- * Set to true if you what to use JDBC batching for persisting and deleting beans. - *

- * With this Ebean will batch up persist requests and use the JDBC batch api. - * This is a performance optimisation designed to reduce the network chatter. - *

- * When true this is equivalent to {@code setPersistBatch(PersistBatch.ALL)} or - * when false to {@code setPersistBatch(PersistBatch.NONE)} - */ - public void setPersistBatching(boolean persistBatching) { - this.persistBatch = (persistBatching) ? PersistBatch.ALL : PersistBatch.NONE; - } - - /** - * Return the batch size used for JDBC batching. This defaults to 20. - */ - public int getPersistBatchSize() { - return persistBatchSize; - } - - /** - * Set the batch size used for JDBC batching. If unset this defaults to 20. - *

- * You can also set the batch size on the transaction. - * - * @see Transaction#setBatchSize(int) - */ - public void setPersistBatchSize(int persistBatchSize) { - this.persistBatchSize = persistBatchSize; - } - - /** - * Gets the query batch size. This defaults to 100. - * - * @return the query batch size - */ - public int getQueryBatchSize() { - return queryBatchSize; - } - - /** - * Sets the query batch size. This defaults to 100. - * - * @param queryBatchSize the new query batch size - */ - public void setQueryBatchSize(int queryBatchSize) { - this.queryBatchSize = queryBatchSize; - } - - public EnumType getDefaultEnumType() { - return defaultEnumType; - } - - public void setDefaultEnumType(EnumType defaultEnumType) { - this.defaultEnumType = defaultEnumType; - } - - /** - * Return true if lazy loading is disabled on queries by default. - */ - public boolean isDisableLazyLoading() { - return disableLazyLoading; - } - - /** - * Set to true to disable lazy loading by default. - *

- * It can be turned on per query via {@link Query#setDisableLazyLoading(boolean)}. - */ - public void setDisableLazyLoading(boolean disableLazyLoading) { - this.disableLazyLoading = disableLazyLoading; - } - - /** - * Return the default batch size for lazy loading of beans and collections. - */ - public int getLazyLoadBatchSize() { - return lazyLoadBatchSize; - } - - /** - * Set the default batch size for lazy loading. - *

- * This is the number of beans or collections loaded when lazy loading is - * invoked by default. - *

- * The default value is for this is 10 (load 10 beans or collections). - *

- * You can explicitly control the lazy loading batch size for a given join on - * a query using +lazy(batchSize) or JoinConfig. - */ - public void setLazyLoadBatchSize(int lazyLoadBatchSize) { - this.lazyLoadBatchSize = lazyLoadBatchSize; - } - - /** - * Set the number of sequences to fetch/preallocate when using DB sequences. - *

- * This is a performance optimisation to reduce the number times Ebean - * requests a sequence to be used as an Id for a bean (aka reduce network - * chatter). - - */ - public void setDatabaseSequenceBatchSize(int databaseSequenceBatchSize) { - platformConfig.setDatabaseSequenceBatchSize(databaseSequenceBatchSize); - } - - /** - * Return the default JDBC fetchSize hint for findList queries. - */ - public int getJdbcFetchSizeFindList() { - return jdbcFetchSizeFindList; - } - - /** - * Set the default JDBC fetchSize hint for findList queries. - */ - public void setJdbcFetchSizeFindList(int jdbcFetchSizeFindList) { - this.jdbcFetchSizeFindList = jdbcFetchSizeFindList; - } - - /** - * Return the default JDBC fetchSize hint for findEach/findEachWhile queries. - */ - public int getJdbcFetchSizeFindEach() { - return jdbcFetchSizeFindEach; - } - - /** - * Set the default JDBC fetchSize hint for findEach/findEachWhile queries. - */ - public void setJdbcFetchSizeFindEach(int jdbcFetchSizeFindEach) { - this.jdbcFetchSizeFindEach = jdbcFetchSizeFindEach; - } - - /** - * Return the ChangeLogPrepare. - *

- * This is used to set user context information to the ChangeSet in the - * foreground thread prior to the logging occurring in a background thread. - */ - public ChangeLogPrepare getChangeLogPrepare() { - return changeLogPrepare; - } - - /** - * Set the ChangeLogPrepare. - *

- * This is used to set user context information to the ChangeSet in the - * foreground thread prior to the logging occurring in a background thread. - */ - public void setChangeLogPrepare(ChangeLogPrepare changeLogPrepare) { - this.changeLogPrepare = changeLogPrepare; - } - - /** - * Return the ChangeLogListener which actually performs the logging of change sets - * in the background. - */ - public ChangeLogListener getChangeLogListener() { - return changeLogListener; - } - - /** - * Set the ChangeLogListener which actually performs the logging of change sets - * in the background. - */ - public void setChangeLogListener(ChangeLogListener changeLogListener) { - this.changeLogListener = changeLogListener; - } - - /** - * Return the ChangeLogRegister which controls which ChangeLogFilter is used for each - * bean type and in this way provide fine grained control over which persist requests - * are included in the change log. - */ - public ChangeLogRegister getChangeLogRegister() { - return changeLogRegister; - } - - /** - * Set the ChangeLogRegister which controls which ChangeLogFilter is used for each - * bean type and in this way provide fine grained control over which persist requests - * are included in the change log. - */ - public void setChangeLogRegister(ChangeLogRegister changeLogRegister) { - this.changeLogRegister = changeLogRegister; - } - - /** - * Return true if inserts should be included in the change log by default. - */ - public boolean isChangeLogIncludeInserts() { - return changeLogIncludeInserts; - } - - /** - * Set if inserts should be included in the change log by default. - */ - public void setChangeLogIncludeInserts(boolean changeLogIncludeInserts) { - this.changeLogIncludeInserts = changeLogIncludeInserts; - } - - /** - * Return true (default) if the changelog should be written async. - */ - public boolean isChangeLogAsync() { - return changeLogAsync; - } - - /** - * Sets if the changelog should be written async (default = true). - */ - public void setChangeLogAsync(boolean changeLogAsync) { - this.changeLogAsync = changeLogAsync; - } - - /** - * Return the ReadAuditLogger to use. - */ - public ReadAuditLogger getReadAuditLogger() { - return readAuditLogger; - } - - /** - * Set the ReadAuditLogger to use. If not set the default implementation is used - * which logs the read events in JSON format to a standard named SLF4J logger - * (which can be configured in say logback to log to a separate log file). - */ - public void setReadAuditLogger(ReadAuditLogger readAuditLogger) { - this.readAuditLogger = readAuditLogger; - } - - /** - * Return the ReadAuditPrepare to use. - */ - public ReadAuditPrepare getReadAuditPrepare() { - return readAuditPrepare; - } - - /** - * Set the ReadAuditPrepare to use. - *

- * It is expected that an implementation is used that read user context information - * (user id, user ip address etc) and sets it on the ReadEvent bean before it is sent - * to the ReadAuditLogger. - */ - public void setReadAuditPrepare(ReadAuditPrepare readAuditPrepare) { - this.readAuditPrepare = readAuditPrepare; - } - - /** - * Return the configuration for profiling. - */ - public ProfilingConfig getProfilingConfig() { - return profilingConfig; - } - - /** - * Set the configuration for profiling. - */ - public void setProfilingConfig(ProfilingConfig profilingConfig) { - this.profilingConfig = profilingConfig; - } - - /** - * Return the DB schema to use. - */ - public String getDbSchema() { - return dbSchema; - } - - /** - * Set the DB schema to use. This specifies to use this schema for: - *

    - *
  • Running Database migrations - Create and use the DB schema
  • - *
  • Testing DDL - Create-all.sql DDL execution creates and uses schema
  • - *
  • Testing Docker - Set default schema on connection URL
  • - *
- */ - public void setDbSchema(String dbSchema) { - this.dbSchema = dbSchema; - } - - /** - * Return the DB migration configuration. - */ - public DbMigrationConfig getMigrationConfig() { - return migrationConfig; - } - - /** - * Set the DB migration configuration. - */ - public void setMigrationConfig(DbMigrationConfig migrationConfig) { - this.migrationConfig = migrationConfig; - } - - /** - * Return the Geometry SRID. - */ - public int getGeometrySRID() { - return platformConfig.getGeometrySRID(); - } - - /** - * Set the Geometry SRID. - */ - public void setGeometrySRID(int geometrySRID) { - platformConfig.setGeometrySRID(geometrySRID); - } - - /** - * Return the time zone to use when reading/writing Timestamps via JDBC. - *

- * When set a Calendar object is used in JDBC calls when reading/writing Timestamp objects. - */ - public String getDataTimeZone() { - return System.getProperty("ebean.dataTimeZone", dataTimeZone); - } - - /** - * Set the time zone to use when reading/writing Timestamps via JDBC. - */ - public void setDataTimeZone(String dataTimeZone) { - this.dataTimeZone = dataTimeZone; - } - - /** - * Return the suffix appended to the base table to derive the view that contains the union - * of the base table and the history table in order to support asOf queries. - */ - public String getAsOfViewSuffix() { - return asOfViewSuffix; - } - - /** - * Set the suffix appended to the base table to derive the view that contains the union - * of the base table and the history table in order to support asOf queries. - */ - public void setAsOfViewSuffix(String asOfViewSuffix) { - this.asOfViewSuffix = asOfViewSuffix; - } - - /** - * Return the database column used to support history and 'As of' queries. This column is a timestamp range - * or equivalent. - */ - public String getAsOfSysPeriod() { - return asOfSysPeriod; - } - - /** - * Set the database column used to support history and 'As of' queries. This column is a timestamp range - * or equivalent. - */ - public void setAsOfSysPeriod(String asOfSysPeriod) { - this.asOfSysPeriod = asOfSysPeriod; - } - - /** - * Return the history table suffix (defaults to _history). - */ - public String getHistoryTableSuffix() { - return historyTableSuffix; - } - - /** - * Set the history table suffix. - */ - public void setHistoryTableSuffix(String historyTableSuffix) { - this.historyTableSuffix = historyTableSuffix; - } - - /** - * Return true if we are running in a JTA Transaction manager. - */ - public boolean isUseJtaTransactionManager() { - return useJtaTransactionManager; - } - - /** - * Set to true if we are running in a JTA Transaction manager. - */ - public void setUseJtaTransactionManager(boolean useJtaTransactionManager) { - this.useJtaTransactionManager = useJtaTransactionManager; - } - - /** - * Return the external transaction manager. - */ - public ExternalTransactionManager getExternalTransactionManager() { - return externalTransactionManager; - } - - /** - * Set the external transaction manager. - */ - public void setExternalTransactionManager(ExternalTransactionManager externalTransactionManager) { - this.externalTransactionManager = externalTransactionManager; - } - - /** - * Return the ServerCachePlugin. - */ - public ServerCachePlugin getServerCachePlugin() { - return serverCachePlugin; - } - - /** - * Set the ServerCachePlugin to use. - */ - public void setServerCachePlugin(ServerCachePlugin serverCachePlugin) { - this.serverCachePlugin = serverCachePlugin; - } - - /** - * Return true if LOB's should default to fetch eager. - * By default this is set to false and LOB's must be explicitly fetched. - */ - public boolean isEagerFetchLobs() { - return eagerFetchLobs; - } - - /** - * Set to true if you want LOB's to be fetch eager by default. - * By default this is set to false and LOB's must be explicitly fetched. - */ - public void setEagerFetchLobs(boolean eagerFetchLobs) { - this.eagerFetchLobs = eagerFetchLobs; - } - - /** - * Return the max call stack to use for origin location. - */ - public int getMaxCallStack() { - return maxCallStack; - } - - /** - * Set the max call stack to use for origin location. - */ - public void setMaxCallStack(int maxCallStack) { - this.maxCallStack = maxCallStack; - } - - /** - * Return true if transactions should rollback on checked exceptions. - */ - public boolean isTransactionRollbackOnChecked() { - return transactionRollbackOnChecked; - } - - /** - * Set to true if transactions should by default rollback on checked exceptions. - */ - public void setTransactionRollbackOnChecked(boolean transactionRollbackOnChecked) { - this.transactionRollbackOnChecked = transactionRollbackOnChecked; - } - - /** - * Return the Background executor schedule pool size. Defaults to 1. - */ - public int getBackgroundExecutorSchedulePoolSize() { - return backgroundExecutorSchedulePoolSize; - } - - /** - * Set the Background executor schedule pool size. - */ - public void setBackgroundExecutorSchedulePoolSize(int backgroundExecutorSchedulePoolSize) { - this.backgroundExecutorSchedulePoolSize = backgroundExecutorSchedulePoolSize; - } - - /** - * Return the Background executor shutdown seconds. This is the time allowed for the pool to shutdown nicely - * before it is forced shutdown. - */ - public int getBackgroundExecutorShutdownSecs() { - return backgroundExecutorShutdownSecs; - } - - /** - * Set the Background executor shutdown seconds. This is the time allowed for the pool to shutdown nicely - * before it is forced shutdown. - */ - public void setBackgroundExecutorShutdownSecs(int backgroundExecutorShutdownSecs) { - this.backgroundExecutorShutdownSecs = backgroundExecutorShutdownSecs; - } - - /** - * Return the L2 cache default max size. - */ - public int getCacheMaxSize() { - return cacheMaxSize; - } - - /** - * Set the L2 cache default max size. - */ - public void setCacheMaxSize(int cacheMaxSize) { - this.cacheMaxSize = cacheMaxSize; - } - - /** - * Return the L2 cache default max idle time in seconds. - */ - public int getCacheMaxIdleTime() { - return cacheMaxIdleTime; - } - - /** - * Set the L2 cache default max idle time in seconds. - */ - public void setCacheMaxIdleTime(int cacheMaxIdleTime) { - this.cacheMaxIdleTime = cacheMaxIdleTime; - } - - /** - * Return the L2 cache default max time to live in seconds. - */ - public int getCacheMaxTimeToLive() { - return cacheMaxTimeToLive; - } - - /** - * Set the L2 cache default max time to live in seconds. - */ - public void setCacheMaxTimeToLive(int cacheMaxTimeToLive) { - this.cacheMaxTimeToLive = cacheMaxTimeToLive; - } - - /** - * Return the L2 query cache default max size. - */ - public int getQueryCacheMaxSize() { - return queryCacheMaxSize; - } - - /** - * Set the L2 query cache default max size. - */ - public void setQueryCacheMaxSize(int queryCacheMaxSize) { - this.queryCacheMaxSize = queryCacheMaxSize; - } - - /** - * Return the L2 query cache default max idle time in seconds. - */ - public int getQueryCacheMaxIdleTime() { - return queryCacheMaxIdleTime; - } - - /** - * Set the L2 query cache default max idle time in seconds. - */ - public void setQueryCacheMaxIdleTime(int queryCacheMaxIdleTime) { - this.queryCacheMaxIdleTime = queryCacheMaxIdleTime; - } - - /** - * Return the L2 query cache default max time to live in seconds. - */ - public int getQueryCacheMaxTimeToLive() { - return queryCacheMaxTimeToLive; - } - - /** - * Set the L2 query cache default max time to live in seconds. - */ - public void setQueryCacheMaxTimeToLive(int queryCacheMaxTimeToLive) { - this.queryCacheMaxTimeToLive = queryCacheMaxTimeToLive; - } - - /** - * Return the NamingConvention. - *

- * If none has been set the default UnderscoreNamingConvention is used. - */ - public NamingConvention getNamingConvention() { - return namingConvention; - } - - /** - * Set the NamingConvention. - *

- * If none is set the default UnderscoreNamingConvention is used. - */ - public void setNamingConvention(NamingConvention namingConvention) { - this.namingConvention = namingConvention; - } - - /** - * Return true if all DB column and table names should use quoted identifiers. - */ - public boolean isAllQuotedIdentifiers() { - return platformConfig.isAllQuotedIdentifiers(); - } - - /** - * Set to true if all DB column and table names should use quoted identifiers. - */ - public void setAllQuotedIdentifiers(boolean allQuotedIdentifiers) { - platformConfig.setAllQuotedIdentifiers(allQuotedIdentifiers); - if (allQuotedIdentifiers) { - adjustNamingConventionForAllQuoted(); - } - } - - private void adjustNamingConventionForAllQuoted() { - if (namingConvention instanceof UnderscoreNamingConvention) { - // we need to use matching naming convention - this.namingConvention = new MatchingNamingConvention(); - } - } - - /** - * 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 Database is Document store only instance (has no JDBC DB). - */ - public void setDocStoreOnly(boolean docStoreOnly) { - this.docStoreOnly = docStoreOnly; - } - - /** - * Return the configuration for the ElasticSearch integration. - */ - public DocStoreConfig getDocStoreConfig() { - return docStoreConfig; - } - - /** - * Set the configuration for the ElasticSearch integration. - */ - public void setDocStoreConfig(DocStoreConfig docStoreConfig) { - this.docStoreConfig = docStoreConfig; - } - - /** - * Return the constraint naming convention used in DDL generation. - */ - public DbConstraintNaming getConstraintNaming() { - return platformConfig.getConstraintNaming(); - } - - /** - * Set the constraint naming convention used in DDL generation. - */ - public void setConstraintNaming(DbConstraintNaming constraintNaming) { - platformConfig.setConstraintNaming(constraintNaming); - } - - /** - * Return the configuration for AutoTune. - */ - public AutoTuneConfig getAutoTuneConfig() { - return autoTuneConfig; - } - - /** - * Set the configuration for AutoTune. - */ - public void setAutoTuneConfig(AutoTuneConfig autoTuneConfig) { - this.autoTuneConfig = autoTuneConfig; - } - - /** - * Return the DataSource. - */ - public DataSource getDataSource() { - return dataSource; - } - - /** - * Set a DataSource. - */ - public void setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - } - - /** - * Return the read only DataSource. - */ - public DataSource getReadOnlyDataSource() { - return readOnlyDataSource; - } - - /** - * Set the read only DataSource. - *

- * Note that the DataSource is expected to use AutoCommit true mode avoiding the need - * for explicit commit (or rollback). - *

- * This read only DataSource will be used for implicit query only transactions. It is not - * used if the transaction is created explicitly or if the query is an update or delete query. - */ - public void setReadOnlyDataSource(DataSource readOnlyDataSource) { - this.readOnlyDataSource = readOnlyDataSource; - } - - /** - * Return the configuration to build a DataSource using Ebean's own DataSource - * implementation. - */ - public DataSourceConfig getDataSourceConfig() { - return dataSourceConfig; - } - - /** - * Set the configuration required to build a DataSource using Ebean's own - * DataSource implementation. - */ - public void setDataSourceConfig(DataSourceConfig dataSourceConfig) { - this.dataSourceConfig = dataSourceConfig; - } - - /** - * Return true if Ebean should create a DataSource for use with implicit read only transactions. - */ - public boolean isAutoReadOnlyDataSource() { - return autoReadOnlyDataSource; - } - - /** - * Set to true if Ebean should create a DataSource for use with implicit read only transactions. - */ - public void setAutoReadOnlyDataSource(boolean autoReadOnlyDataSource) { - this.autoReadOnlyDataSource = autoReadOnlyDataSource; - } - - /** - * Return the configuration for the read only DataSource. - *

- * This is only used if autoReadOnlyDataSource is true. - *

- * The driver, url, username and password default to the configuration for the main DataSource if they are not - * set on this configuration. This means there is actually no need to set any configuration here and we only - * set configuration for url, username and password etc if it is different from the main DataSource. - */ - public DataSourceConfig getReadOnlyDataSourceConfig() { - return readOnlyDataSourceConfig; - } - - /** - * Set the configuration for the read only DataSource. - */ - public void setReadOnlyDataSourceConfig(DataSourceConfig readOnlyDataSourceConfig) { - this.readOnlyDataSourceConfig = readOnlyDataSourceConfig; - } - - /** - * Return the JNDI name of the DataSource to use. - */ - public String getDataSourceJndiName() { - return dataSourceJndiName; - } - - /** - * Set the JNDI name of the DataSource to use. - *

- * By default a prefix of "java:comp/env/jdbc/" is used to lookup the - * DataSource. This prefix is not used if dataSourceJndiName starts with - * "java:". - */ - public void setDataSourceJndiName(String dataSourceJndiName) { - this.dataSourceJndiName = dataSourceJndiName; - } - - /** - * Return a value used to represent TRUE in the database. - *

- * This is used for databases that do not support boolean natively. - *

- * The value returned is either a Integer or a String (e.g. "1", or "T"). - */ - public String getDatabaseBooleanTrue() { - return platformConfig.getDatabaseBooleanTrue(); - } - - /** - * Set the value to represent TRUE in the database. - *

- * This is used for databases that do not support boolean natively. - *

- * The value set is either a Integer or a String (e.g. "1", or "T"). - */ - public void setDatabaseBooleanTrue(String databaseTrue) { - platformConfig.setDatabaseBooleanTrue(databaseTrue); - } - - /** - * Return a value used to represent FALSE in the database. - *

- * This is used for databases that do not support boolean natively. - *

- * The value returned is either a Integer or a String (e.g. "0", or "F"). - */ - public String getDatabaseBooleanFalse() { - return platformConfig.getDatabaseBooleanFalse(); - } - - /** - * Set the value to represent FALSE in the database. - *

- * This is used for databases that do not support boolean natively. - *

- * The value set is either a Integer or a String (e.g. "0", or "F"). - */ - public void setDatabaseBooleanFalse(String databaseFalse) { - this.platformConfig.setDatabaseBooleanFalse(databaseFalse); - } - - /** - * Return the number of DB sequence values that should be preallocated. - */ - public int getDatabaseSequenceBatchSize() { - return platformConfig.getDatabaseSequenceBatchSize(); - } - - /** - * Set the number of DB sequence values that should be preallocated and cached - * by Ebean. - *

- * This is only used for DB's that use sequences and is a performance - * optimisation. This reduces the number of times Ebean needs to get a - * sequence value from the Database reducing network chatter. - *

- * By default this value is 10 so when we need another Id (and don't have one - * in our cache) Ebean will fetch 10 id's from the database. Note that when - * the cache drops to have full (which is 5 by default) Ebean will fetch - * another batch of Id's in a background thread. - */ - public void setDatabaseSequenceBatch(int databaseSequenceBatchSize) { - this.platformConfig.setDatabaseSequenceBatchSize(databaseSequenceBatchSize); - } - - /** - * Return the database platform name (can be null). - *

- * If null then the platform is determined automatically via the JDBC driver - * information. - */ - public String getDatabasePlatformName() { - return databasePlatformName; - } - - /** - * Explicitly set the database platform name - *

- * If none is set then the platform is determined automatically via the JDBC - * driver information. - *

- * This can be used when the Database Platform can not be automatically - * detected from the JDBC driver (possibly 3rd party JDBC driver). It is also - * useful when you want to do offline DDL generation for a database platform - * that you don't have access to. - *

- * Values are oracle, h2, postgres, mysql, sqlserver16, sqlserver17. - */ - public void setDatabasePlatformName(String databasePlatformName) { - this.databasePlatformName = databasePlatformName; - } - - /** - * Return the database platform to use for this database. - */ - public DatabasePlatform getDatabasePlatform() { - return databasePlatform; - } - - /** - * Explicitly set the database platform to use. - *

- * If none is set then the platform is determined via the databasePlatformName - * or automatically via the JDBC driver information. - */ - public void setDatabasePlatform(DatabasePlatform databasePlatform) { - this.databasePlatform = databasePlatform; - } - - /** - * Return the preferred DB platform IdType. - */ - public IdType getIdType() { - return platformConfig.getIdType(); - } - - /** - * Set the preferred DB platform IdType. - */ - public void setIdType(IdType idType) { - this.platformConfig.setIdType(idType); - } - - /** - * Return the EncryptKeyManager. - */ - public EncryptKeyManager getEncryptKeyManager() { - return encryptKeyManager; - } - - /** - * Set the EncryptKeyManager. - *

- * This is required when you want to use encrypted properties. - *

- * You can also set this in ebean.proprerties: - *

- *

{@code
-   * # set via ebean.properties
-   * ebean.encryptKeyManager=org.avaje.tests.basic.encrypt.BasicEncyptKeyManager
-   * }
- */ - public void setEncryptKeyManager(EncryptKeyManager encryptKeyManager) { - this.encryptKeyManager = encryptKeyManager; - } - - /** - * Return the EncryptDeployManager. - *

- * This is optionally used to programmatically define which columns are - * encrypted instead of using the {@link Encrypted} Annotation. - */ - public EncryptDeployManager getEncryptDeployManager() { - return encryptDeployManager; - } - - /** - * Set the EncryptDeployManager. - *

- * This is optionally used to programmatically define which columns are - * encrypted instead of using the {@link Encrypted} Annotation. - */ - public void setEncryptDeployManager(EncryptDeployManager encryptDeployManager) { - this.encryptDeployManager = encryptDeployManager; - } - - /** - * Return the Encryptor used to encrypt data on the java client side (as - * opposed to DB encryption functions). - */ - public Encryptor getEncryptor() { - return encryptor; - } - - /** - * Set the Encryptor used to encrypt data on the java client side (as opposed - * to DB encryption functions). - *

- * Ebean has a default implementation that it will use if you do not set your - * own Encryptor implementation. - */ - public void setEncryptor(Encryptor encryptor) { - this.encryptor = encryptor; - } - - /** - * Return true if the Database instance should be created in offline mode. - */ - public boolean isDbOffline() { - return dbOffline; - } - - /** - * Set to true if the Database instance should be created in offline mode. - *

- * Typically used to create an Database instance for DDL Migration generation - * without requiring a real DataSource / Database to connect to. - */ - public void setDbOffline(boolean dbOffline) { - this.dbOffline = dbOffline; - } - - /** - * Return the DbEncrypt used to encrypt and decrypt properties. - *

- * Note that if this is not set then the DbPlatform may already have a - * DbEncrypt set and that will be used. - */ - public DbEncrypt getDbEncrypt() { - return dbEncrypt; - } - - /** - * Set the DbEncrypt used to encrypt and decrypt properties. - *

- * Note that if this is not set then the DbPlatform may already have a - * DbEncrypt set (H2, MySql, Postgres and Oracle platforms have a DbEncrypt) - */ - public void setDbEncrypt(DbEncrypt dbEncrypt) { - this.dbEncrypt = dbEncrypt; - } - - /** - * Return the configuration for DB types (such as UUID and custom mappings). - */ - public PlatformConfig getPlatformConfig() { - return platformConfig; - } - - /** - * Set the configuration for DB platform (such as UUID and custom mappings). - */ - public void setPlatformConfig(PlatformConfig platformConfig) { - this.platformConfig = platformConfig; - } - - /** - * Set the DB type used to store UUID. - */ - public void setDbUuid(PlatformConfig.DbUuid dbUuid) { - this.platformConfig.setDbUuid(dbUuid); - } - - /** - * Returns the UUID version mode. - */ - public UuidVersion getUuidVersion() { - return uuidVersion; - } - - /** - * Sets the UUID version mode. - */ - public void setUuidVersion(UuidVersion uuidVersion) { - this.uuidVersion = uuidVersion; - } - - /** - * Return the UUID state file. - */ - public String getUuidStateFile() { - if (uuidStateFile == null || uuidStateFile.isEmpty()) { - // by default, add servername... - uuidStateFile = name + "-uuid.state"; - // and store it in the user's home directory - String homeDir = System.getProperty("user.home"); - if (homeDir != null && homeDir.isEmpty()) { - uuidStateFile = homeDir + "/.ebean/" + uuidStateFile; - } - } - return uuidStateFile; - } - - /** - * Set the UUID state file. - */ - public void setUuidStateFile(String uuidStateFile) { - this.uuidStateFile = uuidStateFile; - } - - /** - * Return true if LocalTime should be persisted with nanos precision. - */ - public boolean isLocalTimeWithNanos() { - return localTimeWithNanos; - } - - /** - * Set to true if LocalTime should be persisted with nanos precision. - *

- * Otherwise it is persisted using java.sql.Time which is seconds precision. - */ - public void setLocalTimeWithNanos(boolean localTimeWithNanos) { - this.localTimeWithNanos = localTimeWithNanos; - } - - /** - * Return true if Duration should be persisted with nanos precision (SQL DECIMAL). - *

- * Otherwise it is persisted with second precision (SQL INTEGER). - */ - public boolean isDurationWithNanos() { - return durationWithNanos; - } - - /** - * Set to true if Duration should be persisted with nanos precision (SQL DECIMAL). - *

- * Otherwise it is persisted with second precision (SQL INTEGER). - */ - public void setDurationWithNanos(boolean durationWithNanos) { - this.durationWithNanos = durationWithNanos; - } - - /** - * Set to true to run DB migrations on server start. - *

- * This is the same as serverConfig.getMigrationConfig().setRunMigration(). We have added this method here - * as it is often the only thing we need to configure for migrations. - */ - public void setRunMigration(boolean runMigration) { - migrationConfig.setRunMigration(runMigration); - } - - /** - * Set to true to generate the "create all" DDL on startup. - *

- * Typically we want this on when we are running tests locally (and often using H2) - * and we want to create the full DB schema from scratch to run tests. - */ - public void setDdlGenerate(boolean ddlGenerate) { - this.ddlGenerate = ddlGenerate; - } - - /** - * Set to true to run the generated "create all DDL" on startup. - *

- * Typically we want this on when we are running tests locally (and often using H2) - * and we want to create the full DB schema from scratch to run tests. - */ - public void setDdlRun(boolean ddlRun) { - this.ddlRun = ddlRun; - } - - /** - * Set to false if you not want to run the extra-ddl.xml scripts. (default = true) - *

- * Typically we want this on when we are running tests. - */ - public void setDdlExtra(boolean ddlExtra) { - this.ddlExtra = ddlExtra; - } - - - /** - * Return true if the "drop all ddl" should be skipped. - *

- * Typically we want to do this when using H2 (in memory) as our test database and the drop statements - * are not required so skipping the drop table statements etc makes it faster with less noise in the logs. - */ - public boolean isDdlCreateOnly() { - return ddlCreateOnly; - } - - /** - * Set to true if the "drop all ddl" should be skipped. - *

- * Typically we want to do this when using H2 (in memory) as our test database and the drop statements - * are not required so skipping the drop table statements etc makes it faster with less noise in the logs. - */ - public void setDdlCreateOnly(boolean ddlCreateOnly) { - this.ddlCreateOnly = ddlCreateOnly; - } - - /** - * Return SQL script to execute after the "create all" DDL has been run. - *

- * Typically this is a sql script that inserts test seed data when running tests. - * Place a sql script in src/test/resources that inserts test seed data. - */ - public String getDdlSeedSql() { - return ddlSeedSql; - } - - /** - * Set a SQL script to execute after the "create all" DDL has been run. - *

- * Typically this is a sql script that inserts test seed data when running tests. - * Place a sql script in src/test/resources that inserts test seed data. - */ - public void setDdlSeedSql(String ddlSeedSql) { - this.ddlSeedSql = ddlSeedSql; - } - - /** - * Return a SQL script to execute before the "create all" DDL has been run. - */ - public String getDdlInitSql() { - return ddlInitSql; - } - - /** - * Set a SQL script to execute before the "create all" DDL has been run. - */ - public void setDdlInitSql(String ddlInitSql) { - this.ddlInitSql = ddlInitSql; - } - - /** - * Return true if the DDL should be generated. - */ - public boolean isDdlGenerate() { - return ddlGenerate; - } - - /** - * Return true if the DDL should be run. - */ - public boolean isDdlRun() { - return ddlRun; - } - - /** - * Return true, if extra-ddl.xml should be executed. - */ - public boolean isDdlExtra() { - return ddlExtra; - } - - /** - * Return true if the class path search should be disabled. - */ - public boolean isDisableClasspathSearch() { - return disableClasspathSearch; - } - - /** - * 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 Database instance just to use the - * SQL functions such as SqlQuery, SqlUpdate etc. - */ - public void setDisableClasspathSearch(boolean disableClasspathSearch) { - this.disableClasspathSearch = disableClasspathSearch; - } - - /** - * Return the mode to use for Joda LocalTime support 'normal' or 'utc'. - */ - public String getJodaLocalTimeMode() { - return jodaLocalTimeMode; - } - - /** - * Set the mode to use for Joda LocalTime support 'normal' or 'utc'. - */ - public void setJodaLocalTimeMode(String jodaLocalTimeMode) { - this.jodaLocalTimeMode = jodaLocalTimeMode; - } - - /** - * Programmatically add classes (typically entities) that this server should - * use. - *

- * The class can be an Entity, Embedded type, ScalarType, BeanPersistListener, - * BeanFinder or BeanPersistController. - *

- * If no classes are specified then the classes are found automatically via - * searching the class path. - *

- * Alternatively the classes can be added via {@link #setClasses(List)}. - * - * @param cls the entity type (or other type) that should be registered by this - * database. - */ - public void addClass(Class cls) { - classes.add(cls); - } - - /** - * Register all the classes (typically entity classes). - */ - public void addAll(List> classList) { - if (classList != null && !classList.isEmpty()) { - classes.addAll(classList); - } - } - - /** - * Add a package to search for entities via class path search. - *

- * This is only used if classes have not been explicitly specified. - */ - public void addPackage(String packageName) { - packages.add(packageName); - } - - /** - * Return packages to search for entities via class path search. - *

- * This is only used if classes have not been explicitly specified. - */ - public List getPackages() { - return packages; - } - - /** - * Set packages to search for entities via class path search. - *

- * This is only used if classes have not been explicitly specified. - */ - public void setPackages(List packages) { - this.packages = packages; - } - - /** - * Set the list of classes (entities, listeners, scalarTypes etc) that should - * be used for this database. - *

- * If no classes are specified then the classes are found automatically via - * searching the class path. - *

- * Alternatively the classes can contain added via {@link #addClass(Class)}. - */ - public void setClasses(List> classes) { - this.classes = classes; - } - - /** - * Return the classes registered for this database. Typically this includes - * entities and perhaps listeners. - */ - public List> getClasses() { - return classes; - } - - /** - * Return true if L2 bean cache should be skipped once writes have occurred on a transaction. - *

- * This defaults to true and means that for "find by id" and "find by natural key" - * queries that normally hit L2 bean cache automatically will not do so after a write/persist - * on the transaction. - *

- *

{@code
-   *
-   *   // assume Customer has L2 bean caching enabled ...
-   *
-   *   try (Transaction transaction = DB.beginTransaction()) {
-   *
-   *     // this uses L2 bean cache as the transaction
-   *     // ... is considered "query only" at this point
-   *     Customer.find.byId(42);
-   *
-   *     // transaction no longer "query only" once
-   *     // ... a bean has been saved etc
-   *     DB.save(someBean);
-   *
-   *     // will NOT use L2 bean cache as the transaction
-   *     // ... is no longer considered "query only"
-   *     Customer.find.byId(55);
-   *
-   *
-   *
-   *     // explicit control - please use L2 bean cache
-   *
-   *     transaction.setSkipCache(false);
-   *     Customer.find.byId(77); // hit the l2 bean cache
-   *
-   *
-   *     // explicit control - please don't use L2 bean cache
-   *
-   *     transaction.setSkipCache(true);
-   *     Customer.find.byId(99); // skips l2 bean cache
-   *
-   *   }
-   *
-   * }
- * - * @see Transaction#setSkipCache(boolean) - */ - public boolean isSkipCacheAfterWrite() { - return skipCacheAfterWrite; - } - - /** - * Set to false when we still want to hit the cache after a write has occurred on a transaction. - */ - public void setSkipCacheAfterWrite(boolean skipCacheAfterWrite) { - this.skipCacheAfterWrite = skipCacheAfterWrite; - } - - /** - * Returns true if updates in JDBC batch default to include all properties by default. - */ - public boolean isUpdateAllPropertiesInBatch() { - return updateAllPropertiesInBatch; - } - - /** - * Set to false if by default updates in JDBC batch should not include all properties. - *

- * This mode can be explicitly set per transaction. - * - * @see Transaction#setUpdateAllLoadedProperties(boolean) - */ - public void setUpdateAllPropertiesInBatch(boolean updateAllPropertiesInBatch) { - this.updateAllPropertiesInBatch = updateAllPropertiesInBatch; - } - - /** - * Returns the resource directory. - */ - public String getResourceDirectory() { - return resourceDirectory; - } - - /** - * Sets the resource directory. - */ - public void setResourceDirectory(String resourceDirectory) { - this.resourceDirectory = resourceDirectory; - } - - /** - * Add a custom type mapping. - *

- *

{@code
-   *
-   *   // set the default mapping for BigDecimal.class/decimal
-   *   serverConfig.addCustomMapping(DbType.DECIMAL, "decimal(18,6)");
-   *
-   *   // set the default mapping for String.class/varchar but only for Postgres
-   *   serverConfig.addCustomMapping(DbType.VARCHAR, "text", Platform.POSTGRES);
-   *
-   * }
- * - * @param type The DB type this mapping should apply to - * @param columnDefinition The column definition that should be used - * @param platform Optionally specify the platform this mapping should apply to. - */ - public void addCustomMapping(DbType type, String columnDefinition, Platform platform) { - platformConfig.addCustomMapping(type, columnDefinition, platform); - } - - /** - * Add a custom type mapping that applies to all platforms. - *

- *

{@code
-   *
-   *   // set the default mapping for BigDecimal/decimal
-   *   serverConfig.addCustomMapping(DbType.DECIMAL, "decimal(18,6)");
-   *
-   *   // set the default mapping for String/varchar
-   *   serverConfig.addCustomMapping(DbType.VARCHAR, "text");
-   *
-   * }
- * - * @param type The DB type this mapping should apply to - * @param columnDefinition The column definition that should be used - */ - public void addCustomMapping(DbType type, String columnDefinition) { - platformConfig.addCustomMapping(type, columnDefinition); - } - - /** - * Register a BeanQueryAdapter instance. - *

- * Note alternatively you can use {@link #setQueryAdapters(List)} to set all - * the BeanQueryAdapter instances. - */ - public void add(BeanQueryAdapter beanQueryAdapter) { - queryAdapters.add(beanQueryAdapter); - } - - /** - * Return the BeanQueryAdapter instances. - */ - public List getQueryAdapters() { - return queryAdapters; - } - - /** - * Register all the BeanQueryAdapter instances. - *

- * Note alternatively you can use {@link #add(BeanQueryAdapter)} to add - * BeanQueryAdapter instances one at a time. - */ - public void setQueryAdapters(List queryAdapters) { - this.queryAdapters = queryAdapters; - } - - /** - * Return the custom IdGenerator instances. - */ - public List getIdGenerators() { - return idGenerators; - } - - /** - * Set the custom IdGenerator instances. - */ - public void setIdGenerators(List idGenerators) { - this.idGenerators = idGenerators; - } - - /** - * Register a customer IdGenerator instance. - */ - public void add(IdGenerator idGenerator) { - idGenerators.add(idGenerator); - } - - /** - * Register a BeanPersistController instance. - *

- * Note alternatively you can use {@link #setPersistControllers(List)} to set - * all the BeanPersistController instances. - */ - public void add(BeanPersistController beanPersistController) { - persistControllers.add(beanPersistController); - } - - /** - * Register a BeanPostLoad instance. - *

- * Note alternatively you can use {@link #setPostLoaders(List)} to set - * all the BeanPostLoad instances. - */ - public void add(BeanPostLoad postLoad) { - postLoaders.add(postLoad); - } - - /** - * Register a BeanPostConstructListener instance. - *

- * Note alternatively you can use {@link #setPostConstructListeners(List)} to set - * all the BeanPostConstructListener instances. - */ - public void add(BeanPostConstructListener listener) { - postConstructListeners.add(listener); - } - - /** - * Return the list of BeanFindController instances. - */ - public List getFindControllers() { - return findControllers; - } - - /** - * Set the list of BeanFindController instances. - */ - public void setFindControllers(List findControllers) { - this.findControllers = findControllers; - } - - /** - * Return the list of BeanPostLoader instances. - */ - public List getPostLoaders() { - return postLoaders; - } - - /** - * Set the list of BeanPostLoader instances. - */ - public void setPostLoaders(List postLoaders) { - this.postLoaders = postLoaders; - } - - /** - * Return the list of BeanPostLoader instances. - */ - public List getPostConstructListeners() { - return postConstructListeners; - } - - /** - * Set the list of BeanPostLoader instances. - */ - public void setPostConstructListeners(List listeners) { - this.postConstructListeners = listeners; - } - - /** - * Return the BeanPersistController instances. - */ - public List getPersistControllers() { - return persistControllers; - } - - /** - * Register all the BeanPersistController instances. - *

- * Note alternatively you can use {@link #add(BeanPersistController)} to add - * BeanPersistController instances one at a time. - */ - public void setPersistControllers(List persistControllers) { - this.persistControllers = persistControllers; - } - - /** - * Register a BeanPersistListener instance. - *

- * Note alternatively you can use {@link #setPersistListeners(List)} to set - * all the BeanPersistListener instances. - */ - public void add(BeanPersistListener beanPersistListener) { - persistListeners.add(beanPersistListener); - } - - /** - * Return the BeanPersistListener instances. - */ - public List getPersistListeners() { - return persistListeners; - } - - /** - * Add a BulkTableEventListener - */ - public void add(BulkTableEventListener bulkTableEventListener) { - bulkTableEventListeners.add(bulkTableEventListener); - } - - /** - * Return the list of BulkTableEventListener instances. - */ - public List getBulkTableEventListeners() { - return bulkTableEventListeners; - } - - /** - * Add a ServerConfigStartup. - */ - public void addServerConfigStartup(ServerConfigStartup configStartupListener) { - configStartupListeners.add(configStartupListener); - } - - /** - * Return the list of ServerConfigStartup instances. - */ - public List getServerConfigStartupListeners() { - return configStartupListeners; - } - - /** - * Register all the BeanPersistListener instances. - *

- * Note alternatively you can use {@link #add(BeanPersistListener)} to add - * BeanPersistListener instances one at a time. - */ - public void setPersistListeners(List persistListeners) { - this.persistListeners = persistListeners; - } - - /** - * Return the default PersistenceContextScope to be used if one is not explicitly set on a query. - *

- * The PersistenceContextScope can specified on each query via {@link io.ebean - * .Query#setPersistenceContextScope(io.ebean.PersistenceContextScope)}. If it - * is not set on the query this default scope is used. - * - * @see Query#setPersistenceContextScope(PersistenceContextScope) - */ - public PersistenceContextScope getPersistenceContextScope() { - // if somehow null return TRANSACTION scope - return persistenceContextScope == null ? PersistenceContextScope.TRANSACTION : persistenceContextScope; - } - - /** - * Set the PersistenceContext scope to be used if one is not explicitly set on a query. - *

- * This defaults to {@link PersistenceContextScope#TRANSACTION}. - *

- * The PersistenceContextScope can specified on each query via {@link io.ebean - * .Query#setPersistenceContextScope(io.ebean.PersistenceContextScope)}. If it - * is not set on the query this scope is used. - * - * @see Query#setPersistenceContextScope(PersistenceContextScope) - */ - public void setPersistenceContextScope(PersistenceContextScope persistenceContextScope) { - this.persistenceContextScope = persistenceContextScope; - } - - /** - * Return the ClassLoadConfig which is used to detect Joda, Java8 types etc and also - * create new instances of plugins given a className. - */ - public ClassLoadConfig getClassLoadConfig() { - return classLoadConfig; - } - - /** - * Set the ClassLoadConfig which is used to detect Joda, Java8 types etc and also - * create new instances of plugins given a className. - */ - public void setClassLoadConfig(ClassLoadConfig classLoadConfig) { - this.classLoadConfig = classLoadConfig; - } - - /** - * Return the service loader using the classLoader defined in ClassLoadConfig. - */ - public ServiceLoader serviceLoad(Class spiService) { - - return ServiceLoader.load(spiService, classLoadConfig.getClassLoader()); - } - - /** - * Return the first service using the service loader (or null). - */ - public T service(Class spiService) { - ServiceLoader load = serviceLoad(spiService); - Iterator serviceInstances = load.iterator(); - return serviceInstances.hasNext() ? serviceInstances.next() : null; - } - - /** - * Load settings from ebean.properties. - */ - public void loadFromProperties() { - this.properties = Config.asProperties(); - configureFromProperties(); - } - - /** - * Load the settings from the given properties - */ - public void loadFromProperties(Properties properties) { - // keep the properties used for configuration so that these are available for plugins - this.properties = Config.asConfiguration().eval(properties); - configureFromProperties(); - } - - /** - * Load the settings from the given properties - */ - private void configureFromProperties() { - List autoConfigures = autoConfiguration(); - loadSettings(new PropertiesWrapper("ebean", name, properties, classLoadConfig)); - for (AutoConfigure autoConfigure : autoConfigures) { - autoConfigure.postConfigure(this); - } - } - - /** - * Use a 'plugin' to provide automatic configuration. Intended for automatic testing - * configuration with Docker containers via ebean-test-config. - */ - private List autoConfiguration() { - List list = new ArrayList<>(); - for (AutoConfigure autoConfigure : serviceLoad(AutoConfigure.class)) { - autoConfigure.preConfigure(this); - list.add(autoConfigure); - } - return list; - } - - /** - * Return the properties that we used for configuration and were set via a call to loadFromProperties(). - */ - public Properties getProperties() { - return properties; - } - - /** - * loads the data source settings to preserve existing behaviour. IMHO, if someone has set the datasource config already, - * they don't want the settings to be reloaded and reset. This allows a descending class to override this behaviour and prevent it - * from happening. - * - * @param p - The defined property source passed to load settings - */ - protected void loadDataSourceSettings(PropertiesWrapper p) { - dataSourceConfig.loadSettings(p.properties, name); - readOnlyDataSourceConfig.loadSettings(p.properties, name + "-ro"); - } - - /** - * This is broken out to allow overridden behaviour. - */ - protected void loadDocStoreSettings(PropertiesWrapper p) { - docStoreConfig.loadSettings(p); - } - - /** - * This is broken out to allow overridden behaviour. - */ - protected void loadAutoTuneSettings(PropertiesWrapper p) { - autoTuneConfig.loadSettings(p); - } - - /** - * Load the configuration settings from the properties file. - */ - protected void loadSettings(PropertiesWrapper p) { - - dbSchema = p.get("dbSchema", dbSchema); - if (dbSchema != null) { - migrationConfig.setDefaultDbSchema(dbSchema); - } - profilingConfig.loadSettings(p, name); - migrationConfig.loadSettings(p, name); - platformConfig.loadSettings(p); - if (platformConfig.isAllQuotedIdentifiers()) { - adjustNamingConventionForAllQuoted(); - } - namingConvention = createNamingConvention(p, namingConvention); - if (namingConvention != null) { - namingConvention.loadFromProperties(p); - } - if (autoTuneConfig == null) { - autoTuneConfig = new AutoTuneConfig(); - } - loadAutoTuneSettings(p); - - if (dataSourceConfig == null) { - dataSourceConfig = new DataSourceConfig(); - } - loadDataSourceSettings(p); - - if (docStoreConfig == null) { - docStoreConfig = new DocStoreConfig(); - } - loadDocStoreSettings(p); - - loadModuleInfo = p.getBoolean("loadModuleInfo", loadModuleInfo); - maxCallStack = p.getInt("maxCallStack", maxCallStack); - dumpMetricsOnShutdown = p.getBoolean("dumpMetricsOnShutdown", dumpMetricsOnShutdown); - dumpMetricsOptions = p.get("dumpMetricsOptions", dumpMetricsOptions); - queryPlanTTLSeconds = p.getInt("queryPlanTTLSeconds", queryPlanTTLSeconds); - slowQueryMillis = p.getLong("slowQueryMillis", slowQueryMillis); - collectQueryPlans = p.getBoolean("collectQueryPlans", collectQueryPlans); - collectQueryPlanThresholdMicros = p.getLong("collectQueryPlanThresholdMicros", collectQueryPlanThresholdMicros); - docStoreOnly = p.getBoolean("docStoreOnly", docStoreOnly); - disableL2Cache = p.getBoolean("disableL2Cache", disableL2Cache); - localOnlyL2Cache = p.getBoolean("localOnlyL2Cache", localOnlyL2Cache); - enabledL2Regions = p.get("enabledL2Regions", enabledL2Regions); - notifyL2CacheInForeground = p.getBoolean("notifyL2CacheInForeground", notifyL2CacheInForeground); - useJtaTransactionManager = p.getBoolean("useJtaTransactionManager", useJtaTransactionManager); - useJavaxValidationNotNull = p.getBoolean("useJavaxValidationNotNull", useJavaxValidationNotNull); - autoReadOnlyDataSource = p.getBoolean("autoReadOnlyDataSource", autoReadOnlyDataSource); - idGeneratorAutomatic = p.getBoolean("idGeneratorAutomatic", idGeneratorAutomatic); - - backgroundExecutorSchedulePoolSize = p.getInt("backgroundExecutorSchedulePoolSize", backgroundExecutorSchedulePoolSize); - backgroundExecutorShutdownSecs = p.getInt("backgroundExecutorShutdownSecs", backgroundExecutorShutdownSecs); - disableClasspathSearch = p.getBoolean("disableClasspathSearch", disableClasspathSearch); - currentUserProvider = p.createInstance(CurrentUserProvider.class, "currentUserProvider", currentUserProvider); - databasePlatform = p.createInstance(DatabasePlatform.class, "databasePlatform", databasePlatform); - encryptKeyManager = p.createInstance(EncryptKeyManager.class, "encryptKeyManager", encryptKeyManager); - encryptDeployManager = p.createInstance(EncryptDeployManager.class, "encryptDeployManager", encryptDeployManager); - encryptor = p.createInstance(Encryptor.class, "encryptor", encryptor); - dbEncrypt = p.createInstance(DbEncrypt.class, "dbEncrypt", dbEncrypt); - dbOffline = p.getBoolean("dbOffline", dbOffline); - serverCachePlugin = p.createInstance(ServerCachePlugin.class, "serverCachePlugin", serverCachePlugin); - - String packagesProp = p.get("search.packages", p.get("packages", null)); - packages = getSearchList(packagesProp, packages); - - skipCacheAfterWrite = p.getBoolean("skipCacheAfterWrite", skipCacheAfterWrite); - updateAllPropertiesInBatch = p.getBoolean("updateAllPropertiesInBatch", updateAllPropertiesInBatch); - - if (p.get("batch.mode") != null || p.get("persistBatching") != null) { - throw new IllegalArgumentException("Property 'batch.mode' or 'persistBatching' is being set but no longer used. Please change to use 'persistBatchMode'"); - } - - persistBatch = p.getEnum(PersistBatch.class, "persistBatch", persistBatch); - persistBatchOnCascade = p.getEnum(PersistBatch.class, "persistBatchOnCascade", persistBatchOnCascade); - - int batchSize = p.getInt("batch.size", persistBatchSize); - persistBatchSize = p.getInt("persistBatchSize", batchSize); - - persistenceContextScope = PersistenceContextScope.valueOf(p.get("persistenceContextScope", "TRANSACTION")); - - changeLogAsync = p.getBoolean("changeLogAsync", changeLogAsync); - changeLogIncludeInserts = p.getBoolean("changeLogIncludeInserts", changeLogIncludeInserts); - expressionEqualsWithNullAsNoop = p.getBoolean("expressionEqualsWithNullAsNoop", expressionEqualsWithNullAsNoop); - expressionNativeIlike = p.getBoolean("expressionNativeIlike", expressionNativeIlike); - - dataTimeZone = p.get("dataTimeZone", dataTimeZone); - asOfViewSuffix = p.get("asOfViewSuffix", asOfViewSuffix); - asOfSysPeriod = p.get("asOfSysPeriod", asOfSysPeriod); - historyTableSuffix = p.get("historyTableSuffix", historyTableSuffix); - dataSourceJndiName = p.get("dataSourceJndiName", dataSourceJndiName); - jdbcFetchSizeFindEach = p.getInt("jdbcFetchSizeFindEach", jdbcFetchSizeFindEach); - jdbcFetchSizeFindList = p.getInt("jdbcFetchSizeFindList", jdbcFetchSizeFindList); - databasePlatformName = p.get("databasePlatformName", databasePlatformName); - defaultOrderById = p.getBoolean("defaultOrderById", defaultOrderById); - - uuidVersion = p.getEnum(UuidVersion.class, "uuidVersion", uuidVersion); - uuidStateFile = p.get("uuidStateFile", uuidStateFile); - - localTimeWithNanos = p.getBoolean("localTimeWithNanos", localTimeWithNanos); - jodaLocalTimeMode = p.get("jodaLocalTimeMode", jodaLocalTimeMode); - - defaultEnumType = p.getEnum(EnumType.class, "defaultEnumType", defaultEnumType); - disableLazyLoading = p.getBoolean("disableLazyLoading", disableLazyLoading); - lazyLoadBatchSize = p.getInt("lazyLoadBatchSize", lazyLoadBatchSize); - queryBatchSize = p.getInt("queryBatchSize", queryBatchSize); - - jsonInclude = p.getEnum(JsonConfig.Include.class, "jsonInclude", jsonInclude); - jsonDateTime = p.getEnum(JsonConfig.DateTime.class, "jsonDateTime", jsonDateTime); - jsonDate = p.getEnum(JsonConfig.Date.class, "jsonDate", jsonDate); - - ddlGenerate = p.getBoolean("ddl.generate", ddlGenerate); - ddlRun = p.getBoolean("ddl.run", ddlRun); - ddlExtra = p.getBoolean("ddl.extra", ddlExtra); - ddlCreateOnly = p.getBoolean("ddl.createOnly", ddlCreateOnly); - ddlInitSql = p.get("ddl.initSql", ddlInitSql); - ddlSeedSql = p.get("ddl.seedSql", ddlSeedSql); - - // read tenant-configuration from config: - // tenant.mode = NONE | DB | SCHEMA | CATALOG | PARTITION - String mode = p.get("tenant.mode"); - if (mode != null) { - for (TenantMode value : TenantMode.values()) { - if (value.name().equalsIgnoreCase(mode)) { - tenantMode = value; - break; - } - } - } - - currentTenantProvider = p.createInstance(CurrentTenantProvider.class, "tenant.currentTenantProvider", currentTenantProvider); - tenantCatalogProvider = p.createInstance(TenantCatalogProvider.class, "tenant.catalogProvider", tenantCatalogProvider); - tenantSchemaProvider = p.createInstance(TenantSchemaProvider.class, "tenant.schemaProvider", tenantSchemaProvider); - tenantPartitionColumn = p.get("tenant.partitionColumn", tenantPartitionColumn); - classes = getClasses(p); - - String mappingsProp = p.get("mappingLocations", null); - mappingLocations = getSearchList(mappingsProp, mappingLocations); - } - - private NamingConvention createNamingConvention(PropertiesWrapper properties, NamingConvention namingConvention) { - NamingConvention nc = properties.createInstance(NamingConvention.class, "namingConvention", null); - return (nc != null) ? nc : namingConvention; - } - - /** - * Build the list of classes from the comma delimited string. - * - * @param properties the properties - * @return the classes - */ - private List> getClasses(PropertiesWrapper properties) { - String classNames = properties.get("classes", null); - if (classNames == null) { - return classes; - } - - List> classList = new ArrayList<>(); - String[] split = StringHelper.splitNames(classNames); - for (String cn : split) { - if (!"class".equalsIgnoreCase(cn)) { - try { - classList.add(Class.forName(cn)); - } catch (ClassNotFoundException e) { - String msg = "Error registering class [" + cn + "] from [" + classNames + "]"; - throw new RuntimeException(msg, e); - } - } - } - return classList; - } - - private List getSearchList(String searchNames, List defaultValue) { - if (searchNames != null) { - String[] entries = StringHelper.splitNames(searchNames); - List hitList = new ArrayList<>(entries.length); - Collections.addAll(hitList, entries); - return hitList; - } else { - return defaultValue; - } - } - - /** - * Return the PersistBatch mode to use for 'batchOnCascade' taking into account if the database - * platform supports getGeneratedKeys in batch mode. - */ - public PersistBatch appliedPersistBatchOnCascade() { - if (persistBatchOnCascade == PersistBatch.INHERIT) { - // use the platform default (ALL except SQL Server which has NONE) - return databasePlatform.getPersistBatchOnCascade(); - } - return persistBatchOnCascade; - } - - /** - * Return the Jackson ObjectMapper. - *

- * Note that this is not strongly typed as Jackson ObjectMapper is an optional dependency. - */ - public Object getObjectMapper() { - return objectMapper; - } - - /** - * Set the Jackson ObjectMapper. - *

- * Note that this is not strongly typed as Jackson ObjectMapper is an optional dependency. - */ - public void setObjectMapper(Object objectMapper) { - this.objectMapper = objectMapper; - } - - /** - * Return true if eq("someProperty", null) should to generate "1=1" rather than "is null" sql expression. - */ - public boolean isExpressionEqualsWithNullAsNoop() { - return expressionEqualsWithNullAsNoop; - } - - /** - * Set to true if you want eq("someProperty", null) to generate "1=1" rather than "is null" sql expression. - *

- * Setting this to true has the effect that eq(propertyName, value), ieq(propertyName, value) and - * ne(propertyName, value) have no effect when the value is null. The expression factory adds a NoopExpression - * which will add "1=1" into the SQL rather than "is null". - */ - public void setExpressionEqualsWithNullAsNoop(boolean expressionEqualsWithNullAsNoop) { - this.expressionEqualsWithNullAsNoop = expressionEqualsWithNullAsNoop; - } - - /** - * Return true if native ILIKE expression should be used if supported by the database platform (e.g. Postgres). - */ - public boolean isExpressionNativeIlike() { - return expressionNativeIlike; - } - - /** - * Set to true to use native ILIKE expression if supported by the database platform (e.g. Postgres). - */ - public void setExpressionNativeIlike(boolean expressionNativeIlike) { - this.expressionNativeIlike = expressionNativeIlike; - } - - /** - * Return the enabled L2 cache regions. - */ - public String getEnabledL2Regions() { - return enabledL2Regions; - } - - /** - * Set the enabled L2 cache regions (comma delimited). - */ - public void setEnabledL2Regions(String enabledL2Regions) { - this.enabledL2Regions = enabledL2Regions; - } - - /** - * Return true if L2 cache is disabled. - */ - public boolean isDisableL2Cache() { - return disableL2Cache; - } - - /** - * Set to true to disable L2 caching. Typically useful in performance testing. - */ - public void setDisableL2Cache(boolean disableL2Cache) { - this.disableL2Cache = disableL2Cache; - } - - /** - * Return true to use local only L2 cache. Effectively ignore l2 cache plugin like ebean-redis etc. - */ - public boolean isLocalOnlyL2Cache() { - return localOnlyL2Cache; - } - - /** - * Force the use of local only L2 cache. Effectively ignore l2 cache plugin like ebean-redis etc. - */ - public void setLocalOnlyL2Cache(boolean localOnlyL2Cache) { - this.localOnlyL2Cache = localOnlyL2Cache; - } - - /** - * Returns if we use javax.validation.constraints.NotNull - */ - public boolean isUseJavaxValidationNotNull() { - return useJavaxValidationNotNull; - } - - /** - * Controls if Ebean should ignore &x64;javax.validation.contstraints.NotNull - * with respect to generating a NOT NULL column. - *

- * Normally when Ebean sees javax NotNull annotation it means that column is defined as NOT NULL. - * Set this to false and the javax NotNull annotation is effectively ignored (and - * we instead use Ebean's own NotNull annotation or JPA Column(nullable=false) annotation. - */ - public void setUseJavaxValidationNotNull(boolean useJavaxValidationNotNull) { - this.useJavaxValidationNotNull = useJavaxValidationNotNull; - } - - /** - * Return true if L2 cache notification should run in the foreground. - */ - public boolean isNotifyL2CacheInForeground() { - return notifyL2CacheInForeground; - } - - /** - * Set this to true to run L2 cache notification in the foreground. - *

- * In general we don't want to do that as when we use a distributed cache (like Ignite, Hazelcast etc) - * we are making network calls and we prefer to do this in background and not impact the response time - * of the executing transaction. - */ - public void setNotifyL2CacheInForeground(boolean notifyL2CacheInForeground) { - this.notifyL2CacheInForeground = notifyL2CacheInForeground; - } - - /** - * Return the query plan time to live. - */ - public int getQueryPlanTTLSeconds() { - return queryPlanTTLSeconds; - } - - /** - * Set the query plan time to live. - */ - public void setQueryPlanTTLSeconds(int queryPlanTTLSeconds) { - this.queryPlanTTLSeconds = queryPlanTTLSeconds; - } - - /** - * Run the DB migration against the DataSource. - */ - public DataSource runDbMigration(DataSource dataSource) { - if (migrationConfig.isRunMigration()) { - MigrationRunner runner = migrationConfig.createRunner(getClassLoadConfig().getClassLoader(), properties); - runner.run(dataSource); - } - return dataSource; - } - - /** - * Create a new PlatformConfig based of the one held but with overridden properties by reading - * properties with the given path and prefix. - *

- * Typically used in Db Migration generation for many platform targets that might have different - * configuration for IdType, UUID, quoted identifiers etc. - * - * @param propertiesPath The properties path used for loading and setting properties - * @param platformPrefix The prefix used for loading and setting properties - * @return A copy of the PlatformConfig with overridden properties - */ - public PlatformConfig newPlatformConfig(String propertiesPath, String platformPrefix) { - if (properties == null) { - properties = new Properties(); - } - PropertiesWrapper p = new PropertiesWrapper(propertiesPath, platformPrefix, properties, classLoadConfig); - PlatformConfig config = new PlatformConfig(platformConfig); - config.loadSettings(p); - return config; - } - - /** - * Add a mapping location to search for xml mapping via class path search. - */ - public void addMappingLocation(String mappingLocation) { - if (mappingLocations == null) { - mappingLocations = new ArrayList<>(); - } - mappingLocations.add(mappingLocation); - } - - /** - * Return mapping locations to search for xml mapping via class path search. - */ - public List getMappingLocations() { - return mappingLocations; - } - - /** - * Set mapping locations to search for xml mapping via class path search. - *

- * This is only used if classes have not been explicitly specified. - */ - public void setMappingLocations(List mappingLocations) { - this.mappingLocations = mappingLocations; - } - - /** - * When false we need explicit @GeneratedValue mapping to assign - * Identity or Sequence generated values. When true Id properties are automatically - * assigned Identity or Sequence without the GeneratedValue mapping. - */ - public boolean isIdGeneratorAutomatic() { - return idGeneratorAutomatic; - } - - /** - * Set to false such that Id properties require explicit @GeneratedValue - * mapping before they are assigned Identity or Sequence generation based on platform. - */ - public void setIdGeneratorAutomatic(boolean idGeneratorAutomatic) { - this.idGeneratorAutomatic = idGeneratorAutomatic; - } - - /** - * Return true if query plan capture is enabled. - */ - public boolean isCollectQueryPlans() { - return collectQueryPlans; - } - - /** - * Set to true to enable query plan capture. - */ - public void setCollectQueryPlans(boolean collectQueryPlans) { - this.collectQueryPlans = collectQueryPlans; - } - - /** - * Return the query plan collection threshold in microseconds. - */ - public long getCollectQueryPlanThresholdMicros() { - return collectQueryPlanThresholdMicros; - } - - /** - * Set the query plan collection threshold in microseconds. - */ - public void setCollectQueryPlanThresholdMicros(long collectQueryPlanThresholdMicros) { - this.collectQueryPlanThresholdMicros = collectQueryPlanThresholdMicros; - } - - /** - * Return true if metrics should be dumped when the server is shutdown. - */ - public boolean isDumpMetricsOnShutdown() { - return dumpMetricsOnShutdown; - } - - /** - * Set to true if metrics should be dumped when the server is shutdown. - */ - public void setDumpMetricsOnShutdown(boolean dumpMetricsOnShutdown) { - this.dumpMetricsOnShutdown = dumpMetricsOnShutdown; - } - - /** - * Return the options for dumping metrics. - */ - public String getDumpMetricsOptions() { - return dumpMetricsOptions; - } - - /** - * Include 'sql' or 'hash' in options such that they are included in the output. - * - * @param dumpMetricsOptions Example "sql,hash", "sql" - */ - public void setDumpMetricsOptions(String dumpMetricsOptions) { - this.dumpMetricsOptions = dumpMetricsOptions; - } - - /** - * Return true if entity classes should be loaded and registered via ModuleInfoLoader. - *

- * When false we either register entity classes via application code or use classpath - * scanning to find and register entity classes. - */ - public boolean isAutoLoadModuleInfo() { - return loadModuleInfo && classes.isEmpty(); - } - - /** - * Set false to turn off automatic registration of entity beans. - *

- * When using query beans that also generates a module info class that - * can register the entity bean classes (to avoid classpath scanning). - * This is on by default and setting this to false turns it off. - */ - public void setLoadModuleInfo(boolean loadModuleInfo) { - this.loadModuleInfo = loadModuleInfo; - } - - public enum UuidVersion { - VERSION4, - VERSION1, - VERSION1RND - } } diff --git a/src/main/java/io/ebean/config/ServerConfigProvider.java b/src/main/java/io/ebean/config/ServerConfigProvider.java index 37f05b551..f992b004d 100644 --- a/src/main/java/io/ebean/config/ServerConfigProvider.java +++ b/src/main/java/io/ebean/config/ServerConfigProvider.java @@ -1,11 +1,12 @@ package io.ebean.config; /** + * Deprecated - migrate to DatabaseConfigProvider. + *

* Provides a ServiceLoader based mechanism to configure a ServerConfig. *

* Provide an implementation and register it via the standard Java ServiceLoader mechanism * via a file at META-INF/services/io.ebean.config.ServerConfigProvider. - *

*

* If you are using a DI container like Spring or Guice you are unlikely to use this but instead use a * spring specific configuration. When we are not using a DI container we may use this mechanism to @@ -27,6 +28,7 @@ package io.ebean.config; * * } */ +@Deprecated public interface ServerConfigProvider { /** diff --git a/src/main/java/io/ebean/dbmigration/DbMigration.java b/src/main/java/io/ebean/dbmigration/DbMigration.java index 7bab8f7db..f27024e0a 100644 --- a/src/main/java/io/ebean/dbmigration/DbMigration.java +++ b/src/main/java/io/ebean/dbmigration/DbMigration.java @@ -2,7 +2,7 @@ package io.ebean.dbmigration; import io.ebean.Database; import io.ebean.annotation.Platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.config.dbplatform.DatabasePlatform; import java.io.IOException; @@ -88,7 +88,7 @@ public interface DbMigration { /** * Set the serverConfig to use. Typically this is not called explicitly. */ - void setServerConfig(ServerConfig config); + void setServerConfig(DatabaseConfig config); /** * Set the specific platform to generate DDL for. diff --git a/src/main/java/io/ebean/event/ServerConfigStartup.java b/src/main/java/io/ebean/event/ServerConfigStartup.java index a5563869e..f29b8a22a 100644 --- a/src/main/java/io/ebean/event/ServerConfigStartup.java +++ b/src/main/java/io/ebean/event/ServerConfigStartup.java @@ -1,6 +1,6 @@ package io.ebean.event; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; /** * Used to configure the server on startup. @@ -11,8 +11,8 @@ import io.ebean.config.ServerConfig; public interface ServerConfigStartup { /** - * On starting configure the ServerConfig. + * On starting configure the DatabaseConfig. */ - void onStart(ServerConfig serverConfig); + void onStart(DatabaseConfig config); } diff --git a/src/main/java/io/ebean/plugin/SpiServer.java b/src/main/java/io/ebean/plugin/SpiServer.java index 2b55077fb..a711291b5 100644 --- a/src/main/java/io/ebean/plugin/SpiServer.java +++ b/src/main/java/io/ebean/plugin/SpiServer.java @@ -3,7 +3,7 @@ package io.ebean.plugin; import io.ebean.EbeanServer; import io.ebean.bean.BeanLoader; import io.ebean.bean.EntityBeanIntercept; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.config.dbplatform.DatabasePlatform; import javax.sql.DataSource; @@ -17,7 +17,7 @@ public interface SpiServer extends EbeanServer, BeanLoader { /** * Return the serverConfig. */ - ServerConfig getServerConfig(); + DatabaseConfig getServerConfig(); /** * Return the DatabasePlatform for this database. diff --git a/src/main/java/io/ebean/service/SpiContainer.java b/src/main/java/io/ebean/service/SpiContainer.java index bf4aa4aca..547f4648e 100644 --- a/src/main/java/io/ebean/service/SpiContainer.java +++ b/src/main/java/io/ebean/service/SpiContainer.java @@ -1,7 +1,7 @@ package io.ebean.service; -import io.ebean.EbeanServer; -import io.ebean.config.ServerConfig; +import io.ebean.Database; +import io.ebean.config.DatabaseConfig; /** * Creates the Database implementations. This is used internally by the EbeanServerFactory and is not currently @@ -14,7 +14,7 @@ public interface SpiContainer { * * @param configuration The configuration information for this database. */ - EbeanServer createServer(ServerConfig configuration); + Database createServer(DatabaseConfig configuration); /** * Create an EbeanServer just using the name. @@ -23,7 +23,7 @@ public interface SpiContainer { * avaje.properties file. *

*/ - EbeanServer createServer(String name); + Database createServer(String name); /** * Shutdown any Ebean wide resources such as clustering. diff --git a/src/main/java/io/ebeaninternal/api/ExtraTypeFactory.java b/src/main/java/io/ebeaninternal/api/ExtraTypeFactory.java index feafd43e2..99e5caf39 100644 --- a/src/main/java/io/ebeaninternal/api/ExtraTypeFactory.java +++ b/src/main/java/io/ebeaninternal/api/ExtraTypeFactory.java @@ -1,6 +1,6 @@ package io.ebeaninternal.api; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.server.type.ScalarType; import java.util.List; @@ -13,5 +13,5 @@ public interface ExtraTypeFactory { /** * Provide extra types to Ebean. */ - List> createTypes(ServerConfig config, Object objectMapper); + List> createTypes(DatabaseConfig config, Object objectMapper); } diff --git a/src/main/java/io/ebeaninternal/api/SpiEbeanServer.java b/src/main/java/io/ebeaninternal/api/SpiEbeanServer.java index 4ac98d61d..caa195b10 100644 --- a/src/main/java/io/ebeaninternal/api/SpiEbeanServer.java +++ b/src/main/java/io/ebeaninternal/api/SpiEbeanServer.java @@ -10,9 +10,8 @@ import io.ebean.RowMapper; import io.ebean.Transaction; import io.ebean.TxScope; import io.ebean.bean.BeanCollectionLoader; -import io.ebean.bean.BeanLoader; import io.ebean.bean.CallOrigin; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.config.dbplatform.DatabasePlatform; import io.ebean.event.readaudit.ReadAuditLogger; import io.ebean.event.readaudit.ReadAuditPrepare; @@ -66,7 +65,7 @@ public interface SpiEbeanServer extends ExtendedServer, EbeanServer, BeanCollect /** * Return the server configuration. */ - ServerConfig getServerConfig(); + DatabaseConfig getServerConfig(); /** * Return the DatabasePlatform for this server. diff --git a/src/main/java/io/ebeaninternal/dbmigration/DdlGenerator.java b/src/main/java/io/ebeaninternal/dbmigration/DdlGenerator.java index 132e357cb..1dbc53ad2 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/DdlGenerator.java +++ b/src/main/java/io/ebeaninternal/dbmigration/DdlGenerator.java @@ -1,8 +1,8 @@ package io.ebeaninternal.dbmigration; import io.ebean.annotation.Platform; +import io.ebean.config.DatabaseConfig; import io.ebean.config.DbMigrationConfig; -import io.ebean.config.ServerConfig; import io.ebean.config.dbplatform.DatabasePlatform; import io.ebean.migration.ddl.DdlRunner; import io.ebean.migration.runner.ScriptTransform; @@ -56,25 +56,25 @@ public class DdlGenerator { private String createAllContent; private File baseDir; - public DdlGenerator(SpiEbeanServer server, ServerConfig serverConfig) { + public DdlGenerator(SpiEbeanServer server, DatabaseConfig config) { this.server = server; - this.jaxbPresent = serverConfig.getClassLoadConfig().isJavaxJAXBPresent(); - this.generateDdl = serverConfig.isDdlGenerate(); - this.extraDdl = serverConfig.isDdlExtra(); - this.createOnly = serverConfig.isDdlCreateOnly(); - this.dbSchema = serverConfig.getDbSchema(); + this.jaxbPresent = config.getClassLoadConfig().isJavaxJAXBPresent(); + this.generateDdl = config.isDdlGenerate(); + this.extraDdl = config.isDdlExtra(); + this.createOnly = config.isDdlCreateOnly(); + this.dbSchema = config.getDbSchema(); final DatabasePlatform databasePlatform = server.getDatabasePlatform(); this.platform = databasePlatform.getPlatform(); this.platformName = platform.base().name(); - if (!serverConfig.getTenantMode().isDdlEnabled() && serverConfig.isDdlRun()) { - log.warn("DDL can't be run on startup with TenantMode " + serverConfig.getTenantMode()); + if (!config.getTenantMode().isDdlEnabled() && config.isDdlRun()) { + log.warn("DDL can't be run on startup with TenantMode " + config.getTenantMode()); this.runDdl = false; this.ddlAutoCommit = false; } else { - this.runDdl = serverConfig.isDdlRun(); + this.runDdl = config.isDdlRun(); this.ddlAutoCommit = databasePlatform.isDdlAutoCommit(); } - this.scriptTransform = createScriptTransform(serverConfig.getMigrationConfig()); + this.scriptTransform = createScriptTransform(config.getMigrationConfig()); this.baseDir = initBaseDir(); } diff --git a/src/main/java/io/ebeaninternal/dbmigration/DefaultDbMigration.java b/src/main/java/io/ebeaninternal/dbmigration/DefaultDbMigration.java index 8130293ef..797eac9ec 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/DefaultDbMigration.java +++ b/src/main/java/io/ebeaninternal/dbmigration/DefaultDbMigration.java @@ -4,10 +4,10 @@ import io.ebean.DB; import io.ebean.Database; import io.ebean.EbeanServer; import io.ebean.annotation.Platform; +import io.ebean.config.DatabaseConfig; import io.ebean.config.DbConstraintNaming; import io.ebean.config.DbMigrationConfig; import io.ebean.config.PlatformConfig; -import io.ebean.config.ServerConfig; import io.ebean.config.dbplatform.DatabasePlatform; import io.ebean.config.dbplatform.clickhouse.ClickHousePlatform; import io.ebean.config.dbplatform.cockroach.CockroachPlatform; @@ -104,7 +104,7 @@ public class DefaultDbMigration implements DbMigration { protected List platforms = new ArrayList<>(); - protected ServerConfig serverConfig; + protected DatabaseConfig serverConfig; protected DbConstraintNaming constraintNaming; @@ -164,7 +164,7 @@ public class DefaultDbMigration implements DbMigration { * Set the serverConfig to use. Typically this is not called explicitly. */ @Override - public void setServerConfig(ServerConfig config) { + public void setServerConfig(DatabaseConfig config) { if (this.serverConfig == null) { this.serverConfig = config; } diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/BaseDdlHandler.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/BaseDdlHandler.java index 29ee263bc..870d90472 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/BaseDdlHandler.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/BaseDdlHandler.java @@ -1,6 +1,6 @@ package io.ebeaninternal.dbmigration.ddlgeneration; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.dbmigration.ddlgeneration.platform.BaseTableDdl; import io.ebeaninternal.dbmigration.ddlgeneration.platform.PlatformDdl; import io.ebeaninternal.dbmigration.migration.AddColumn; @@ -27,11 +27,11 @@ public class BaseDdlHandler implements DdlHandler { protected final TableDdl tableDdl; - public BaseDdlHandler(ServerConfig serverConfig, PlatformDdl platformDdl) { - this(serverConfig, platformDdl, new BaseTableDdl(serverConfig, platformDdl)); + public BaseDdlHandler(DatabaseConfig config, PlatformDdl platformDdl) { + this(config, platformDdl, new BaseTableDdl(config, platformDdl)); } - - protected BaseDdlHandler(ServerConfig serverConfig, PlatformDdl platformDdl, TableDdl tableDdl) { + + protected BaseDdlHandler(DatabaseConfig config, PlatformDdl platformDdl, TableDdl tableDdl) { this.tableDdl = tableDdl; } diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/AbstractHanaDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/AbstractHanaDdl.java index 9f749bc14..f14c96762 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/AbstractHanaDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/AbstractHanaDdl.java @@ -1,6 +1,6 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.config.dbplatform.DatabasePlatform; import io.ebean.config.dbplatform.DbPlatformType; import io.ebeaninternal.dbmigration.ddlgeneration.DdlBuffer; @@ -90,8 +90,8 @@ public abstract class AbstractHanaDdl extends PlatformDdl { } @Override - public DdlHandler createDdlHandler(ServerConfig serverConfig) { - return new HanaDdlHandler(serverConfig, this); + public DdlHandler createDdlHandler(DatabaseConfig config) { + return new HanaDdlHandler(config, this); } @Override diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/BaseTableDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/BaseTableDdl.java index fba4bda6a..9da8ad4bf 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/BaseTableDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/BaseTableDdl.java @@ -1,9 +1,9 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; import io.ebean.annotation.Platform; +import io.ebean.config.DatabaseConfig; import io.ebean.config.DbConstraintNaming; import io.ebean.config.NamingConvention; -import io.ebean.config.ServerConfig; import io.ebean.config.dbplatform.DbHistorySupport; import io.ebean.config.dbplatform.IdType; import io.ebean.util.StringHelper; @@ -202,13 +202,13 @@ public class BaseTableDdl implements TableDdl { /** * Construct with a naming convention and platform specific DDL. */ - public BaseTableDdl(ServerConfig serverConfig, PlatformDdl platformDdl) { - this.namingConvention = serverConfig.getNamingConvention(); - this.naming = serverConfig.getConstraintNaming(); - this.historyTableSuffix = serverConfig.getHistoryTableSuffix(); + public BaseTableDdl(DatabaseConfig config, PlatformDdl platformDdl) { + this.namingConvention = config.getNamingConvention(); + this.naming = config.getConstraintNaming(); + this.historyTableSuffix = config.getHistoryTableSuffix(); this.platformDdl = platformDdl; - this.platformDdl.configure(serverConfig); - this.strictMode = serverConfig.getMigrationConfig().isStrictMode(); + this.platformDdl.configure(config); + this.strictMode = config.getMigrationConfig().isStrictMode(); DbHistorySupport hist = platformDdl.getPlatform().getHistorySupport(); if (hist == null) { this.historySupport = HistorySupport.NONE; diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseDdl.java index f9f943385..97f3bf8c7 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseDdl.java @@ -1,6 +1,6 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.config.dbplatform.DatabasePlatform; import io.ebeaninternal.dbmigration.ddlgeneration.DdlBuffer; import io.ebeaninternal.dbmigration.ddlgeneration.DdlHandler; @@ -19,8 +19,8 @@ public class ClickHouseDdl extends PlatformDdl { } @Override - public DdlHandler createDdlHandler(ServerConfig serverConfig) { - return new ClickHouseDdlHandler(serverConfig, this); + public DdlHandler createDdlHandler(DatabaseConfig config) { + return new ClickHouseDdlHandler(config, this); } @Override diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseDdlHandler.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseDdlHandler.java index 2371cfaee..6f1eb9bce 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseDdlHandler.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseDdlHandler.java @@ -1,11 +1,11 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.dbmigration.ddlgeneration.BaseDdlHandler; public class ClickHouseDdlHandler extends BaseDdlHandler { - public ClickHouseDdlHandler(ServerConfig serverConfig, PlatformDdl platformDdl) { - super(serverConfig, platformDdl, new ClickHouseTableDdl(serverConfig, platformDdl)); + public ClickHouseDdlHandler(DatabaseConfig config, PlatformDdl platformDdl) { + super(config, platformDdl, new ClickHouseTableDdl(config, platformDdl)); } } diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseTableDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseTableDdl.java index c8c432856..66a51f2e7 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseTableDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/ClickHouseTableDdl.java @@ -1,13 +1,13 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.dbmigration.ddlgeneration.DdlBuffer; import io.ebeaninternal.dbmigration.migration.CreateTable; public class ClickHouseTableDdl extends BaseTableDdl { - public ClickHouseTableDdl(ServerConfig serverConfig, PlatformDdl platformDdl) { - super(serverConfig, platformDdl); + public ClickHouseTableDdl(DatabaseConfig config, PlatformDdl platformDdl) { + super(config, platformDdl); } @Override diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/DbTriggerBasedHistoryDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/DbTriggerBasedHistoryDdl.java index f6d5ce94c..575deb5a1 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/DbTriggerBasedHistoryDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/DbTriggerBasedHistoryDdl.java @@ -1,7 +1,7 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; +import io.ebean.config.DatabaseConfig; import io.ebean.config.DbConstraintNaming; -import io.ebean.config.ServerConfig; import io.ebeaninternal.dbmigration.ddlgeneration.DdlBuffer; import io.ebeaninternal.dbmigration.ddlgeneration.DdlWrite; import io.ebeaninternal.dbmigration.migration.AddHistoryTable; @@ -37,12 +37,12 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl { } @Override - public void configure(ServerConfig serverConfig, PlatformDdl platformDdl) { + public void configure(DatabaseConfig config, PlatformDdl platformDdl) { this.platformDdl = platformDdl; - this.sysPeriod = serverConfig.getAsOfSysPeriod(); - this.viewSuffix = serverConfig.getAsOfViewSuffix(); - this.historySuffix = serverConfig.getHistoryTableSuffix(); - this.constraintNaming = serverConfig.getConstraintNaming(); + this.sysPeriod = config.getAsOfSysPeriod(); + this.viewSuffix = config.getAsOfViewSuffix(); + this.historySuffix = config.getHistoryTableSuffix(); + this.constraintNaming = config.getConstraintNaming(); this.sysPeriodStart = sysPeriod + "_start"; this.sysPeriodEnd = sysPeriod + "_end"; diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaDdlHandler.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaDdlHandler.java index b3355e280..47172dc30 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaDdlHandler.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaDdlHandler.java @@ -1,11 +1,11 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.dbmigration.ddlgeneration.BaseDdlHandler; public class HanaDdlHandler extends BaseDdlHandler { - public HanaDdlHandler(ServerConfig serverConfig, PlatformDdl platformDdl) { - super(serverConfig, platformDdl, new HanaTableDdl(serverConfig, platformDdl)); + public HanaDdlHandler(DatabaseConfig config, PlatformDdl platformDdl) { + super(config, platformDdl, new HanaTableDdl(config, platformDdl)); } } diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaHistoryDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaHistoryDdl.java index 84dc76ea7..3624fa1da 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaHistoryDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaHistoryDdl.java @@ -1,6 +1,6 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.dbmigration.ddlgeneration.DdlBuffer; import io.ebeaninternal.dbmigration.ddlgeneration.DdlWrite; import io.ebeaninternal.dbmigration.migration.AddHistoryTable; @@ -24,11 +24,11 @@ public class HanaHistoryDdl implements PlatformHistoryDdl { private Map createdHistoryTables = new ConcurrentHashMap<>(); @Override - public void configure(ServerConfig serverConfig, PlatformDdl platformDdl) { - this.systemPeriodStart = serverConfig.getAsOfSysPeriod() + "_start"; - this.systemPeriodEnd = serverConfig.getAsOfSysPeriod() + "_end"; + public void configure(DatabaseConfig config, PlatformDdl platformDdl) { + this.systemPeriodStart = config.getAsOfSysPeriod() + "_start"; + this.systemPeriodEnd = config.getAsOfSysPeriod() + "_end"; this.platformDdl = platformDdl; - this.historySuffix = serverConfig.getHistoryTableSuffix(); + this.historySuffix = config.getHistoryTableSuffix(); } @Override diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaTableDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaTableDdl.java index c0ce7dcee..341fe9517 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaTableDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/HanaTableDdl.java @@ -1,7 +1,7 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; +import io.ebean.config.DatabaseConfig; import io.ebean.config.PropertiesWrapper; -import io.ebean.config.ServerConfig; import io.ebeaninternal.dbmigration.ddlgeneration.DdlWrite; import io.ebeaninternal.dbmigration.migration.AddColumn; import io.ebeaninternal.dbmigration.migration.AlterColumn; @@ -17,11 +17,11 @@ public class HanaTableDdl extends BaseTableDdl { private final HanaHistoryDdl historyDdl; private final boolean generateUniqueDdl; - public HanaTableDdl(ServerConfig serverConfig, PlatformDdl platformDdl) { - super(serverConfig, platformDdl); + public HanaTableDdl(DatabaseConfig config, PlatformDdl platformDdl) { + super(config, platformDdl); this.historyDdl = (HanaHistoryDdl) platformDdl.historyDdl; - if (serverConfig.getProperties() != null) { - PropertiesWrapper wrapper = new PropertiesWrapper("ebean", "hana", serverConfig.getProperties(), serverConfig.getClassLoadConfig()); + if (config.getProperties() != null) { + PropertiesWrapper wrapper = new PropertiesWrapper("ebean", "hana", config.getProperties(), config.getClassLoadConfig()); this.generateUniqueDdl = wrapper.getBoolean("generateUniqueDdl", false); } else { this.generateUniqueDdl = false; diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/MariaDbHistoryDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/MariaDbHistoryDdl.java index 4dcb101ec..3fbdfad61 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/MariaDbHistoryDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/MariaDbHistoryDdl.java @@ -1,6 +1,6 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.dbmigration.ddlgeneration.DdlBuffer; import io.ebeaninternal.dbmigration.ddlgeneration.DdlWrite; import io.ebeaninternal.dbmigration.migration.AddHistoryTable; @@ -15,7 +15,7 @@ import java.io.IOException; public class MariaDbHistoryDdl implements PlatformHistoryDdl { @Override - public void configure(ServerConfig serverConfig, PlatformDdl platformDdl) { + public void configure(DatabaseConfig config, PlatformDdl platformDdl) { // do nothing } diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/NoHistorySupportDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/NoHistorySupportDdl.java index 9404bf1ca..fbaab9be8 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/NoHistorySupportDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/NoHistorySupportDdl.java @@ -1,6 +1,6 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.dbmigration.ddlgeneration.DdlWrite; import io.ebeaninternal.dbmigration.migration.AddHistoryTable; import io.ebeaninternal.dbmigration.migration.DropHistoryTable; @@ -15,7 +15,7 @@ import java.io.IOException; public class NoHistorySupportDdl implements PlatformHistoryDdl { @Override - public void configure(ServerConfig serverConfig, PlatformDdl platformDdl) { + public void configure(DatabaseConfig config, PlatformDdl platformDdl) { // does nothing } diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformDdl.java index 43e64ca34..8ddc38a33 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformDdl.java @@ -1,6 +1,7 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; import io.ebean.annotation.ConstraintMode; +import io.ebean.config.DatabaseConfig; import io.ebean.config.DbConstraintNaming; import io.ebean.config.ServerConfig; import io.ebean.config.dbplatform.DatabasePlatform; @@ -141,16 +142,16 @@ public class PlatformDdl { /** * Set configuration options. */ - public void configure(ServerConfig serverConfig) { - historyDdl.configure(serverConfig, this); - naming = serverConfig.getConstraintNaming(); + public void configure(DatabaseConfig config) { + historyDdl.configure(config, this); + naming = config.getConstraintNaming(); } /** * Create a DdlHandler for the specific database platform. */ - public DdlHandler createDdlHandler(ServerConfig serverConfig) { - return new BaseDdlHandler(serverConfig, this); + public DdlHandler createDdlHandler(DatabaseConfig config) { + return new BaseDdlHandler(config, this); } /** diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformHistoryDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformHistoryDdl.java index 61bc1362c..cc8838246 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformHistoryDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformHistoryDdl.java @@ -1,6 +1,6 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.dbmigration.ddlgeneration.DdlWrite; import io.ebeaninternal.dbmigration.migration.AddHistoryTable; import io.ebeaninternal.dbmigration.migration.DropHistoryTable; @@ -16,7 +16,7 @@ public interface PlatformHistoryDdl { /** * Configure typically reading the necessary parameters from ServerConfig and Platform. */ - void configure(ServerConfig serverConfig, PlatformDdl platformDdl); + void configure(DatabaseConfig config, PlatformDdl platformDdl); /** * Creates a new table and add history support to the table using platform specific mechanism. diff --git a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/SqlServerHistoryDdl.java b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/SqlServerHistoryDdl.java index f5d907748..bff50e575 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/SqlServerHistoryDdl.java +++ b/src/main/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/SqlServerHistoryDdl.java @@ -1,6 +1,6 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.dbmigration.ddlgeneration.DdlBuffer; import io.ebeaninternal.dbmigration.ddlgeneration.DdlWrite; import io.ebeaninternal.dbmigration.migration.AddHistoryTable; @@ -19,9 +19,9 @@ public class SqlServerHistoryDdl implements PlatformHistoryDdl { private PlatformDdl platformDdl; @Override - public void configure(ServerConfig serverConfig, PlatformDdl platformDdl) { - this.systemPeriodStart = serverConfig.getAsOfSysPeriod() + "From"; - this.systemPeriodEnd = serverConfig.getAsOfSysPeriod() + "To"; + public void configure(DatabaseConfig config, PlatformDdl platformDdl) { + this.systemPeriodStart = config.getAsOfSysPeriod() + "From"; + this.systemPeriodEnd = config.getAsOfSysPeriod() + "To"; this.platformDdl = platformDdl; } diff --git a/src/main/java/io/ebeaninternal/dbmigration/model/PlatformDdlWriter.java b/src/main/java/io/ebeaninternal/dbmigration/model/PlatformDdlWriter.java index 43ce498b9..a3a602e0e 100644 --- a/src/main/java/io/ebeaninternal/dbmigration/model/PlatformDdlWriter.java +++ b/src/main/java/io/ebeaninternal/dbmigration/model/PlatformDdlWriter.java @@ -1,7 +1,7 @@ package io.ebeaninternal.dbmigration.model; +import io.ebean.config.DatabaseConfig; import io.ebean.config.DbMigrationConfig; -import io.ebean.config.ServerConfig; import io.ebean.config.dbplatform.DatabasePlatform; import io.ebeaninternal.dbmigration.ddlgeneration.DdlBuffer; import io.ebeaninternal.dbmigration.ddlgeneration.DdlHandler; @@ -27,7 +27,7 @@ public class PlatformDdlWriter { private static final Logger logger = LoggerFactory.getLogger(PlatformDdlWriter.class); - private final ServerConfig serverConfig; + private final DatabaseConfig serverConfig; private final DbMigrationConfig config; @@ -35,9 +35,9 @@ public class PlatformDdlWriter { private final int lockTimeoutSeconds; - public PlatformDdlWriter(DatabasePlatform platform, ServerConfig serverConfig, DbMigrationConfig config, int lockTimeoutSeconds) { + public PlatformDdlWriter(DatabasePlatform platform, DatabaseConfig dbConfig, DbMigrationConfig config, int lockTimeoutSeconds) { this.platformDdl = PlatformDdlBuilder.create(platform); - this.serverConfig = serverConfig; + this.serverConfig = dbConfig; this.config = config; this.lockTimeoutSeconds = lockTimeoutSeconds; } diff --git a/src/main/java/io/ebeaninternal/server/autotune/service/AutoTuneServiceFactory.java b/src/main/java/io/ebeaninternal/server/autotune/service/AutoTuneServiceFactory.java index c27adf1c9..44ac72887 100644 --- a/src/main/java/io/ebeaninternal/server/autotune/service/AutoTuneServiceFactory.java +++ b/src/main/java/io/ebeaninternal/server/autotune/service/AutoTuneServiceFactory.java @@ -1,14 +1,13 @@ package io.ebeaninternal.server.autotune.service; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.api.SpiEbeanServer; import io.ebeaninternal.server.autotune.AutoTuneService; public class AutoTuneServiceFactory { - public static AutoTuneService create(SpiEbeanServer server, ServerConfig serverConfig) { - - return new DefaultAutoTuneService(server, serverConfig); + public static AutoTuneService create(SpiEbeanServer server, DatabaseConfig config) { + return new DefaultAutoTuneService(server, config); } } diff --git a/src/main/java/io/ebeaninternal/server/autotune/service/DefaultAutoTuneService.java b/src/main/java/io/ebeaninternal/server/autotune/service/DefaultAutoTuneService.java index da7c98322..76e59da77 100644 --- a/src/main/java/io/ebeaninternal/server/autotune/service/DefaultAutoTuneService.java +++ b/src/main/java/io/ebeaninternal/server/autotune/service/DefaultAutoTuneService.java @@ -1,7 +1,7 @@ package io.ebeaninternal.server.autotune.service; import io.ebean.config.AutoTuneConfig; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.api.SpiEbeanServer; import io.ebeaninternal.api.SpiQuery; import io.ebeaninternal.server.autotune.AutoTuneCollection; @@ -49,10 +49,8 @@ public class DefaultAutoTuneService implements AutoTuneService { private long runtimeChangeCount; - public DefaultAutoTuneService(SpiEbeanServer server, ServerConfig serverConfig) { - - AutoTuneConfig config = serverConfig.getAutoTuneConfig(); - + public DefaultAutoTuneService(SpiEbeanServer server, DatabaseConfig databaseConfig) { + AutoTuneConfig config = databaseConfig.getAutoTuneConfig(); this.server = server; this.queryTuning = config.isQueryTuning(); this.profiling = config.isProfiling(); diff --git a/src/main/java/io/ebeaninternal/server/cache/CacheManagerOptions.java b/src/main/java/io/ebeaninternal/server/cache/CacheManagerOptions.java index 36a7ed571..87b8f631f 100644 --- a/src/main/java/io/ebeaninternal/server/cache/CacheManagerOptions.java +++ b/src/main/java/io/ebeaninternal/server/cache/CacheManagerOptions.java @@ -4,7 +4,7 @@ import io.ebean.cache.QueryCacheEntryValidate; import io.ebean.cache.ServerCacheFactory; import io.ebean.cache.ServerCacheOptions; import io.ebean.config.CurrentTenantProvider; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.server.cluster.ClusterManager; /** @@ -14,7 +14,7 @@ public class CacheManagerOptions { private final ClusterManager clusterManager; - private final ServerConfig serverConfig; + private final DatabaseConfig serverConfig; private final boolean localL2Caching; @@ -35,11 +35,11 @@ public class CacheManagerOptions { this.queryDefault = new ServerCacheOptions(); } - public CacheManagerOptions(ClusterManager clusterManager, ServerConfig serverConfig, boolean localL2Caching) { + public CacheManagerOptions(ClusterManager clusterManager, DatabaseConfig config, boolean localL2Caching) { this.clusterManager = clusterManager; - this.serverConfig = serverConfig; + this.serverConfig = config; this.localL2Caching = localL2Caching; - this.currentTenantProvider = serverConfig.getCurrentTenantProvider(); + this.currentTenantProvider = config.getCurrentTenantProvider(); } public CacheManagerOptions with(ServerCacheOptions beanDefault, ServerCacheOptions queryDefault) { diff --git a/src/main/java/io/ebeaninternal/server/cache/DefaultServerCachePlugin.java b/src/main/java/io/ebeaninternal/server/cache/DefaultServerCachePlugin.java index 09cbc0910..262aa8bf2 100644 --- a/src/main/java/io/ebeaninternal/server/cache/DefaultServerCachePlugin.java +++ b/src/main/java/io/ebeaninternal/server/cache/DefaultServerCachePlugin.java @@ -3,7 +3,7 @@ package io.ebeaninternal.server.cache; import io.ebean.BackgroundExecutor; import io.ebean.cache.ServerCacheFactory; import io.ebean.cache.ServerCachePlugin; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; /** * Default implementation of ServerCachePlugin. @@ -14,7 +14,7 @@ public class DefaultServerCachePlugin implements ServerCachePlugin { * Creates the default ServerCacheFactory. */ @Override - public ServerCacheFactory create(ServerConfig config, BackgroundExecutor executor) { + public ServerCacheFactory create(DatabaseConfig config, BackgroundExecutor executor) { return new DefaultServerCacheFactory(executor); } } diff --git a/src/main/java/io/ebeaninternal/server/core/ClassPathScanners.java b/src/main/java/io/ebeaninternal/server/core/ClassPathScanners.java index 11dc2da47..6724fa4f6 100644 --- a/src/main/java/io/ebeaninternal/server/core/ClassPathScanners.java +++ b/src/main/java/io/ebeaninternal/server/core/ClassPathScanners.java @@ -2,7 +2,7 @@ package io.ebeaninternal.server.core; import io.avaje.classpath.scanner.ClassPathScanner; import io.avaje.classpath.scanner.ClassPathScannerFactory; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import java.util.ArrayList; import java.util.List; @@ -15,11 +15,10 @@ public class ClassPathScanners { /** * Return the list of ClassPathScanner services using serverConfig service loader. */ - public static List find(ServerConfig serverConfig) { - + public static List find(DatabaseConfig config) { List scanners = new ArrayList<>(); - for (ClassPathScannerFactory factory : serverConfig.serviceLoad(ClassPathScannerFactory.class)) { - scanners.add(factory.createScanner(serverConfig.getClassLoadConfig().getClassLoader())); + for (ClassPathScannerFactory factory : config.serviceLoad(ClassPathScannerFactory.class)) { + scanners.add(factory.createScanner(config.getClassLoadConfig().getClassLoader())); } return scanners; } diff --git a/src/main/java/io/ebeaninternal/server/core/DatabasePlatformFactory.java b/src/main/java/io/ebeaninternal/server/core/DatabasePlatformFactory.java index f5edba67a..9210f5389 100644 --- a/src/main/java/io/ebeaninternal/server/core/DatabasePlatformFactory.java +++ b/src/main/java/io/ebeaninternal/server/core/DatabasePlatformFactory.java @@ -1,6 +1,6 @@ package io.ebeaninternal.server.core; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.config.dbplatform.DatabasePlatform; import io.ebean.config.dbplatform.clickhouse.ClickHousePlatform; import io.ebean.config.dbplatform.cockroach.CockroachPlatform; @@ -47,26 +47,24 @@ public class DatabasePlatformFactory { /** * Create the appropriate database specific platform. */ - public DatabasePlatform create(ServerConfig serverConfig) { - + public DatabasePlatform create(DatabaseConfig config) { try { - String offlinePlatform = DbOffline.getPlatform(); if (offlinePlatform != null) { logger.info("offline platform [{}]", offlinePlatform); return byDatabaseName(offlinePlatform); } - if (serverConfig.getDatabasePlatformName() != null) { + if (config.getDatabasePlatformName() != null) { // choose based on dbName - return byDatabaseName(serverConfig.getDatabasePlatformName()); + return byDatabaseName(config.getDatabasePlatformName()); } - if (serverConfig.getDataSourceConfig().isOffline()) { + if (config.getDataSourceConfig().isOffline()) { throw new PersistenceException("You must specify a DatabasePlatformName when you are offline"); } // guess using meta data from driver - return byDataSource(serverConfig.getDataSource()); + return byDataSource(config.getDataSource()); } catch (Exception ex) { throw new PersistenceException(ex); diff --git a/src/main/java/io/ebeaninternal/server/core/DefaultContainer.java b/src/main/java/io/ebeaninternal/server/core/DefaultContainer.java index 2c2c3b91c..0b67531c8 100644 --- a/src/main/java/io/ebeaninternal/server/core/DefaultContainer.java +++ b/src/main/java/io/ebeaninternal/server/core/DefaultContainer.java @@ -1,6 +1,8 @@ package io.ebeaninternal.server.core; import io.ebean.config.ContainerConfig; +import io.ebean.config.DatabaseConfig; +import io.ebean.config.DatabaseConfigProvider; import io.ebean.config.ModuleInfoLoader; import io.ebean.config.ServerConfig; import io.ebean.config.ServerConfigProvider; @@ -52,20 +54,16 @@ public class DefaultContainer implements SpiContainer { */ @Override public SpiEbeanServer createServer(String name) { - - ServerConfig config = new ServerConfig(); + DatabaseConfig config = new DatabaseConfig(); config.setName(name); config.loadFromProperties(); - return createServer(config); } - private SpiBackgroundExecutor createBackgroundExecutor(ServerConfig serverConfig) { - + private SpiBackgroundExecutor createBackgroundExecutor(DatabaseConfig serverConfig) { String namePrefix = "ebean-" + serverConfig.getName(); int schedulePoolSize = serverConfig.getBackgroundExecutorSchedulePoolSize(); int shutdownSecs = serverConfig.getBackgroundExecutorShutdownSecs(); - return new DefaultBackgroundExecutor(schedulePoolSize, shutdownSecs, namePrefix); } @@ -73,41 +71,39 @@ public class DefaultContainer implements SpiContainer { * Create the implementation from the configuration. */ @Override - public SpiEbeanServer createServer(ServerConfig serverConfig) { - + public SpiEbeanServer createServer(DatabaseConfig config) { synchronized (this) { - applyConfigServices(serverConfig); - - setNamingConvention(serverConfig); - BootupClasses bootupClasses = getBootupClasses(serverConfig); + applyConfigServices(config); + setNamingConvention(config); + BootupClasses bootupClasses = getBootupClasses(config); boolean online = true; - if (serverConfig.isDocStoreOnly()) { - serverConfig.setDatabasePlatform(new H2Platform()); + if (config.isDocStoreOnly()) { + config.setDatabasePlatform(new H2Platform()); } else { - TenantMode tenantMode = serverConfig.getTenantMode(); + TenantMode tenantMode = config.getTenantMode(); if (TenantMode.DB != tenantMode) { - setDataSource(serverConfig); + setDataSource(config); if (!tenantMode.isDynamicDataSource()) { // check the autoCommit and Transaction Isolation - online = checkDataSource(serverConfig); + online = checkDataSource(config); } } } // determine database platform (Oracle etc) - setDatabasePlatform(serverConfig); - if (serverConfig.getDbEncrypt() != null) { + setDatabasePlatform(config); + if (config.getDbEncrypt() != null) { // use a configured DbEncrypt rather than the platform default - serverConfig.getDatabasePlatform().setDbEncrypt(serverConfig.getDbEncrypt()); + config.getDatabasePlatform().setDbEncrypt(config.getDbEncrypt()); } // inform the NamingConvention of the associated DatabasePlatform - serverConfig.getNamingConvention().setDatabasePlatform(serverConfig.getDatabasePlatform()); + config.getNamingConvention().setDatabasePlatform(config.getDatabasePlatform()); // executor and l2 caching service setup early (used during server construction) - SpiBackgroundExecutor executor = createBackgroundExecutor(serverConfig); - InternalConfiguration c = new InternalConfiguration(online, clusterManager, executor, serverConfig, bootupClasses); + SpiBackgroundExecutor executor = createBackgroundExecutor(config); + InternalConfiguration c = new InternalConfiguration(online, clusterManager, executor, config, bootupClasses); DefaultServer server = new DefaultServer(c, c.cacheManager()); @@ -121,10 +117,17 @@ public class DefaultContainer implements SpiContainer { } } - private void applyConfigServices(ServerConfig config) { + private void applyConfigServices(DatabaseConfig config) { if (config.isDefaultServer()) { - for (ServerConfigProvider configProvider : ServiceLoader.load(ServerConfigProvider.class)) { + boolean appliedConfig = false; + for (DatabaseConfigProvider configProvider : ServiceLoader.load(DatabaseConfigProvider.class)) { configProvider.apply(config); + appliedConfig = true; + } + if (!appliedConfig && config instanceof ServerConfig) { + for (ServerConfigProvider configProvider : ServiceLoader.load(ServerConfigProvider.class)) { + configProvider.apply((ServerConfig)config); + } } if (config.isAutoLoadModuleInfo()) { // auto register entity classes (default db) @@ -157,42 +160,42 @@ public class DefaultContainer implements SpiContainer { * Get the entities, scalarTypes, Listeners etc combining the class registered * ones with the already created instances. */ - private BootupClasses getBootupClasses(ServerConfig serverConfig) { + private BootupClasses getBootupClasses(DatabaseConfig config) { - BootupClasses bootup = getBootupClasses1(serverConfig); - bootup.addIdGenerators(serverConfig.getIdGenerators()); - bootup.addPersistControllers(serverConfig.getPersistControllers()); - bootup.addPostLoaders(serverConfig.getPostLoaders()); - bootup.addPostConstructListeners(serverConfig.getPostConstructListeners()); - bootup.addFindControllers(serverConfig.getFindControllers()); - bootup.addPersistListeners(serverConfig.getPersistListeners()); - bootup.addQueryAdapters(serverConfig.getQueryAdapters()); - bootup.addServerConfigStartup(serverConfig.getServerConfigStartupListeners()); - bootup.addChangeLogInstances(serverConfig); + BootupClasses bootup = getBootupClasses1(config); + bootup.addIdGenerators(config.getIdGenerators()); + bootup.addPersistControllers(config.getPersistControllers()); + bootup.addPostLoaders(config.getPostLoaders()); + bootup.addPostConstructListeners(config.getPostConstructListeners()); + bootup.addFindControllers(config.getFindControllers()); + bootup.addPersistListeners(config.getPersistListeners()); + bootup.addQueryAdapters(config.getQueryAdapters()); + bootup.addServerConfigStartup(config.getServerConfigStartupListeners()); + bootup.addChangeLogInstances(config); // run any ServerConfigStartup instances - bootup.runServerConfigStartup(serverConfig); + bootup.runServerConfigStartup(config); return bootup; } /** * Get the class based entities, scalarTypes, Listeners etc. */ - private BootupClasses getBootupClasses1(ServerConfig serverConfig) { + private BootupClasses getBootupClasses1(DatabaseConfig config) { - List> entityClasses = serverConfig.getClasses(); - if (serverConfig.isDisableClasspathSearch() || (entityClasses != null && !entityClasses.isEmpty())) { + List> entityClasses = config.getClasses(); + if (config.isDisableClasspathSearch() || (entityClasses != null && !entityClasses.isEmpty())) { // use classes we explicitly added via configuration return new BootupClasses(entityClasses); } - return BootupClassPathSearch.search(serverConfig); + return BootupClassPathSearch.search(config); } /** * Set the naming convention to underscore if it has not already been set. */ - private void setNamingConvention(ServerConfig config) { + private void setNamingConvention(DatabaseConfig config) { if (config.getNamingConvention() == null) { config.setNamingConvention(new UnderscoreNamingConvention()); } @@ -201,7 +204,7 @@ public class DefaultContainer implements SpiContainer { /** * Set the DatabasePlatform if it has not already been set. */ - private void setDatabasePlatform(ServerConfig config) { + private void setDatabasePlatform(DatabaseConfig config) { DatabasePlatform platform = config.getDatabasePlatform(); if (platform == null) { @@ -219,7 +222,7 @@ public class DefaultContainer implements SpiContainer { /** * Set the DataSource if it has not already been set. */ - private void setDataSource(ServerConfig config) { + private void setDataSource(DatabaseConfig config) { if (isOfflineMode(config)) { logger.debug("... DbOffline using platform [{}]", DbOffline.getPlatform()); } else { @@ -227,8 +230,8 @@ public class DefaultContainer implements SpiContainer { } } - private boolean isOfflineMode(ServerConfig serverConfig) { - return serverConfig.isDbOffline() || DbOffline.isSet(); + private boolean isOfflineMode(DatabaseConfig config) { + return config.isDbOffline() || DbOffline.isSet(); } /** @@ -241,26 +244,22 @@ public class DefaultContainer implements SpiContainer { * checking may not work as expected. *

*/ - private boolean checkDataSource(ServerConfig serverConfig) { - - if (isOfflineMode(serverConfig)) { + private boolean checkDataSource(DatabaseConfig config) { + if (isOfflineMode(config)) { return false; } - - if (serverConfig.getDataSource() == null) { - if (serverConfig.getDataSourceConfig().isOffline()) { + if (config.getDataSource() == null) { + if (config.getDataSourceConfig().isOffline()) { // this is ok - offline DDL generation etc return false; } throw new RuntimeException("DataSource not set?"); } - - try (Connection connection = serverConfig.getDataSource().getConnection()) { + try (Connection connection = config.getDataSource().getConnection()) { if (connection.getAutoCommit()) { - logger.warn("DataSource [{}] has autoCommit defaulting to true!", serverConfig.getName()); + logger.warn("DataSource [{}] has autoCommit defaulting to true!", config.getName()); } return true; - } catch (SQLException ex) { throw new PersistenceException(ex); } diff --git a/src/main/java/io/ebeaninternal/server/core/DefaultServer.java b/src/main/java/io/ebeaninternal/server/core/DefaultServer.java index 03cd023a9..eef5afd23 100644 --- a/src/main/java/io/ebeaninternal/server/core/DefaultServer.java +++ b/src/main/java/io/ebeaninternal/server/core/DefaultServer.java @@ -44,6 +44,7 @@ import io.ebean.bean.PersistenceContext.WithOption; import io.ebean.cache.ServerCacheManager; import io.ebean.common.CopyOnFirstWriteList; import io.ebean.config.CurrentTenantProvider; +import io.ebean.config.DatabaseConfig; import io.ebean.config.EncryptKeyManager; import io.ebean.config.ServerConfig; import io.ebean.config.SlowQueryEvent; @@ -158,7 +159,7 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer { private static final Logger logger = LoggerFactory.getLogger(DefaultServer.class); - private final ServerConfig serverConfig; + private final DatabaseConfig serverConfig; private final String serverName; @@ -306,12 +307,12 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer { /** * Create the CallStackFactory depending if AutoTune is being used. */ - private CallOriginFactory initCallStackFactory(ServerConfig serverConfig) { - if (!serverConfig.getAutoTuneConfig().isActive()) { + private CallOriginFactory initCallStackFactory(DatabaseConfig config) { + if (!config.getAutoTuneConfig().isActive()) { // use a common CallStack for performance as we don't care with no AutoTune return new NoopCallOriginFactory(); } - return new DefaultCallOriginFactory(serverConfig.getMaxCallStack()); + return new DefaultCallOriginFactory(config.getMaxCallStack()); } private void configureServerPlugins() { @@ -363,7 +364,7 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer { } @Override - public ServerConfig getServerConfig() { + public DatabaseConfig getServerConfig() { return serverConfig; } diff --git a/src/main/java/io/ebeaninternal/server/core/InitDataSource.java b/src/main/java/io/ebeaninternal/server/core/InitDataSource.java index 001ad820e..f5d612ca2 100644 --- a/src/main/java/io/ebeaninternal/server/core/InitDataSource.java +++ b/src/main/java/io/ebeaninternal/server/core/InitDataSource.java @@ -1,6 +1,6 @@ package io.ebeaninternal.server.core; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.datasource.DataSourceAlertFactory; import io.ebean.datasource.DataSourceConfig; import io.ebean.datasource.DataSourceFactory; @@ -16,16 +16,16 @@ class InitDataSource { private final JndiDataSourceLookup jndiDataSourceFactory = new JndiDataSourceLookup(); - private final ServerConfig config; + private final DatabaseConfig config; /** * Create and set the main DataSource and read-only DataSource. */ - static void init(ServerConfig config) { + static void init(DatabaseConfig config) { new InitDataSource(config).initialise(); } - InitDataSource(ServerConfig config) { + InitDataSource(DatabaseConfig config) { this.config = config; } diff --git a/src/main/java/io/ebeaninternal/server/core/InternalConfigXmlRead.java b/src/main/java/io/ebeaninternal/server/core/InternalConfigXmlRead.java index 0716f1812..7c94937b4 100644 --- a/src/main/java/io/ebeaninternal/server/core/InternalConfigXmlRead.java +++ b/src/main/java/io/ebeaninternal/server/core/InternalConfigXmlRead.java @@ -2,7 +2,7 @@ package io.ebeaninternal.server.core; import io.avaje.classpath.scanner.ClassPathScanner; import io.avaje.classpath.scanner.Resource; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.server.dto.DtoNamedQueries; import io.ebeaninternal.xmlmapping.XmlMappingReader; import io.ebeaninternal.xmlmapping.model.XmDto; @@ -23,7 +23,7 @@ class InternalConfigXmlRead { private static final Logger log = LoggerFactory.getLogger(InternalConfigXmlRead.class); - private final ServerConfig serverConfig; + private final DatabaseConfig serverConfig; private final ClassLoader classLoader; @@ -31,7 +31,7 @@ class InternalConfigXmlRead { private List xmlEbeanList; - InternalConfigXmlRead(ServerConfig serverConfig) { + InternalConfigXmlRead(DatabaseConfig serverConfig) { this.serverConfig = serverConfig; this.classLoader = serverConfig.getClassLoadConfig().getClassLoader(); if (serverConfig.getClassLoadConfig().isJavaxJAXBPresent()) { diff --git a/src/main/java/io/ebeaninternal/server/core/InternalConfiguration.java b/src/main/java/io/ebeaninternal/server/core/InternalConfiguration.java index b32cda77b..7616145a0 100644 --- a/src/main/java/io/ebeaninternal/server/core/InternalConfiguration.java +++ b/src/main/java/io/ebeaninternal/server/core/InternalConfiguration.java @@ -9,6 +9,7 @@ import io.ebean.cache.ServerCacheNotify; import io.ebean.cache.ServerCacheNotifyPlugin; import io.ebean.cache.ServerCacheOptions; import io.ebean.cache.ServerCachePlugin; +import io.ebean.config.DatabaseConfig; import io.ebean.config.ExternalTransactionManager; import io.ebean.config.ProfilingConfig; import io.ebean.config.ServerConfig; @@ -115,7 +116,7 @@ public class InternalConfiguration { private final boolean online; - private final ServerConfig serverConfig; + private final DatabaseConfig serverConfig; private final BootupClasses bootupClasses; @@ -171,7 +172,7 @@ public class InternalConfiguration { private final ExtraMetrics extraMetrics = new ExtraMetrics(); InternalConfiguration(boolean online, ClusterManager clusterManager, SpiBackgroundExecutor backgroundExecutor, - ServerConfig serverConfig, BootupClasses bootupClasses) { + DatabaseConfig serverConfig, BootupClasses bootupClasses) { this.online = online; this.serverConfig = serverConfig; @@ -227,7 +228,7 @@ public class InternalConfiguration { /** * Create and return the ExpressionFactory based on configuration and database platform. */ - private ExpressionFactory initExpressionFactory(ServerConfig serverConfig) { + private ExpressionFactory initExpressionFactory(DatabaseConfig serverConfig) { boolean nativeIlike = serverConfig.isExpressionNativeIlike() && databasePlatform.isSupportsNativeIlike(); return new DefaultExpressionFactory(serverConfig.isExpressionEqualsWithNullAsNoop(), nativeIlike); @@ -385,7 +386,7 @@ public class InternalConfiguration { return serverConfig.getDatabasePlatform(); } - public ServerConfig getServerConfig() { + public DatabaseConfig getServerConfig() { return serverConfig; } diff --git a/src/main/java/io/ebeaninternal/server/core/bootup/BootupClassPathSearch.java b/src/main/java/io/ebeaninternal/server/core/bootup/BootupClassPathSearch.java index cc750c410..f2d2eea6f 100644 --- a/src/main/java/io/ebeaninternal/server/core/bootup/BootupClassPathSearch.java +++ b/src/main/java/io/ebeaninternal/server/core/bootup/BootupClassPathSearch.java @@ -1,7 +1,7 @@ package io.ebeaninternal.server.core.bootup; import io.avaje.classpath.scanner.ClassPathScanner; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.server.core.ClassPathScanners; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -24,21 +24,19 @@ public class BootupClassPathSearch { * Search the classPath for the classes we are interested in returning * them as BootupClasses. */ - public static BootupClasses search(ServerConfig serverConfig) { - - return new BootupClassPathSearch(serverConfig).getBootupClasses(); + public static BootupClasses search(DatabaseConfig config) { + return new BootupClassPathSearch(config).getBootupClasses(); } - private BootupClassPathSearch(ServerConfig serverConfig) { - + private BootupClassPathSearch(DatabaseConfig config) { // find packages defined in ebean.mf resources - Set mfPackages = ManifestReader.create(serverConfig.getClassLoadConfig().getClassLoader()) + Set mfPackages = ManifestReader.create(config.getClassLoadConfig().getClassLoader()) .read("META-INF/ebean.mf") .read("ebean.mf") .entityPackages(); - this.packages = DistillPackages.distill(serverConfig.getPackages(), mfPackages); - this.scanners = ClassPathScanners.find(serverConfig); + this.packages = DistillPackages.distill(config.getPackages(), mfPackages); + this.scanners = ClassPathScanners.find(config); } /** diff --git a/src/main/java/io/ebeaninternal/server/core/bootup/BootupClasses.java b/src/main/java/io/ebeaninternal/server/core/bootup/BootupClasses.java index f73d3b778..7e1420fc0 100644 --- a/src/main/java/io/ebeaninternal/server/core/bootup/BootupClasses.java +++ b/src/main/java/io/ebeaninternal/server/core/bootup/BootupClasses.java @@ -2,9 +2,9 @@ package io.ebeaninternal.server.core.bootup; import io.avaje.classpath.scanner.ClassFilter; import io.ebean.annotation.DocStore; +import io.ebean.config.DatabaseConfig; import io.ebean.config.IdGenerator; import io.ebean.config.ScalarTypeConverter; -import io.ebean.config.ServerConfig; import io.ebean.event.BeanFindController; import io.ebean.event.BeanPersistController; import io.ebean.event.BeanPersistListener; @@ -106,12 +106,11 @@ public class BootupClasses implements ClassFilter { /** * Run any ServerConfigStartup listeners. */ - public void runServerConfigStartup(ServerConfig serverConfig) { - + public void runServerConfigStartup(DatabaseConfig config) { for (Class cls : serverConfigStartupCandidates) { try { ServerConfigStartup newInstance = (ServerConfigStartup) cls.newInstance(); - newInstance.onStart(serverConfig); + newInstance.onStart(config); } catch (Exception e) { // assume that the desired behavior is to fail - add your own try catch if needed throw new IllegalStateException("Error running ServerConfigStartup " + cls, e); @@ -119,7 +118,7 @@ public class BootupClasses implements ClassFilter { } for (ServerConfigStartup startup : serverConfigStartupInstances) { try { - startup.onStart(serverConfig); + startup.onStart(config); } catch (Exception e) { // assume that the desired behavior is to fail - add your own try catch if needed throw new IllegalStateException("Error running ServerConfigStartup " + startup.getClass(), e); @@ -188,13 +187,13 @@ public class BootupClasses implements ClassFilter { add(startupInstances, serverConfigStartupInstances, serverConfigStartupCandidates); } - public void addChangeLogInstances(ServerConfig serverConfig) { + public void addChangeLogInstances(DatabaseConfig config) { - readAuditPrepare = serverConfig.getReadAuditPrepare(); - readAuditLogger = serverConfig.getReadAuditLogger(); - changeLogPrepare = serverConfig.getChangeLogPrepare(); - changeLogListener = serverConfig.getChangeLogListener(); - changeLogRegister = serverConfig.getChangeLogRegister(); + readAuditPrepare = config.getReadAuditPrepare(); + readAuditLogger = config.getReadAuditLogger(); + changeLogPrepare = config.getChangeLogPrepare(); + changeLogListener = config.getChangeLogListener(); + changeLogRegister = config.getChangeLogRegister(); // if not already set create the implementations found // via classpath scanning diff --git a/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptor.java b/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptor.java index 3039c3af0..0e2185150 100644 --- a/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptor.java +++ b/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptor.java @@ -12,8 +12,8 @@ import io.ebean.bean.EntityBeanIntercept; import io.ebean.bean.PersistenceContext; import io.ebean.bean.SingleBeanLoader; import io.ebean.cache.QueryCacheEntry; +import io.ebean.config.DatabaseConfig; import io.ebean.config.EncryptKey; -import io.ebean.config.ServerConfig; import io.ebean.config.dbplatform.IdType; import io.ebean.config.dbplatform.PlatformIdGenerator; import io.ebean.event.BeanFindController; @@ -523,7 +523,7 @@ public class BeanDescriptor implements BeanType, STreeType { /** * Return the ServerConfig. */ - public ServerConfig getServerConfig() { + public DatabaseConfig getServerConfig() { return owner.getServerConfig(); } diff --git a/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptorManager.java b/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptorManager.java index 3ab92c5b1..e56bd1b9c 100644 --- a/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptorManager.java +++ b/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptorManager.java @@ -7,6 +7,7 @@ import io.ebean.annotation.ConstraintMode; import io.ebean.bean.BeanCollection; import io.ebean.bean.EntityBean; import io.ebean.config.BeanNotEnhancedException; +import io.ebean.config.DatabaseConfig; import io.ebean.config.EncryptKey; import io.ebean.config.EncryptKeyManager; import io.ebean.config.NamingConvention; @@ -129,7 +130,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap { private final BeanManagerFactory beanManagerFactory; - private final ServerConfig serverConfig; + private final DatabaseConfig serverConfig; private final ChangeLogListener changeLogListener; @@ -270,8 +271,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap { /** * Return the AsOfViewSuffix based on the DbHistorySupport. */ - private String getAsOfViewSuffix(DatabasePlatform databasePlatform, ServerConfig serverConfig) { - + private String getAsOfViewSuffix(DatabasePlatform databasePlatform, DatabaseConfig serverConfig) { DbHistorySupport historySupport = databasePlatform.getHistorySupport(); // with historySupport returns a simple view suffix or the sql2011 as of timestamp suffix return (historySupport == null) ? serverConfig.getAsOfViewSuffix() : historySupport.getAsOfViewSuffix(serverConfig.getAsOfViewSuffix()); @@ -280,7 +280,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap { /** * Return the versions between timestamp suffix based on the DbHistorySupport. */ - private String getVersionsBetweenSuffix(DatabasePlatform databasePlatform, ServerConfig serverConfig) { + private String getVersionsBetweenSuffix(DatabasePlatform databasePlatform, DatabaseConfig serverConfig) { DbHistorySupport historySupport = databasePlatform.getHistorySupport(); // with historySupport returns a simple view suffix or the sql2011 versions between timestamp suffix @@ -293,7 +293,7 @@ public class BeanDescriptorManager implements BeanDescriptorMap { } @Override - public ServerConfig getServerConfig() { + public DatabaseConfig getServerConfig() { return serverConfig; } diff --git a/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptorMap.java b/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptorMap.java index 90fe0c5ff..678947815 100644 --- a/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptorMap.java +++ b/src/main/java/io/ebeaninternal/server/deploy/BeanDescriptorMap.java @@ -1,8 +1,8 @@ package io.ebeaninternal.server.deploy; +import io.ebean.config.DatabaseConfig; import io.ebean.config.EncryptKey; import io.ebean.config.NamingConvention; -import io.ebean.config.ServerConfig; import io.ebeaninternal.server.cache.SpiCacheManager; import io.ebeaninternal.server.deploy.id.IdBinder; import io.ebeaninternal.server.deploy.meta.DeployBeanDescriptor; @@ -25,7 +25,7 @@ public interface BeanDescriptorMap { /** * Return the ServerConfig. */ - ServerConfig getServerConfig(); + DatabaseConfig getServerConfig(); /** * Return the Cache Manager. diff --git a/src/main/java/io/ebeaninternal/server/deploy/BeanLifecycleAdapterFactory.java b/src/main/java/io/ebeaninternal/server/deploy/BeanLifecycleAdapterFactory.java index c27700b7d..273acd7b7 100644 --- a/src/main/java/io/ebeaninternal/server/deploy/BeanLifecycleAdapterFactory.java +++ b/src/main/java/io/ebeaninternal/server/deploy/BeanLifecycleAdapterFactory.java @@ -2,7 +2,7 @@ package io.ebeaninternal.server.deploy; import io.ebean.annotation.PostSoftDelete; import io.ebean.annotation.PreSoftDelete; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.event.BeanPersistAdapter; import io.ebean.event.BeanPersistRequest; import io.ebean.event.BeanPostConstructListener; @@ -34,7 +34,7 @@ class BeanLifecycleAdapterFactory { private final boolean postConstructPresent; - BeanLifecycleAdapterFactory(ServerConfig serverConfig) { + BeanLifecycleAdapterFactory(DatabaseConfig serverConfig) { this.postConstructPresent = serverConfig.getClassLoadConfig().isJavaxPostConstructPresent(); } diff --git a/src/main/java/io/ebeaninternal/server/deploy/generatedproperty/GeneratedPropertyFactory.java b/src/main/java/io/ebeaninternal/server/deploy/generatedproperty/GeneratedPropertyFactory.java index ffd88655e..ecafa6074 100644 --- a/src/main/java/io/ebeaninternal/server/deploy/generatedproperty/GeneratedPropertyFactory.java +++ b/src/main/java/io/ebeaninternal/server/deploy/generatedproperty/GeneratedPropertyFactory.java @@ -3,8 +3,8 @@ package io.ebeaninternal.server.deploy.generatedproperty; import io.ebean.Transaction; import io.ebean.config.ClassLoadConfig; import io.ebean.config.CurrentUserProvider; +import io.ebean.config.DatabaseConfig; import io.ebean.config.IdGenerator; -import io.ebean.config.ServerConfig; import io.ebean.config.dbplatform.PlatformIdGenerator; import io.ebeaninternal.server.deploy.meta.DeployBeanProperty; @@ -37,7 +37,7 @@ public class GeneratedPropertyFactory { private final Map idGeneratorMap = new HashMap<>(); - public GeneratedPropertyFactory(boolean offlineMode, ServerConfig serverConfig, List idGenerators) { + public GeneratedPropertyFactory(boolean offlineMode, DatabaseConfig serverConfig, List idGenerators) { this.classLoadConfig = serverConfig.getClassLoadConfig(); this.insertFactory = new InsertTimestampFactory(classLoadConfig); diff --git a/src/main/java/io/ebeaninternal/server/deploy/meta/DeployBeanDescriptor.java b/src/main/java/io/ebeaninternal/server/deploy/meta/DeployBeanDescriptor.java index cd5fabcd0..961fb945b 100644 --- a/src/main/java/io/ebeaninternal/server/deploy/meta/DeployBeanDescriptor.java +++ b/src/main/java/io/ebeaninternal/server/deploy/meta/DeployBeanDescriptor.java @@ -4,7 +4,7 @@ import io.ebean.annotation.Cache; import io.ebean.annotation.DocStore; import io.ebean.annotation.DocStoreMode; import io.ebean.annotation.Identity; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.config.TableName; import io.ebean.config.dbplatform.IdType; import io.ebean.config.dbplatform.PlatformIdGenerator; @@ -18,7 +18,6 @@ import io.ebean.event.changelog.ChangeLogFilter; import io.ebean.text.PathProperties; import io.ebeaninternal.api.ConcurrencyMode; import io.ebeaninternal.server.core.CacheOptions; -import io.ebeaninternal.server.deploy.IdentityMode; import io.ebeaninternal.server.deploy.BeanDescriptor.EntityType; import io.ebeaninternal.server.deploy.BeanDescriptorManager; import io.ebeaninternal.server.deploy.ChainedBeanPersistController; @@ -27,6 +26,7 @@ import io.ebeaninternal.server.deploy.ChainedBeanPostConstructListener; import io.ebeaninternal.server.deploy.ChainedBeanPostLoad; import io.ebeaninternal.server.deploy.ChainedBeanQueryAdapter; import io.ebeaninternal.server.deploy.DeployPropertyParserMap; +import io.ebeaninternal.server.deploy.IdentityMode; import io.ebeaninternal.server.deploy.IndexDefinition; import io.ebeaninternal.server.deploy.InheritInfo; import io.ebeaninternal.server.deploy.PartitionMeta; @@ -68,7 +68,7 @@ public class DeployBeanDescriptor { private static final String I_SCALAOBJECT = "scala.ScalaObject"; - private final ServerConfig serverConfig; + private final DatabaseConfig serverConfig; private final BeanDescriptorManager manager; @@ -199,7 +199,7 @@ public class DeployBeanDescriptor { /** * Construct the BeanDescriptor. */ - public DeployBeanDescriptor(BeanDescriptorManager manager, Class beanType, ServerConfig serverConfig) { + public DeployBeanDescriptor(BeanDescriptorManager manager, Class beanType, DatabaseConfig serverConfig) { this.manager = manager; this.serverConfig = serverConfig; this.beanType = beanType; diff --git a/src/main/java/io/ebeaninternal/server/deploy/meta/DeployBeanObtainJackson.java b/src/main/java/io/ebeaninternal/server/deploy/meta/DeployBeanObtainJackson.java index 9526c2aa2..20beef7eb 100644 --- a/src/main/java/io/ebeaninternal/server/deploy/meta/DeployBeanObtainJackson.java +++ b/src/main/java/io/ebeaninternal/server/deploy/meta/DeployBeanObtainJackson.java @@ -3,18 +3,18 @@ package io.ebeaninternal.server.deploy.meta; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.introspect.AnnotatedClassResolver; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; /** * Used to obtain the Jackson AnnotatedClass for a given bean type utlimately to obtain field level Jackson annotations. */ class DeployBeanObtainJackson { - private final ServerConfig serverConfig; + private final DatabaseConfig config; private final Class beanType; - DeployBeanObtainJackson(ServerConfig serverConfig, Class beanType) { - this.serverConfig = serverConfig; + DeployBeanObtainJackson(DatabaseConfig config, Class beanType) { + this.config = config; this.beanType = beanType; } @@ -22,8 +22,7 @@ class DeployBeanObtainJackson { * Return the Jackson AnnotatedClass for the given bean type. */ Object obtain() { - - ObjectMapper objectMapper = (ObjectMapper) serverConfig.getObjectMapper(); + ObjectMapper objectMapper = (ObjectMapper) config.getObjectMapper(); JavaType javaType = objectMapper.getTypeFactory().constructType(beanType); return AnnotatedClassResolver.resolve(objectMapper.getDeserializationConfig(), javaType, objectMapper.getDeserializationConfig()); } diff --git a/src/main/java/io/ebeaninternal/server/deploy/parse/DeployUtil.java b/src/main/java/io/ebeaninternal/server/deploy/parse/DeployUtil.java index 1d88478a6..ad0cdb896 100644 --- a/src/main/java/io/ebeaninternal/server/deploy/parse/DeployUtil.java +++ b/src/main/java/io/ebeaninternal/server/deploy/parse/DeployUtil.java @@ -5,12 +5,12 @@ import io.ebean.annotation.DbJson; import io.ebean.annotation.DbJsonB; import io.ebean.annotation.DbJsonType; import io.ebean.annotation.DbMap; +import io.ebean.config.DatabaseConfig; import io.ebean.config.EncryptDeploy; import io.ebean.config.EncryptDeployManager; import io.ebean.config.EncryptKeyManager; import io.ebean.config.Encryptor; import io.ebean.config.NamingConvention; -import io.ebean.config.ServerConfig; import io.ebean.config.TableName; import io.ebean.config.dbplatform.DatabasePlatform; import io.ebean.config.dbplatform.DbPlatformType; @@ -59,17 +59,15 @@ public class DeployUtil { private final boolean useJavaxValidationNotNull; - public DeployUtil(TypeManager typeMgr, ServerConfig serverConfig) { - + public DeployUtil(TypeManager typeMgr, DatabaseConfig config) { this.typeManager = typeMgr; - this.namingConvention = serverConfig.getNamingConvention(); - this.dbPlatform = serverConfig.getDatabasePlatform(); - this.encryptDeployManager = serverConfig.getEncryptDeployManager(); - this.encryptKeyManager = serverConfig.getEncryptKeyManager(); - - Encryptor be = serverConfig.getEncryptor(); + this.namingConvention = config.getNamingConvention(); + this.dbPlatform = config.getDatabasePlatform(); + this.encryptDeployManager = config.getEncryptDeployManager(); + this.encryptKeyManager = config.getEncryptKeyManager(); + Encryptor be = config.getEncryptor(); this.bytesEncryptor = be != null ? be : new SimpleAesEncryptor(); - this.useJavaxValidationNotNull = serverConfig.isUseJavaxValidationNotNull(); + this.useJavaxValidationNotNull = config.isUseJavaxValidationNotNull(); } public TypeManager getTypeManager() { diff --git a/src/main/java/io/ebeaninternal/server/deploy/parse/ReadAnnotationConfig.java b/src/main/java/io/ebeaninternal/server/deploy/parse/ReadAnnotationConfig.java index e1cb4530a..bf96849b0 100644 --- a/src/main/java/io/ebeaninternal/server/deploy/parse/ReadAnnotationConfig.java +++ b/src/main/java/io/ebeaninternal/server/deploy/parse/ReadAnnotationConfig.java @@ -3,7 +3,7 @@ package io.ebeaninternal.server.deploy.parse; import io.ebean.annotation.Aggregation; import io.ebean.annotation.Formula; import io.ebean.annotation.Where; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.server.deploy.generatedproperty.GeneratedPropertyFactory; import javax.persistence.Column; @@ -26,15 +26,13 @@ class ReadAnnotationConfig { private final Set> metaAnnotations = new HashSet<>(); - ReadAnnotationConfig(GeneratedPropertyFactory generatedPropFactory, String asOfViewSuffix, String versionsBetweenSuffix, ServerConfig serverConfig) { - + ReadAnnotationConfig(GeneratedPropertyFactory generatedPropFactory, String asOfViewSuffix, String versionsBetweenSuffix, DatabaseConfig config) { this.generatedPropFactory = generatedPropFactory; this.asOfViewSuffix = asOfViewSuffix; this.versionsBetweenSuffix = versionsBetweenSuffix; - this.disableL2Cache = serverConfig.isDisableL2Cache(); - this.eagerFetchLobs = serverConfig.isEagerFetchLobs(); - this.idGeneratorAutomatic = serverConfig.isIdGeneratorAutomatic(); - + this.disableL2Cache = config.isDisableL2Cache(); + this.eagerFetchLobs = config.isEagerFetchLobs(); + this.idGeneratorAutomatic = config.isIdGeneratorAutomatic(); this.javaxValidationAnnotations = generatedPropFactory.getClassLoadConfig().isJavaxValidationAnnotationsPresent(); this.jacksonAnnotations = generatedPropFactory.getClassLoadConfig().isJacksonAnnotationsPresent(); this.metaAnnotations.add(Column.class); diff --git a/src/main/java/io/ebeaninternal/server/deploy/parse/ReadAnnotations.java b/src/main/java/io/ebeaninternal/server/deploy/parse/ReadAnnotations.java index aad6f547e..a14f91182 100644 --- a/src/main/java/io/ebeaninternal/server/deploy/parse/ReadAnnotations.java +++ b/src/main/java/io/ebeaninternal/server/deploy/parse/ReadAnnotations.java @@ -1,6 +1,6 @@ package io.ebeaninternal.server.deploy.parse; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.server.deploy.BeanDescriptorManager; import io.ebeaninternal.server.deploy.generatedproperty.GeneratedPropertyFactory; @@ -12,7 +12,7 @@ public class ReadAnnotations { private final ReadAnnotationConfig readConfig; - public ReadAnnotations(GeneratedPropertyFactory generatedPropFactory, String asOfViewSuffix, String versionsBetweenSuffix, ServerConfig serverConfig) { + public ReadAnnotations(GeneratedPropertyFactory generatedPropFactory, String asOfViewSuffix, String versionsBetweenSuffix, DatabaseConfig serverConfig) { this.readConfig = new ReadAnnotationConfig(generatedPropFactory, asOfViewSuffix, versionsBetweenSuffix, serverConfig); if (readConfig.isJavaxValidationAnnotations()) { InitMetaValidationAnnotation.init(readConfig); diff --git a/src/main/java/io/ebeaninternal/server/query/CQueryEngine.java b/src/main/java/io/ebeaninternal/server/query/CQueryEngine.java index 3e8bab49c..8df9e38f6 100644 --- a/src/main/java/io/ebeaninternal/server/query/CQueryEngine.java +++ b/src/main/java/io/ebeaninternal/server/query/CQueryEngine.java @@ -6,7 +6,7 @@ import io.ebean.Version; import io.ebean.bean.BeanCollection; import io.ebean.bean.EntityBean; import io.ebean.bean.ObjectGraphNode; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.config.dbplatform.DatabasePlatform; import io.ebean.util.JdbcClose; import io.ebean.util.StringHelper; @@ -54,7 +54,7 @@ public class CQueryEngine { private final DatabasePlatform dbPlatform; - public CQueryEngine(ServerConfig serverConfig, DatabasePlatform dbPlatform, Binder binder, Map asOfTableMapping, Map draftTableMap) { + public CQueryEngine(DatabaseConfig serverConfig, DatabasePlatform dbPlatform, Binder binder, Map asOfTableMapping, Map draftTableMap) { this.dbPlatform = dbPlatform; this.defaultFetchSizeFindEach = serverConfig.getJdbcFetchSizeFindEach(); this.defaultFetchSizeFindList = serverConfig.getJdbcFetchSizeFindList(); diff --git a/src/main/java/io/ebeaninternal/server/transaction/TransactionManagerOptions.java b/src/main/java/io/ebeaninternal/server/transaction/TransactionManagerOptions.java index f55389a19..9a1b0139b 100644 --- a/src/main/java/io/ebeaninternal/server/transaction/TransactionManagerOptions.java +++ b/src/main/java/io/ebeaninternal/server/transaction/TransactionManagerOptions.java @@ -2,7 +2,7 @@ package io.ebeaninternal.server.transaction; import io.ebean.BackgroundExecutor; import io.ebean.cache.ServerCacheNotify; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebeaninternal.api.SpiLogManager; import io.ebeaninternal.api.SpiProfileHandler; import io.ebeaninternal.server.cluster.ClusterManager; @@ -16,7 +16,7 @@ import io.ebeanservice.docstore.api.DocStoreUpdateProcessor; public class TransactionManagerOptions { final boolean notifyL2CacheInForeground; - final ServerConfig config; + final DatabaseConfig config; final ClusterManager clusterManager; final BackgroundExecutor backgroundExecutor; @@ -31,7 +31,7 @@ public class TransactionManagerOptions { final ClockService clockService; - public TransactionManagerOptions(boolean notifyL2CacheInForeground, ServerConfig config, TransactionScopeManager scopeManager, ClusterManager clusterManager, + public TransactionManagerOptions(boolean notifyL2CacheInForeground, DatabaseConfig config, TransactionScopeManager scopeManager, ClusterManager clusterManager, BackgroundExecutor backgroundExecutor, DocStoreUpdateProcessor docStoreUpdateProcessor, BeanDescriptorManager descMgr, DataSourceSupplier dataSourceSupplier, SpiProfileHandler profileHandler, SpiLogManager logManager, TableModState tableModState, ServerCacheNotify cacheNotify, ClockService clockService) { diff --git a/src/main/java/io/ebeaninternal/server/type/DefaultTypeFactory.java b/src/main/java/io/ebeaninternal/server/type/DefaultTypeFactory.java index 77a69ae21..3392aeafa 100644 --- a/src/main/java/io/ebeaninternal/server/type/DefaultTypeFactory.java +++ b/src/main/java/io/ebeaninternal/server/type/DefaultTypeFactory.java @@ -1,7 +1,7 @@ package io.ebeaninternal.server.type; +import io.ebean.config.DatabaseConfig; import io.ebean.config.JsonConfig; -import io.ebean.config.ServerConfig; import io.ebeaninternal.server.core.BasicTypeConverter; import java.math.BigInteger; @@ -14,9 +14,9 @@ import java.util.Calendar; */ public class DefaultTypeFactory { - private final ServerConfig serverConfig; + private final DatabaseConfig serverConfig; - public DefaultTypeFactory(ServerConfig serverConfig) { + public DefaultTypeFactory(DatabaseConfig serverConfig) { this.serverConfig = serverConfig; } diff --git a/src/main/java/io/ebeaninternal/server/type/DefaultTypeManager.java b/src/main/java/io/ebeaninternal/server/type/DefaultTypeManager.java index 521721553..c3dff6054 100644 --- a/src/main/java/io/ebeaninternal/server/type/DefaultTypeManager.java +++ b/src/main/java/io/ebeaninternal/server/type/DefaultTypeManager.java @@ -8,10 +8,10 @@ import io.ebean.annotation.DbEnumType; import io.ebean.annotation.DbEnumValue; import io.ebean.annotation.EnumValue; import io.ebean.annotation.Platform; +import io.ebean.config.DatabaseConfig; import io.ebean.config.JsonConfig; import io.ebean.config.PlatformConfig; 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.Cidr; @@ -184,7 +184,7 @@ public final class DefaultTypeManager implements TypeManager { /** * Create the DefaultTypeManager. */ - public DefaultTypeManager(ServerConfig config, BootupClasses bootupClasses) { + public DefaultTypeManager(DatabaseConfig config, BootupClasses bootupClasses) { this.java7Present = config.getClassLoadConfig().isJava7Present(); this.jsonDateTime = config.getJsonDateTime(); @@ -248,7 +248,7 @@ public final class DefaultTypeManager implements TypeManager { /** * Load custom scalar types registered via ExtraTypeFactory and ServiceLoader. */ - private void loadTypesFromProviders(ServerConfig config, Object objectMapper) { + private void loadTypesFromProviders(DatabaseConfig config, Object objectMapper) { ServiceLoader factories = ServiceLoader.load(ExtraTypeFactory.class); Iterator iterator = factories.iterator(); @@ -785,12 +785,11 @@ public final class DefaultTypeManager implements TypeManager { add(scalarType); } - private Object initObjectMapper(ServerConfig serverConfig) { - - Object objectMapper = serverConfig.getObjectMapper(); + private Object initObjectMapper(DatabaseConfig config) { + Object objectMapper = config.getObjectMapper(); if (objectMapper == null) { objectMapper = new ObjectMapper(); - serverConfig.setObjectMapper(objectMapper); + config.setObjectMapper(objectMapper); } return objectMapper; } @@ -862,12 +861,9 @@ public final class DefaultTypeManager implements TypeManager { /** * Add support for Jackson's JsonNode mapping to Clob, Blob, Varchar, JSON and JSONB. */ - private void initialiseJacksonTypes(ServerConfig config) { - + private void initialiseJacksonTypes(DatabaseConfig config) { if (objectMapper != null) { - logger.trace("Registering JsonNode type support"); - ObjectMapper mapper = (ObjectMapper) objectMapper; jsonNodeClob = new ScalarTypeJsonNode.Clob(mapper); jsonNodeBlob = new ScalarTypeJsonNode.Blob(mapper); @@ -885,12 +881,10 @@ public final class DefaultTypeManager implements TypeManager { } } - private void initialiseJavaTimeTypes(ServerConfig config) { - + private void initialiseJavaTimeTypes(DatabaseConfig config) { if (java7Present) { typeMap.put(java.nio.file.Path.class, new ScalarTypePath()); } - if (config.getClassLoadConfig().isJavaTimePresent()) { logger.debug("Registering java.time data types"); addType(java.time.Period.class, new ScalarTypePeriod()); @@ -926,8 +920,7 @@ public final class DefaultTypeManager implements TypeManager { * Detect if Joda classes are in the classpath and if so register the Joda data types. */ @SuppressWarnings("deprecation") - private void initialiseJodaTypes(ServerConfig config) { - + private void initialiseJodaTypes(DatabaseConfig config) { // detect if Joda classes are in the classpath if (config.getClassLoadConfig().isJodaTimePresent()) { // Joda classes are in the classpath so register the types @@ -955,8 +948,7 @@ public final class DefaultTypeManager implements TypeManager { * Register all the standard types supported. This is the standard JDBC types * plus some other common types such as java.util.Date and java.util.Calendar. */ - private void initialiseStandard(ServerConfig config) { - + private void initialiseStandard(DatabaseConfig config) { DatabasePlatform databasePlatform = config.getDatabasePlatform(); int platformClobType = databasePlatform.getClobDbType(); int platformBlobType = databasePlatform.getBlobDbType(); diff --git a/src/test/java/io/ebean/EbeanServerFactory_ServerConfigStart_Test.java b/src/test/java/io/ebean/EbeanServerFactory_ServerConfigStart_Test.java index 8cc14eb2c..f3cdd5688 100644 --- a/src/test/java/io/ebean/EbeanServerFactory_ServerConfigStart_Test.java +++ b/src/test/java/io/ebean/EbeanServerFactory_ServerConfigStart_Test.java @@ -1,11 +1,10 @@ package io.ebean; -import io.ebean.EbeanServer; -import io.ebean.EbeanServerFactory; +import io.ebean.config.DatabaseConfig; import io.ebean.config.ServerConfig; import io.ebean.event.ServerConfigStartup; -import org.tests.model.basic.UTDetail; import org.junit.Test; +import org.tests.model.basic.UTDetail; import static org.assertj.core.api.Assertions.assertThat; @@ -47,10 +46,10 @@ public class EbeanServerFactory_ServerConfigStart_Test { public static class OnStartup implements ServerConfigStartup { - ServerConfig calledWithConfig; + DatabaseConfig calledWithConfig; @Override - public void onStart(ServerConfig serverConfig) { + public void onStart(DatabaseConfig serverConfig) { calledWithConfig = serverConfig; } } @@ -58,10 +57,10 @@ public class EbeanServerFactory_ServerConfigStart_Test { public static class OnStartupViaClass implements ServerConfigStartup { - static ServerConfig calledWithConfig; + static DatabaseConfig calledWithConfig; @Override - public void onStart(ServerConfig serverConfig) { + public void onStart(DatabaseConfig serverConfig) { calledWithConfig = serverConfig; } } diff --git a/src/test/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformDdl_AlterColumnTest.java b/src/test/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformDdl_AlterColumnTest.java index 9b761bb36..5faa823bf 100644 --- a/src/test/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformDdl_AlterColumnTest.java +++ b/src/test/java/io/ebeaninternal/dbmigration/ddlgeneration/platform/PlatformDdl_AlterColumnTest.java @@ -1,6 +1,7 @@ package io.ebeaninternal.dbmigration.ddlgeneration.platform; import io.ebean.Ebean; +import io.ebean.config.DatabaseConfig; import io.ebean.config.ServerConfig; import io.ebean.config.dbplatform.IdType; import io.ebean.config.dbplatform.h2.H2Platform; @@ -28,7 +29,7 @@ public class PlatformDdl_AlterColumnTest { private final PlatformDdl hanaDdl = PlatformDdlBuilder.create(new HanaPlatform()); { - ServerConfig serverConfig = Ebean.getDefaultServer().getPluginApi().getServerConfig(); + DatabaseConfig serverConfig = Ebean.getDefaultServer().getPluginApi().getServerConfig(); sqlServerDdl.configure(serverConfig); } diff --git a/src/test/java/org/tests/model/basic/MyEBasicConfigStartup.java b/src/test/java/org/tests/model/basic/MyEBasicConfigStartup.java index 0441b40ff..72cb3e689 100644 --- a/src/test/java/org/tests/model/basic/MyEBasicConfigStartup.java +++ b/src/test/java/org/tests/model/basic/MyEBasicConfigStartup.java @@ -1,6 +1,6 @@ package org.tests.model.basic; -import io.ebean.config.ServerConfig; +import io.ebean.config.DatabaseConfig; import io.ebean.event.AbstractBeanPersistListener; import io.ebean.event.BulkTableEvent; import io.ebean.event.BulkTableEventListener; @@ -23,7 +23,7 @@ public class MyEBasicConfigStartup implements ServerConfigStartup { } @Override - public void onStart(ServerConfig serverConfig) { + public void onStart(DatabaseConfig serverConfig) { serverConfig.add(new EbasicPersistList()); serverConfig.add(new EbasicBulkListener());