Compare commits

..
759 Commits
Author SHA1 Message Date
Rob Bygrave 61cc5e3459 Version 16.10.0 2026-06-09 07:57:32 +12:00
Rob Bygrave 23f23fa32b Bump ebean-agent to 16.10.0 2026-06-09 07:53:36 +12:00
Rob BygraveandGitHub f65c409bfe Merge pull request #3781 from ebean-orm/feature/sqlquery-plan-capture
SqlQuery - add support for query plan capture
2026-06-09 00:39:52 +12:00
robin.bygrave ec49824430 SqlQuery - update docs wrt plan capture 2026-06-09 00:28:13 +12:00
robin.bygrave 819aaece4d SqlQuery - add support for query plan capture 2026-06-09 00:20:53 +12:00
Rob BygraveandGitHub c275953582 Merge pull request #3780 from ebean-orm/feature/dto-plan-capture
DtoQuery updated to support query plan capture
2026-06-08 23:47:40 +12:00
robin.bygrave 82e8494f42 Add profile location test 2026-06-08 23:47:21 +12:00
robin.bygrave abacda2c8f Update docs 2026-06-08 23:34:19 +12:00
robin.bygrave a7d1253dba DtoQuery skip bind capture when it's actually an orm query 2026-06-08 23:31:52 +12:00
robin.bygrave a081d08621 DtoQuery initiate the bind capture 2026-06-08 23:24:13 +12:00
robin.bygrave 8c37b53bad DtoQuery modified to support query plan capture 2026-06-08 23:06:09 +12:00
Rob Bygrave 3f6d565800 Version 16.9.0 2026-06-08 19:09:46 +12:00
Rob BygraveandGitHub 1408696912 Redesign of metric labels - secondary queries (lazy|query) now just u… (#3779)
* Redesign of metric labels - secondary queries (lazy|query) now just use parent + relativePath + type

# Query metric/plan label change — comparison

Improves the metric/plan name generated for **secondary** (`_lazy` / `_query`) loads so
they relate to their parent/root query, and unifies separators on `.`.

The secondary lazy name is now **always** `orm.<parent's full name>.<path>.<loadMode>`,
so it always prefixes the real parent metric.

## Root query name

| Root query source | Original | New |
|---|---|---|
| `setLabel("custMain")` | `orm.Customer_custMain` | `orm.Customer.custMain` |
| ProfileLocation `CustomerFinder.byName` | `orm.CustomerFinder.byName` | `orm.CustomerFinder.byName` *(same)* |
| ProfileLocation `DataLoader.loadAll` (Customer query) | `orm.Customer_DataLoader.loadAll` | `orm.Customer.DataLoader.loadAll` |
| Unlabeled, no location | `orm.Customer.findList` | `orm.Customer.findList` *(same)* |

## Secondary lazy (`contacts`) name

Original prefixes the **loaded** type (`Contact`) + the call-site location and uses `__`
between path and load mode. New prefixes the **parent's full name**.

| Root query source | Original lazy name | New lazy name |
|---|---|---|
| `setLabel("custMain")` *(profile location also present)* | `orm.Contact_CustomerFinder.findActive_contacts__lazy` — explicit label **lost** | `orm.Customer.custMain.contacts.lazy` |
| `setLabel("custMain")` *(no profile location)* | `orm.Contact_custMain_contacts__lazy` | `orm.Customer.custMain.contacts.lazy` |
| ProfileLocation `CustomerFinder.byName` | `orm.Contact_CustomerFinder.byName_contacts__lazy` | `orm.CustomerFinder.byName.contacts.lazy` |
| ProfileLocation `DataLoader.loadAll` | `orm.Contact_DataLoader.loadAll_contacts__lazy` | `orm.Customer.DataLoader.loadAll.contacts.lazy` |
| Unlabeled, no location | `orm.Contact.findList` *(own name; no parent path)* | `orm.Contact.findList` *(same)* |

## Problems fixed
- **(A) Secondary load didn't relate to its parent** — original prefixed the *loaded* type
  (`Contact`) + the *call-site* location, never the parent query's name. New name literally
  starts with the parent's full name.
- Explicit `setLabel` was **silently dropped** for secondary queries when a profile location
  existed.
- `__` path/loadMode separator and mixed `_`/`.` replaced by uniform `.`.

## Nested and `.query` secondary loads

Each secondary query name is `<immediate parent's full name>.<immediate path>.<loadMode>`,
so every hop literally prefixes its parent metric. Example with root `setLabel("custMain")`
on `Customer`, chain `Customer -> orders -> details`:

Nested lazy:
```
orm.Customer.custMain
orm.Customer.custMain.orders.lazy
orm.Customer.custMain.orders.lazy.details.lazy
```

Secondary eager `.query` fetch:
```
orm.Customer.custMain
orm.Customer.custMain.orders.query
orm.Customer.custMain.orders.query.details.query
```

The intermediate load mode (`.lazy.` / `.query.`) is retained so each name is an exact
extension of its immediate parent's name.

* Use ProfileLocation as leading metric name without <type> prefix

* docs: Add guide for ebean-query-metrics.md

* docs: Add guide for query plan capture
2026-06-08 19:03:43 +12:00
Rob Bygrave e0531a6315 Merge branch 'master' of github.com:ebean-orm/ebean 2026-06-08 19:01:17 +12:00
0023f0ce13 [open telemetry] Add query lable as an attribute to the query spans (#3778)
Co-authored-by: robin.bygrave <robin.bygrave@eroad.com>
2026-06-08 10:42:12 +12:00
Rob Bygrave 032f4de857 Version 16.8.0 2026-06-06 20:06:30 +12:00
Rob Bygrave 59431814ce Merge branch 'master' of github.com:ebean-orm/ebean 2026-06-06 19:57:18 +12:00
Rob BygraveandGitHub e7194055be Merge pull request #3776 from ebean-orm/feature/PString_eqIfNotBlank
Add PString eqIfNotBlank() helper query expression
2026-06-06 18:37:59 +12:00
robin.bygrave 806c7cd752 Fix test with overlapping cases 2026-06-06 18:16:11 +12:00
Rob BygraveandGitHub dfc7f92160 Merge pull request #3777 from ebean-orm/fature/otel-query-hash
[open telemetry] Add query hash as an attribute to the query spans
2026-06-06 18:04:18 +12:00
robin.bygrave 26351325a8 Fix test with overlapping cases 2026-06-06 18:03:39 +12:00
robin.bygrave 2d37f9d01e [open telemetry] Add query hash as an attribute to the query spans 2026-06-06 17:55:59 +12:00
robin.bygrave d3fd03ce5b Add PString eqIfNotBlank() helper query expression
Just to make this relatively common case pretty nice and clean
2026-06-06 17:45:45 +12:00
Rob Bygrave a8e92791cd Version 16.7.0 2026-06-03 07:44:59 +12:00
Rob BygraveandGitHub 94e63cc30f Merge pull request #3774 from ebean-orm/feature/timedMetric-max-reset
Add collectMetrics(reset) option, with change to query time metric MA…
2026-06-02 14:48:15 +12:00
Rob BygraveandGitHub 3567263250 Merge pull request #3775 from ebean-orm/feature/fix-error-profiling-batch
open telemetry: Fix for IndexOutOfBoundsException with Batched PreparedStatements and open telemetry
2026-06-02 14:46:54 +12:00
robin.bygrave bc03f8d516 open telemetry: Fix for IndexOutOfBoundsException with Batched PreparedStatements and open telemetry
Caused by: java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
 at jdk.internal.util.Preconditions.outOfBounds(Unknown Source)
 at jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Unknown Source)
 at jdk.internal.util.Preconditions.checkIndex(Unknown Source)
 at java.util.Objects.checkIndex(Unknown Source)
 at java.util.ArrayList.get(Unknown Source)
 at io.ebeaninternal.server.persist.BatchedPstmt.profile(BatchedPstmt.java:132)
2026-06-02 14:42:44 +12:00
robin.bygrave 7035ff20eb Docs: Add a doc guide for adding open telemetry 2026-05-29 17:11:04 +12:00
Rob BygraveandGitHub f38479022a Merge pull request #3773 from ebean-orm/dependabot/maven/ebean-opentelemetry/io.opentelemetry-opentelemetry-api-1.62.0
Build(deps): Bump io.opentelemetry:opentelemetry-api from 1.51.0 to 1.62.0 in /ebean-opentelemetry
2026-05-21 22:12:11 +12:00
robin.bygrave 986cc905d8 Fix test only - Resource test entity table name invalid for Oracle 2026-05-21 22:10:58 +12:00
robin.bygrave 8f3fe688cb Fix test only - ResourceEntityTest SQL for Postgres uses ANY rather than IN 2026-05-21 22:05:59 +12:00
robin.bygrave eee26d9ed3 Add collectMetrics(reset) option, with change to query time metric MAX value to reset
So the desire here is to better support sending metrics to Prometheus style metrics collectors that prefer CUMULATIVE metrics rather than DELTA based metrics.

To do this, expose additional MetaInfoManager.collectMetrics(reset) method.

In supporting this, the MAX value really does need to reset even with CUMULATIVE metrics and act more like a gauge as otherwise it becomes almost useless as the max value over the lifetime. So we need to adjust MAX to always reset and act like a gauge to be useful in this CUMULATIVE metrics reporting mode.
2026-05-21 22:03:15 +12:00
dependabot[bot]andGitHub 44bd60e586 Build(deps): Bump io.opentelemetry:opentelemetry-api
Bumps [io.opentelemetry:opentelemetry-api](https://github.com/open-telemetry/opentelemetry-java) from 1.51.0 to 1.62.0.
- [Release notes](https://github.com/open-telemetry/opentelemetry-java/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-java/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-java/compare/v1.51.0...v1.62.0)

---
updated-dependencies:
- dependency-name: io.opentelemetry:opentelemetry-api
  dependency-version: 1.62.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-14 16:44:36 +00:00
Rob BygraveandGitHub 20d7af6d25 Merge pull request #3772 from ebean-orm/feature/otel-isRecording
open telemetry: Use Span.current().isRecording() rather than isValid()
2026-05-14 16:22:57 +12:00
robin.bygrave e5aeda9d4e open telemetry: Use Span.current().isRecording() rather than isValid()
Change to use isRecording() to determine if ProfileStream should be
created for collecting profiling events
2026-05-14 16:20:28 +12:00
Sergey KuznetsovandGitHub 46bb1ca060 Add timeout support to UpdateQuery and DefaultUpdateQuery (#3771) 2026-05-14 15:25:07 +12:00
robin.bygrave 0652167101 docs: add next steps to test container guide
- Suggest TestEntityBuilder for test data creation
- Link to testing-with-testentitybuilder.md
2026-05-13 13:57:40 +12:00
robin.bygrave 6633293151 docs: update guide versions and fix defaults
- ebean.version 17.2.0 -> 17.5.0 (minimum for TestEntityBuilder)
- avaje-inject 11.5 -> 12.5
- Add io.avaje:junit:1.8 bundle to test dependencies
- Remove .skipDataSourceCheck(true) from database config example
- Add note about Configuration DI wiring in Step 3
2026-05-13 13:57:39 +12:00
Rob BygraveandGitHub 9e603f2848 Deprecate DatabaseConfig and DatabaseFactory, prefer Database.builder() (#3769)
* Deprecate DatabaseConfig and DatabaseFactory, prefer Database.builder()

Deprecate the DatabaseConfig way of creating Database instance.
Migrate to use Database.builder().

* Deprecate DatabaseConfig and DatabaseFactory, migrate test code

* Use @Deprecated(forRemoval = true) on DatabaseConfig and DatabaseFactory

* Tidy up Database javadoc for deprecation
2026-05-08 00:06:43 +12:00
Rob Bygrave fff345ffc8 Merge branch 'master' of github.com:ebean-orm/ebean 2026-05-07 22:13:16 +12:00
Rob BygraveandGitHub dd1fe845aa Remove the DefaultProfileHandler & DefaultProfileStream (Replaced by ebean-opentelemetry) (#3767)
So migrate to use opentelemetry, and remove these internal profilers as
they are never expected to be used now.
2026-05-07 22:10:08 +12:00
Rob BygraveandGitHub 80451c3c62 Performance: Improve OrmQueryProperties, include } into immutableHashSuffix (#3768) 2026-05-07 21:42:20 +12:00
Rob Bygrave 2d199737aa Docs: Add docs/notes on potential future L2 immutable bean cache 2026-05-07 21:36:45 +12:00
Rob Bygrave 63a1e9907d Version 16.6.0 2026-05-06 23:06:25 +12:00
Rob Bygrave 67db089646 Bump ebean-agent version, no effective change 2026-05-06 22:56:49 +12:00
26478924a7 Build(deps): Bump org.postgresql:postgresql in /ebean-pgvector-types (#3766)
Bumps [org.postgresql:postgresql](https://github.com/pgjdbc/pgjdbc) from 42.7.2 to 42.7.11.
- [Release notes](https://github.com/pgjdbc/pgjdbc/releases)
- [Changelog](https://github.com/pgjdbc/pgjdbc/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pgjdbc/pgjdbc/compare/REL42.7.2...REL42.7.11)

---
updated-dependencies:
- dependency-name: org.postgresql:postgresql
  dependency-version: 42.7.11
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-06 22:50:12 +12:00
3cb22fb0cc Build(deps): Bump org.postgresql:postgresql in /ebean-postgis-types (#3765)
Bumps [org.postgresql:postgresql](https://github.com/pgjdbc/pgjdbc) from 42.7.2 to 42.7.11.
- [Release notes](https://github.com/pgjdbc/pgjdbc/releases)
- [Changelog](https://github.com/pgjdbc/pgjdbc/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pgjdbc/pgjdbc/compare/REL42.7.2...REL42.7.11)

---
updated-dependencies:
- dependency-name: org.postgresql:postgresql
  dependency-version: 42.7.11
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-06 22:49:42 +12:00
Rob BygraveandGitHub 4dde7064ba Add ImmutableBeanCache - some parts of the query result graph populated via ImmutableBeanCache (#3753)
* Change [implicit] Lazy loading to be by TYPE rather than by PATH

We have some graph models where a common type (in the tests it is Label)
is used in many different *paths* of the graph. When we are loading via
*path* then all the loading of the Labels isn't in a single batch / load context
but instead split into different load contexts PER PATH.

This change, means that lazy loading operates by TYPE instead of by PATH.

In the tests, all the Labels are read via a single lazy loading query rather
that one lazy loading query per PATH, and this is more efficient.

* ImmutableBeanCache part 1

* ImmutableBeanCache part 2

* ImmutableBeanCache part 3 - add ImmutableBeanCaches

* ImmutableBeanCache - add propagation of caches to secondary queries

* ImmutableBeanCache - use and improve BeanDescriptor.merge() to positional

Using positional avoids the lookup by property name.

* ImmutableBeanCache - add unit testing with BeanDescriptorMergeTest

* ImmutableBeanCache - add testing for the further lazy loading on mutable beans

Also add doc / guides

* Add ImmutableCacheBuilder with underlying DefaultServerCache implementation

This provides a cache with maxSize, maxIdleSeconds, maxSecondsToLive

* Improve javadoc and doc / guides for ImmutableBeanCache

* Add cache invalidation for ImmutableBeanCache

* Use immutable cache direct hits for unmodifiable assoc-one refs

 - add ImmutableBeanCache.getIfPresent() as a non-loading probe
 - use immutable cache hits in AssocOneHelp / AssocOneHelpRefInherit
 - avoid creating ref beans and merge/copy for unmodifiable cache hits
 - keep existing mutable-query and miss/backfill behavior unchanged
2026-05-06 22:35:30 +12:00
681221c0ff Add ebean-opentelemetry module (#3752)
* Enhance ProfileStream to support Open Telemetry

* Add ebean-opentelemetry module

* Add the sql query text as span attribute.

Note: This is a breaking API change here but I'm pretty confident
that no one is using the ProfileStream API - hmmm.

* Otel: Use the query label and transaction label in span name if available

* SpiProfileHandler: Change such that if service loaded, doesn't need ProfileConfig

---------

Co-authored-by: Rob Bygrave <robin.bygrave@gmail.com>
2026-05-06 21:49:31 +12:00
Rob Bygrave d6ce093ac5 Bench: Add general perf benchmark to FetchGroupSelectApplyBenchmark 2026-05-05 23:03:34 +12:00
Rob BygraveandGitHub 515b8e5958 Performance improvement in OrmQueryDetail with copyInto() (#3763)
Relatively minor improvement from reusing existing OrmQueryDetail
2026-05-05 22:54:58 +12:00
Rob BygraveandGitHub 86b4af1321 Performance improvement in OrmQueryProperties with immutable hash prefix and suffix (#3762) 2026-05-05 22:42:09 +12:00
Rob Bygrave eb73318f53 Performance improvement in OrmQueryProperties when appending Set<String> 2026-05-05 21:55:26 +12:00
Rob BygraveandGitHub 96a3ab9d79 Performance improvement in OrmQueryProperties for FetchGroup reuse (#3761) 2026-05-05 21:35:35 +12:00
Rob Bygrave 9954ad1ea7 Docs: Update add ebean postgres guide with gate on DI question 2026-05-04 23:50:19 +12:00
robin.bygrave 2928247ba7 Docs: Add the mkdir 2026-05-01 16:45:43 +12:00
robin.bygrave 3066bb4f74 Docs: Setup add a Step 4b - add di dependencies bit 2026-05-01 16:07:58 +12:00
robin.bygrave a96144cdaa Docs: Adjust setup guide with initial DI / no DI question 2026-05-01 16:03:11 +12:00
robin.bygrave 50e20c3aa0 Docs: update docs / skills location to separate git repo 2026-05-01 15:38:37 +12:00
robin.bygrave f07ca68eb3 Docs: Add docs/skill/ebean-orm 2026-05-01 15:09:54 +12:00
robin.bygrave 0ec7ddb82d Docs: Change the ordering so that test container setup proceeds the main database configuration 2026-05-01 14:59:36 +12:00
robin.bygrave 8074a24d03 Docs: Improve docs with DB -> database and wording around getters/setters/accessors 2026-05-01 14:52:43 +12:00
Rob BygraveandGitHub 7e4a2db9aa Add Query alsoIfPresent() as helper for Nullable conditional expressions (#3756)
Add this as a helper for when using alsoIf(BooleanPredicate) seems overkill
and there isn't a built in IfPresent option for the desired expression and
wanting to keep the fluid style.
2026-04-28 23:24:50 +12:00
Rob BygraveandGitHub 292dcf4b0e Add IfPresent options for like, ilike, startsWith, istartsWith, contains, icontains (#3755) 2026-04-28 23:06:57 +12:00
robin.bygrave f44bf59cb6 Docs: Improve testing-with-testentitybuilder.md - better wiring example 2026-04-24 17:52:44 +12:00
robin.bygrave 7c3741e258 Docs: Add llms.txt to assist agents
Note that this is effectively a duplication of the website llms.txt
2026-04-24 10:18:00 +12:00
robin.bygrave afadaa7208 Docs: Add a template AGENTS.md to assist agent onboarding 2026-04-24 09:32:37 +12:00
46b7510e6c TestEntityBuilder - add saveAll() helper method (#3751)
Co-authored-by: robin.bygrave <robin.bygrave@eroad.com>
2026-04-22 15:10:04 +12:00
Rob Bygrave bcb0b049ff Tests for Oracle, drop pstmtCache to 100
The default was bumped to 300. Seeing ORA-01000: maximum open cursors exceeded
in the Oracle integration test so thinking it is due to the increase in
default preparedStatement cache.
2026-04-22 00:15:25 +12:00
Rob Bygrave 42bfaaf2bf Tests for Oracle, drop pstmtCache to 100
The default was bumped to 300. Seeing ORA-01000: maximum open cursors exceeded
in the Oracle integration test so thinking it is due to the increase in
default preparedStatement cache.
2026-04-22 00:14:20 +12:00
Rob Bygrave 2ca39f1419 Fix test TestErrorBindLog for DB2 2026-04-22 00:03:22 +12:00
Rob Bygrave de2914e550 Fix test TestQueryJoinOnFormula for Postgres distinct on 2026-04-22 00:00:53 +12:00
robin.bygrave 6eda7044a0 Docs: Improve testing-with-testentitybuilder.md 2026-04-21 13:01:18 +12:00
robin.bygrave e4adf25022 Docs: Improve testing-with-testentitybuilder.md 2026-04-20 15:49:44 +12:00
robin.bygrave ad5483100e Improve README.md with reference to llms.txt 2026-04-20 14:55:01 +12:00
robin.bygrave 6d9ed670ef Docs: Improve doc guides wording 2026-04-16 16:48:27 +12:00
robin.bygrave 9e2d821475 Docs: Add LIBRARY.md 2026-04-16 13:53:22 +12:00
Rob Bygrave 80ce7a41a2 Docs: guides - improve writing query beans guide 2026-04-14 00:46:37 +12:00
Rob Bygrave 6458bb0f1c Docs: Add docs / guides for writing queries and using transactions 2026-04-14 00:34:21 +12:00
Rob Bygrave 7ba550cc0d Docs: Add docs / guides for ebean entity bean recommendations 2026-04-12 23:49:41 +12:00
Rob Bygrave fff8dfb8b1 Docs: Add docs / guides for ebean entity bean recommendations 2026-04-12 23:43:54 +12:00
Rob Bygrave d0af7b1788 Docs: Add docs / guides for testing with TestEntityBuilder 2026-04-12 22:51:51 +12:00
Rob Bygrave ebb0305cf3 Version 16.5.0 2026-04-12 22:31:24 +12:00
Rob Bygrave d03d36bba4 Update ebean-agent 2026-04-12 22:27:52 +12:00
Rob BygraveandGitHub 88408edd24 Bump ebean-datasource dependency to 10.5 with increase default prepared statement cache (#3749)
Default prepared statement cache increased from 100 to 300. This could have the
effect of increased memory consumption for applications traded off with potentially
improved performance due to me cached prepared statements for larger applications.

Note that the Postgres itself has a default of 250.
2026-04-12 22:27:02 +12:00
Rob Bygrave 0aad35b840 Merge branch 'master' of github.com:ebean-orm/ebean 2026-04-12 17:21:04 +12:00
Rob Bygrave e7979b285d Docs: docs / guides - add reference link to ebean-datasource guides 2026-04-12 17:20:45 +12:00
Roland PramlandGitHub 91920b00dc M2M on child path produce wrong query on extra join (#3653)
* Testcase for ManyToMany with extra join

* Fix query generation for extra ManyToMany joins

* Fix other tests due different query
2026-04-12 15:07:08 +12:00
Rob Bygrave bdfe016d2d Refactor DLoadBeanContext extract helper method ensureBatchInContext() 2026-04-12 15:02:07 +12:00
b2670f9cc0 Lazy load pre delete 2 (#3748)
* Lazy load in pre-delete does not work

* Re-add deleted beans before lazy-load will happen

* Put the contextClear() calls into a finally

This should mean that any beans put into the context would be
cleared even if there was an issue with the loadBean() call.

---------

Co-authored-by: Roland Praml <roland.praml@foconis.de>
2026-04-12 15:00:28 +12:00
ebc90e0e82 FEATURE: Add support for Generic mapped superclass (#3692)
* creates support for generics in mapped superclasses

* Changes DeployCreateProperties to allow processing of inheritance hierarchies with generics

* adds tests for ebean-querybean

* bumps querybean-generator version

* fixes tests by changing table names for ProductWithGenericLong and ProductWithGenericString

* Restore format, this reduces the diff

* Restore format, this reduces the diff

---------

Co-authored-by: Rob Bygrave <robin.bygrave@gmail.com>
2026-04-12 13:31:49 +12:00
Rob BygraveandGitHub c4230c780f Add usingMaster() to SqlQuery.TypeQuery (#3744) 2026-04-12 12:49:39 +12:00
Rob BygraveandGitHub 794f933310 Feat: Add test entity builder, ease creation of test entity instances populated with random values (#3747)
* Docs: modify guides README with links to the available guides

* Add TestEntityBuilder for building test entity instances populated by random values

* Improve TestEntityBuilder for emails, BigDecimal precision/scale, protected method allow overriding

* Improve TestEntityBuilder for emails, use PersonOther
2026-04-12 12:46:49 +12:00
AntoineDuComptoirDesPharmaciesandGitHub c8a7a263a9 #3129 (#3746)
This Pull Request aim to fix the problem of DBJSONB dirty detection listed in #3129 which was due to PostgreSQL JSONB key reordering while storing value.
This cause Ebean to mark @DbJsonB properties as dirty on every load (triggering unnecessary UPDATEs and version increments) because the raw DB JSON key order differed from Jackson's serialization order.
Currently, Ebean is using CRC32 Checksum to compare but it is field ordering-dependent.

Introduce JsonContentHash:
A streaming order-independent structural hash of JSON content using Jackson's JsonParser.
Object keys are combined with commutative addition (a + b == b + a) so key ordering does not affect the hash, while array elements use positional hashing to preserve semantic ordering.
The hash uses FNV-1a for strings and MurmurHash3's fmix64 finalizer (both public domain) for mixing, producing a 64-bit hash with strong avalanche properties.

Changes:
- Add JsonContentHash utility (streaming, zero allocation, O(n) time)
- SourceMutableValue: use fast string equality with canonical hash fallback
- ChecksumMutableValue: replace CRC32 with JsonContentHash (also upgrades collision resistance from 2^32 to 2^64)
- No API changes, no schema changes, readSet() untouched
2026-04-12 12:46:13 +12:00
robin.bygrave aeef6d0ea2 Docs: modify guides README with snippets devs should copy n paste into their README etc to help guide the AI agents to the appropriate ebean guides 2026-04-11 01:25:23 +12:00
robin.bygrave a99aef8b00 Docs: modify guides section, add initialConnections with explanation 2026-04-11 01:09:30 +12:00
robin.bygrave 6f17cc6327 Docs: Add docs / guides for adding db migration generation 2026-04-11 01:00:08 +12:00
robin.bygrave 903947b3cb Docs: Add docs / guides for lombok use 2026-04-11 00:24:27 +12:00
robin.bygrave 797f75f7b7 Docs: Add docs / guides for postgres test container setup 2026-04-11 00:07:45 +12:00
Rob BygraveandGitHub af443ef2f2 Merge pull request #3745 from ebean-orm/docs/guides-one
Docs: Add docs / guides for step-by-step instructions for AI agents
2026-04-10 23:42:33 +12:00
robin.bygrave ad4f027835 Docs: Add docs / guides for step-by-step instructions for AI agents 2026-04-10 23:42:05 +12:00
Rob Bygrave 367eba8685 Version 16.4.0 2026-04-10 08:03:12 +12:00
Rob BygraveandGitHub be542635a5 Bump ebean-test-containers to 8.0 (major bump to mark the port fix) (#3742)
Docker changed and that broke how ebean-test-containers detected the
currently assigned port for a container. That was fixed in 7.18 but
thinking its a good idea to mark that relatively important bug fix
with a bump of the major version to 8.0.

Everyone using ebean-test-containers should consider updating the
ebean-test-containers dependency to 8.0 or 7.18 (both have the fix).
2026-04-10 08:00:04 +12:00
Rob BygraveandGitHub 6e9d0a91e0 Fix for @Column on timestamp defined as timestamp(255) (#3740)
As per https://github.com/ebean-orm/ebean/discussions/3720

```
  @Column
  ZonedDateTime zonedDateTime2;
```
... resulting in DDL generated as `timestamp(255)`. This is
occurring when the JPA dependency is used like:
jakarta.persistence:jakarta.persistence-api:3.2.0
rather than using the transitive dependency that ebean includes.

Workaround:
Remove the jakarta.persistence:jakarta.persistence-api:3.2.0 dependency.

Fix:
The fix here is to use a timestamp type that has a maximum precision.
When a precision/length is specified greater than the maximum precision
then the fallback type is used which is `timestamp` without any precision.
2026-04-10 00:46:34 +12:00
Rob BygraveandGitHub a99ef3ebf2 Bump ebean-datasource dependency to 10.4, resets metrics on initialisation (#3739) 2026-04-09 22:23:55 +12:00
19afa845d1 FEATURE: inTuples() expressions support for natural key cache lookup (#3732)
* `inTuples()` support for natural key cache lookup

* Simplify NaturalKeyEntryBasic.addInPairs()

---------

Co-authored-by: Rob Bygrave <robin.bygrave@gmail.com>
2026-04-09 19:46:33 +12:00
Rob BygraveandGitHub 239900cd3b Bump ebean-agent to 16.4.0 with support for Java 26 (#3738) 2026-04-09 19:15:36 +12:00
robin.bygrave 73ac39971c Update test TestErrorBindLog for DB2 2026-04-08 22:55:41 +12:00
robin.bygrave 3a876252ec Update test TestQueryJoinOnFormula, restrict platforms for specific test
Restrict the new test_findCount_formulaJoin_subqueryWithOrderBy_issue3686
to H2 and Postgres for now. Not supported on Oracle and SQL Server.
2026-04-08 22:33:06 +12:00
robin.bygrave 231b52ba88 Update test TestErrorBindLog to improve failure message 2026-04-08 22:27:46 +12:00
robin.bygrave 808019cf3d Modify tests, move setRegister(false) setDefaultServer(false) before loadFromProperties() 2026-04-08 22:15:11 +12:00
Rob Bygrave 364520455f Add some logging for test BeanPersistControllerTest 2026-04-08 08:58:38 +12:00
Rob BygraveandGitHub e92621a489 Try old ebean agent, for strange CI build issue (#3737) 2026-04-08 08:51:33 +12:00
Rob BygraveandGitHub ccd1b7b8ec Bump ebean-test-containers to 7.18 (#3736) 2026-04-08 08:31:02 +12:00
thomas-lcdpandGitHub d144273307 ebean-core#3686: use parenthesis-aware ORDER BY removal in buildRowCountQuery to avoid breaking nested subqueries (#3729) 2026-03-27 23:18:15 +13:00
Rob BygraveandGitHub 41c5ebdcd7 Bump ebean-agent with ASM 9.9.1 and Java 26 support (#3731) 2026-03-27 23:15:00 +13:00
Rob BygraveandGitHub 9e711efecb Merge pull request #3730 from ebean-orm/feature/add-docs-for-graalvm-support
Add GraalVM native image support documentation
2026-03-27 22:06:00 +13:00
robin.bygrave ef7fd76f14 Add GraalVM native image support documentation 2026-03-27 22:05:21 +13:00
robin.bygrave b7e3ddbedd Add GraalVM native image badge to README.md 2026-03-27 21:55:29 +13:00
Rob Bygrave 69c932816a Version 16.3.0 2026-02-16 21:07:49 +13:00
Rob Bygrave a1facf527b Bump ebean-agent and avaje junit 2026-02-16 21:03:37 +13:00
Rob BygraveandGitHub ec42ebf66d Bump ebean-datasource to 10.3 (#3727)
This version has moved the connection initialisation that sets the
autoCommit mode to be after the clientInfo and any initial sql has
been executed
2026-02-16 20:24:58 +13:00
Rob Bygrave 5dede70801 Fix for #3722 Remove isSkipCacheExplicit() and use isSkipCache()
This change is to reduce PUTs causing cache pollution where
changes that are rolled back are PUT into the bean cache.

Effectively remove the isSkipCacheExplicit() feature and just
use the existing isSkipCache(). This means that skipCacheAfterWrite
is used and PUTs after a database write/insert/update/delete are
effectively skipped.
2026-02-16 19:49:56 +13:00
Rob BygraveandGitHub b2f02ecc1f Fix for #3723 FilterMany predicates added to incorrect join clause (#3725)
The change that moved the filterMany predicates to the join had an
issue that extra joins may be needed to support those predicates.

Prior to this change, the extra predicates where effectively just
added to the end of the joins, rather than as a "child" node in
the SqlTreeNode tree.

This fix is in SqlTreeBuilder, where the list of top level extra
joins are first tried to be added as a child to a parent node, and
only if we can't find the parent added at the end.
2026-02-15 21:47:17 +13:00
15fa7cd1c2 Bump org.assertj:assertj-core from 3.27.6 to 3.27.7 in /ebean-test (#3718)
Bumps [org.assertj:assertj-core](https://github.com/assertj/assertj) from 3.27.6 to 3.27.7.
- [Release notes](https://github.com/assertj/assertj/releases)
- [Commits](https://github.com/assertj/assertj/compare/assertj-build-3.27.6...assertj-build-3.27.7)

---
updated-dependencies:
- dependency-name: org.assertj:assertj-core
  dependency-version: 3.27.7
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-15 10:02:49 +13:00
Rob BygraveandGitHub 8dced38cd5 Bump kotlin maven plugin version in build (#3724)
* Bump kotlin maven plugin version in build

* For build bump kotlin-maven-plugin version to 2.3.10
2026-02-15 09:59:16 +13:00
Rob Bygrave 7addba7c93 Version 16.2.1 2026-02-02 23:22:22 +13:00
Rob BygraveandGitHub 00b45c1642 For query usingMaster support passing a boolean (#3721)
This is to support the use case where other logic is used to determine if a query
should be "forced" to use the master data source or not, and so it's easier to
pass that as a boolean to the usingMaster() method.
2026-02-02 23:17:37 +13:00
Rob Bygrave a3d9711fe6 Version 16.2.0 2025-11-23 22:18:54 +13:00
Rob Bygrave 1239c50723 Bump ebean-agent to 16.2.0 2025-11-23 22:16:29 +13:00
Rob BygraveandGitHub d85d8449e2 #3695 Behaviour change: findSingleAttribute() to throw when multiple … (#3697)
* #3695 Behaviour change: findSingleAttribute() to throw when multiple rows returned by query

On the plus, this makes the behaviour consistent with all the other findOne() methods (ORM, DTO, SqlQuery) and this very much feels like buggy behaviour [to just get the first result and ignore any subsequent results in the ResultSet]

On the negative of merging this bug fix, any application code relying on the existing behaviour with this fix will break and throw a NonUniqueResultException at RUNTIME (not ideal). However, for these cases where the application now throws an exception, people might not be aware that they were relying on this behaviour and this exception could be useful to highlight that (a potential non-deterministic query result was being used and a potential source of bugs was being).

* Change SqlQuery + Mapper + findOne() also to throw NonUniqueResultException
2025-11-23 22:14:44 +13:00
baf71cbab3 Bump com.microsoft.sqlserver:mssql-jdbc in /ebean-test (#3694)
Bumps [com.microsoft.sqlserver:mssql-jdbc](https://github.com/Microsoft/mssql-jdbc) from 10.2.0.jre8 to 11.1.0.jre8-preview.
- [Release notes](https://github.com/Microsoft/mssql-jdbc/releases)
- [Changelog](https://github.com/microsoft/mssql-jdbc/blob/main/CHANGELOG.md)
- [Commits](https://github.com/Microsoft/mssql-jdbc/commits)

---
updated-dependencies:
- dependency-name: com.microsoft.sqlserver:mssql-jdbc
  dependency-version: 11.1.0.jre8-preview
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-11-23 21:01:00 +13:00
Rob BygraveandGitHub ff0ca35e54 #3701 Improve error message when missing dependency ebean-jackson-mapper (#3708) 2025-11-23 20:25:16 +13:00
0fc9a1ac2f Bug fix and change filterMany to put predicates into JOIN clause, Fix for #3626 (#3707)
* Problem with filterMany

* Missing id

* Other test

* Fix

* Update TestQueryFilterMany.java

* #3706 Bug fix and change filterMany to put predicates into JOIN clause, Fix for #3626

* Fix tests for Postgres, Oracle, Sql Server

---------

Co-authored-by: Roman Parshikov <promansew@gmail.com>
2025-11-23 20:20:13 +13:00
Rob BygraveandGitHub f7b4edb193 Merge pull request #3704 from ebean-orm/feature/bump-test-deps-bytebuddy
Bump test dependencies byte buddy and assertj
2025-11-20 09:35:09 +13:00
robin.bygrave 284c8d4d21 Bump test dependencies byte buddy and assertj 2025-11-20 09:23:39 +13:00
Rob BygraveandGitHub 59a5c5f9bd Bump dependency avaje-config to 4.2 (#3699) 2025-11-11 07:59:40 +13:00
Rob BygraveandGitHub 5b04d6eca3 #3551 Log warning for use of mapping column to Class (#3698)
I think it was a mistake for Ebean to support Class<?> from a security perspective. Instead, Ebean should just use a String <-> Varchar and leave if up to the application to take that String and convert it to a class [and then that potential Class initialisation is owned by the application code and all security considerations around that are owned by the application code].
2025-11-11 07:57:15 +13:00
d5547808a2 PGvector support (#3696)
* Add pgvector-types module.

* Add missing binder definitions.
Add missing PGbit type registration.
Few tests.

* Add cached bean test.

* Prefer final classes, minor formating only

---------

Co-authored-by: Rob Bygrave <robin.bygrave@gmail.com>
2025-11-09 16:55:51 +13:00
Rob Bygrave 5606c95de5 Version 16.1.1 2025-10-22 22:45:21 +13:00
Rob Bygrave 4c2bd408b0 Bump ebean-agent 2025-10-22 22:42:00 +13:00
Rob Bygrave db76d5c27c Test only - add Postgres JSONB raw() expression example 2025-10-22 22:03:09 +13:00
Rob Bygrave f92c2f8c14 Test only - add test for string id InsertOnConflict 2025-10-22 22:02:40 +13:00
Rob BygraveandGitHub 51c3065419 3683 - Add AggregateFormulaContext to support group_concat etc (#3691)
- Add AggregateFormulaContext with ability to override the default via DatabaseBuilder
- Add group_concat, string_agg, listagg to set of known aggregation functions
2025-10-21 22:54:55 +13:00
Rob Bygrave e46dd66292 Test only - bump to Postgres 17 for PostgresReadOnlyDatabaseTest 2025-10-21 20:55:52 +13:00
Rob Bygrave 3e1451bee7 Merge branch 'master' of github.com:ebean-orm/ebean 2025-10-21 20:54:23 +13:00
Rob BygraveandGitHub 4ac3c4ddb1 3682 @Aggregation is applied to query if entity also has a @lob column (#3689)
* Version 16.1.0

* #3682 @Aggregation is applied to query if entity also has a @Lob column

The underling issue was that Aggregation columns should have been marked as default LAZY. This impact was only hit when @Lob column are included which by default lazy fetched, and that means the default select clause determined.
2025-10-20 20:55:18 +13:00
Rob Bygrave ee8e48902b Merge branch 'master' of github.com:ebean-orm/ebean 2025-10-19 18:07:18 +13:00
Rob BygraveandGitHub c37e752ace #3681 javadoc query cache (#3687)
* Version 16.1.0

* Improve javadoc for Query setUseQueryCache() and unmodifiable

Since 16.x a query using the query cache returns unmodifiable object graphs.
2025-10-14 20:04:38 +13:00
Rob Bygrave c9a6f822ac Version 16.1.0 2025-09-19 18:48:28 +12:00
Rob BygraveandGitHub 2231ef9fd1 Bump ebean-agent to 16.1.0 with Java 25 support (#3680)
Note that the IntelliJ plugin has been updated and published. It should be public in a few days.
2025-09-19 16:25:24 +12:00
Rob Bygrave 3ff1905318 Bump ebean-test-containers to 7.15 with updated ClickHouse support 2025-09-19 16:25:00 +12:00
Rob BygraveandGitHub 9b4fecff96 Add support for AutoCommit true transactions (#3679)
* Add support for AutoCommit true transactions

* Update DocStoreTransactionManager
2025-09-19 16:22:59 +12:00
Rob BygraveandGitHub 6f356fd55e #3674 Add @Nullable to Query getId(), getForUpdateLockWait(), getForUpdateLockType() (#3675)
These methods return nullable results, add JSpecify `@Nullable` to correctly indicate this.
2025-09-06 17:22:13 +12:00
Rob BygraveandGitHub 591f260f5b Retain filterMany expression when select fetchGroup applied after filterMany (#3673) 2025-09-02 22:35:43 +12:00
Rob Bygrave b361b10571 Version 16.0.1 2025-09-02 14:09:03 +12:00
Rob BygraveandGitHub c0e4e548ee Update the kotlin-maven-plugin for tests and use EA maven profile (#3671)
* Update the kotlin-maven-plugin for tests

* Add a profile for EA that excludes kotlin-querybean-generator

* For build workflow use maven profile "default"

To ensure the kotlin-querybean-generator, test modules run

* For build workflow use maven profile "default"

To ensure the kotlin-querybean-generator, test modules run
2025-09-02 14:04:59 +12:00
Rob Bygrave 92f3245919 Bump ebean-agent to 16.0.1 2025-09-02 13:37:45 +12:00
Rob BygraveandGitHub 59c2290916 Bump ebean-migration dependency, fix for setting dbSchema on migrations (#3670)
Ref: https://github.com/ebean-orm/ebean-migration/pull/163
2025-09-02 12:52:41 +12:00
Rob BygraveandGitHub 1135eb3f99 #3665 Fix for delete() Skips Bean due to Hash Collision (#3669)
Change the underlying storage of deleting beans to be by type by id so:

  private Map<Class<?>, Set<Object>> deletingBeans;
2025-08-31 22:32:27 +12:00
Rob BygraveandGitHub 1dccdff7bf #3664 Fix / support for extra JoinColumns on ManyToOne (#3668)
* #3664 Fix / support for extra JoinColumns on ManyToOne

Allows for extra JoinColumns on ManyToOne. The extra JoinColumn(s) are
expected to be useful for the case of table partitioning where the extra
join column is used to partition the table. In the test case, the partition
column would be the org_id column and common to both tables (same partition key).

* #3664 Fix / support for extra JoinColumns on ManyToOne

Allows for extra JoinColumns on ManyToOne. The extra JoinColumn(s) are
expected to be useful for the case of table partitioning where the extra
join column is used to partition the table. In the test case, the partition
column would be the org_id column and common to both tables (same partition key).

* #3664 Extend test

* #3664 Tidy up test
2025-08-31 12:52:17 +12:00
Rob BygraveandGitHub 5f74a53e3e #3666 Fix for NPE with filterMany() containing or() (#3667)
For FilterMany with QueryBeans, it creates a queryBean to build the filterMany predicates with. This query bean needed 2 changes for this fix:

1. Needs to set it's internal "root" such that it supports chaining (required for or() etc)
2. The ExpressionFactory needs to be explicitly passed to the expression list (rather than get it from the query which is actually null in this case).
2025-08-31 10:08:07 +12:00
Rob Bygrave 1f9e652ea9 Version 16.0.0 2025-08-25 08:21:49 +12:00
Rob Bygrave 4e592c97ff Update how to deploy 2025-08-05 23:30:18 +12:00
Rob Bygrave 760d19a10d Update how to deploy 2025-08-05 23:16:42 +12:00
Rob Bygrave d2693c3ff2 Version 16.0.0-RC4 2025-08-05 23:15:20 +12:00
Rob BygraveandGitHub 3324b2bda4 Use autocommit false with findIterate for Postgres (#3662)
* Use autocommit false with findIterate for Postgres

* Use autocommit false with findIterate for Postgres

* Use autocommit false with FindDto queries for Postgres

* Use autocommit false with SqlQuery findIterate queries for Postgres

* Ensure that TransactionFactory.createReadOnlyTransaction() returns an ImplicitReadOnlyTransaction

This change changes TransactionFactoryTenant.createReadOnlyTransaction() to return a ImplicitReadOnlyTransaction, as that is now used to support Postgres use of cursors with findIterate style queries.
2025-08-05 23:03:28 +12:00
Rob BygraveandGitHub 1b5e066562 #3654 Fix querybean-generator compiler warning for unclaimed annotations (#3655)
warning: No processor claimed any of these annotations: /io.ebean.typequery.TypeQueryBean,/io.ebean.typequery.Generated

This fix is required when the compiler is run with -Werror specified

An alternative workaround is to use compiler arg -Xlint:-processing rather than -Xlint:all
2025-07-16 20:34:56 +12:00
Rob BygraveandGitHub 104e4ec756 Bump ebean-test-containers to 7.14 - Yugabyte read committed support enabled by default (#3651) 2025-07-14 09:03:39 +12:00
Rob Bygrave 74a2967a6e Tests Yugabyte - comment out the TestQueryForUpdate using repeatable read
... as its noise there is anyone else reads the logs
2025-07-12 09:38:06 +12:00
Rob Bygrave e693b12a97 Tests DB2 - ignore TestRawExpressionInterpolation for DB2 2025-07-12 09:30:16 +12:00
Rob Bygrave 48fb9b34bb Tests Yugabyte - faster test using forUpdate 2025-07-12 09:18:01 +12:00
Rob Bygrave f64400400a Tests Oracle - ignore the TestRawExpressionInterpolation for Oracle 2025-07-12 09:09:34 +12:00
Rob Bygrave d7cc081942 Tests Yugabyte - see if everything else passes 2025-07-12 09:04:02 +12:00
Rob Bygrave 3351548b60 Fix use of JSpecify Nullable annotation in query bean generation 2025-07-11 23:45:31 +12:00
Rob Bygrave 8d9858f57a Test only - Update logging for test TestQueryForUpdate 2025-07-11 23:35:03 +12:00
Rob Bygrave 9b520bc176 Bump avaje-config to 4.1 2025-07-11 23:22:16 +12:00
Rob Bygrave 44fd8e3a56 Adjust TestQueryForUpdate for Yugabyte - use markAsDirty on repeatable read test 2025-07-11 23:11:45 +12:00
Rob Bygrave 6910016c4d Adjust TestQueryForUpdate for Yugabyte - use markAsDirty
To see if the update has an impact on the 2nd thread waiting
2025-07-11 22:58:02 +12:00
Rob Bygrave 5f8a3c0591 Adjust TestQueryForUpdate for Yugabyte - check repeatable read isolation level 2025-07-11 22:05:31 +12:00
Rob BygraveandGitHub 0ae6956c1c Bump ebean-datasource 10.1 with support for initialConnections (#3650)
So in a K8s deployment, this adds support for having an initial number of connections to create initially (higher that min connections). This allows for a smoother deployment, by effectively having initially more connections than min in order to immediately take production load, and then over time trim back down towards the min connections.

So in k8s I am setting min, initial and max connections, where initial connections is high enough to take full production load straight after readiness true.
2025-07-11 21:26:58 +12:00
Rob Bygrave 2e9c5d8548 Merge branch 'query-cache-oom-for-too-large-beans' 2025-07-11 21:19:21 +12:00
Rob Bygrave 93edc840b3 Add a test that hits the new branch of code 2025-07-11 21:18:00 +12:00
34311785fa Fix Jackson NCDF Error (#3639)
* fix jackson NCDF error

split jackson SPI impl into it's own module

* Restore format

* Restore format

* Trim up dependencies

* Rename module to ebean-core-json

---------

Co-authored-by: Rob Bygrave <robin.bygrave@gmail.com>
2025-07-11 20:53:25 +12:00
Rob Bygrave 63929f8ff3 Bump test Yugabyte version to 2.20.11.0-b34 2025-07-11 20:26:12 +12:00
Jonas Fröhler d918c5117f no import changes 2025-07-01 09:05:48 +02:00
Jonas Fröhler dd845a7b0c Fix imports 2025-07-01 09:02:26 +02:00
Jonas Fröhler df0e4d57f0 Clean up 2025-06-27 12:17:19 +02:00
Jonas Fröhler 9c7fa25d49 Query Cache OOM test and potential draft for the fix 2025-06-27 12:14:01 +02:00
Rob Bygrave e82c1a4140 Version 16.0.0-rc3 2025-05-26 21:00:32 +12:00
Rob BygraveandGitHub 389bf48e3e Merge pull request #3636 from ebean-orm/feature/explicit-shutdownHook
Add DatabaseBuilder.shutdownHook option (programmatic disabling registration of JVM shutdown hook)
2025-05-26 17:24:25 +12:00
Rob Bygrave 3b3b44543e Bump ebean-test-containers, programmatically get DatabaseBuilder from test container 2025-05-26 17:23:27 +12:00
Rob Bygrave 297f334da5 Add DatabaseBuilder.shutdownHook option (programmatic disabling registration of JVM shutdown hook) 2025-05-26 17:21:15 +12:00
Rob Bygrave 78c7439445 test only - rename TestRawExpressionInterpolation 2025-05-15 08:00:52 +12:00
Rob BygraveandGitHub 2043ba6411 Merge pull request #3634 from ebean-orm/feature/native-image-otherTypes
[native-image] Modify querybean-generator to include AttributeConverters in generated reflect-config.json
2025-05-14 20:49:52 +12:00
Rob Bygrave 437c58001b [native-image] Modify querybean-generator to include AttributeConverters in generated reflect-config.json 2025-05-14 20:48:07 +12:00
Rob Bygrave 0e812efa7e Merge branch 'master' of github.com:ebean-orm/ebean 2025-05-14 20:27:56 +12:00
Rob BygraveandGitHub 80d4d21986 Merge pull request #3632 from FOCONIS/reorg-args-placeholder
Db2: Reorg args placeholder
2025-05-06 20:44:00 +12:00
Noemi Praml fe66b8c242 fix DbMigrationTest 2025-05-06 09:49:18 +02:00
Noemi Praml 206b2b2d3b migrations 2025-05-06 08:06:48 +02:00
Noemi Praml c0bc3faea0 fix test 2025-05-06 08:06:40 +02:00
Noemi Praml 3d07e7d804 add: reorgARgs Placeholder 2025-05-06 08:00:58 +02:00
Rob Bygrave fc124e8318 Tidy pom only 2025-04-30 00:02:30 +12:00
Rob Bygrave f4fd4f4b09 Version 16.0.0-RC2 2025-04-30 00:01:52 +12:00
Rob Bygrave 16f5311885 Bump parent pom to 5.1 for new maven central deploy 2025-04-29 23:41:48 +12:00
Rob BygraveandGitHub 75a0675977 Merge pull request #3630 from ebean-orm/feature/fix-ea-build-kotlin
Fix EA build, Kotlin not supporting 25-EA release
2025-04-29 23:37:10 +12:00
Rob Bygrave 80ebf4a1ee Fix EA build, Kotlin not supporting 25-EA release
It barfs trying to parse the 25-EA version, means the kotlin-querybean-generator fails the build for the Java Early Release versions.

With this, it will skip the kotlin modules for the Java Early Access release builds.
2025-04-29 23:36:22 +12:00
Rob BygraveandGitHub 4185beb5aa Merge pull request #3629 from ebean-orm/feature/bump-datasource-10
Bump ebean-datasource to 10.0 (Virtual Threads support via MR Jar)
2025-04-29 23:17:54 +12:00
Rob Bygrave 79908c0164 Bump ebean-datasource to 10.0 (Virtual Threads support via MR Jar)
Note that this still supports Java 11.

The 10.0 version of ebean-datasource uses Multi-Version jar such that if running using Java 21+ then it will use Virtual Threads for the background Heartbeat validation and also background closing of connections.
2025-04-29 23:09:49 +12:00
Rob Bygrave b5a16f42ca #3626 Add tests for bean property name instead of db column 2025-04-23 22:33:18 +12:00
Gonçalo Andrade a320a132b3 Fix incorrect usage of bean property name instead of corresponding column 2025-04-22 14:51:38 +01:00
Rob BygraveandGitHub 9e84e93511 Merge pull request #3621 from FOCONIS/new-db-versions
New db versions + testcontainers 7.8
2025-04-17 23:18:05 +12:00
Noemi Praml 6fb40c71ef update StartDb2 2025-04-16 15:22:08 +02:00
Noemi Praml 202b9ae94a update to testcontainers 7.8 2025-04-16 14:52:21 +02:00
Noemi Praml d79b452378 new db2 version 2025-04-16 14:19:11 +02:00
Noemi Praml 78a408dd10 new sqlserver version 2025-04-16 14:19:11 +02:00
Noemi Praml 6af974e432 new mariadb version 2025-04-16 14:19:11 +02:00
Rob BygraveandGitHub 04a8475291 Merge pull request #3623 from ebean-orm/feature/readOnly-DataSource-mark-nullable
Explicitly mark Database.readOnlyDataSource() as @Nullable
2025-04-15 22:25:06 +12:00
Rob Bygrave c56345f92e Explicitly mark Database.readOnlyDataSource() as @Nullable
Using JSpecify @Nullable on the return for Database.readOnlyDataSource()
2025-04-15 22:24:14 +12:00
Rob Bygrave ed0a46955e Explicitly mark Database.readOnlyDataSource() as @Nullable
Using JSpecify @Nullable on the return for Database.readOnlyDataSource()
2025-04-15 22:22:08 +12:00
Rob Bygrave 3c4b04a893 Version 16.0.0-rc1 2025-04-09 23:18:27 +12:00
Rob BygraveandGitHub ee403bdb83 Merge pull request #3620 from ebean-orm/feature/bump-ebean-agent
Bump the ebean-agent to 14.12.0, support for Lombok SuperBuilder
2025-04-09 23:02:46 +12:00
Rob Bygrave b18abe2221 Bump the ebean-agent to 14.12.0, support for Lombok SuperBuilder 2025-04-09 22:52:39 +12:00
Rob BygraveandGitHub d68f372d99 Merge pull request #3619 from ebean-orm/feature/column-length-255
For Postgres @Column(length=255) means varchar(255)
2025-04-09 20:22:56 +12:00
Rob Bygrave c8f769aa2a For Postgres @Column(length=255) means varchar(255)
The `@Column` length defaults to 0 rather than 255, this allows us to detect when it has been explicitly set and thus for Postgres we can now have:

@Column(length=255) mapping to -> varchar(255)
@Column mapping to -> varchar
2025-04-09 20:07:56 +12:00
Rob BygraveandGitHub bde626fd45 Merge pull request #3618 from ebean-orm/feature/bump-datasource-95
Bump ebean-datasource to 9.5
2025-04-09 20:04:23 +12:00
Rob Bygrave b828b73b2c Bump ebean-datasource to 9.5
When using DataSourceBuilder for both main and readOnly datasource, the maxConnections for the readOnly will default to the main pool maxConnections.
2025-04-09 20:02:14 +12:00
Rob BygraveandGitHub 2795a8578f Merge pull request #3616 from ebean-orm/feature/lazyLoadBatch-100
Increase default lazyLoadBatchSize from 10 to 100
2025-04-04 21:15:23 +13:00
Rob Bygrave bd0a3c2303 Increase default lazyLoadBatchSize from 10 to 100 2025-04-04 21:14:47 +13:00
Rob BygraveandGitHub 21e50e9d00 Merge pull request #3615 from ebean-orm/feature/3612-redis-exception
#3612 Catch all RedisException (rather than only IOException)
2025-04-04 20:47:44 +13:00
Rob Bygrave 88a47bf0a9 #3612 Catch all RedisException (rather than only IOException) 2025-04-04 20:45:59 +13:00
Rob Bygrave d9a45245f4 Version 16.0.0-beta1 2025-04-03 19:35:14 +13:00
Rob BygraveandGitHub 7be72df788 Merge pull request #3570 from ebean-orm/feature/improved-readOnly-immutable
Unmodifiable - Improved read only immutable entity beans / graphs
2025-04-02 22:24:19 +13:00
Rob Bygrave 42685335e3 Version 14.11.0 2025-04-01 21:32:48 +13:00
Rob BygraveandGitHub 478a2be405 Merge pull request #3611 from ebean-orm/feature/fix-native-image-mappedSuper
Fix NPE with native-image with @MappedSuperclass
2025-04-01 20:45:17 +13:00
Rob Bygrave ebcac9a503 Fix NPE with native-image with @MappedSuperclass
@MappedSuperclass was excluded from the generated reflect-config.json, this PR fixes that.

The missing reflect-config entry for MappedSuperclass means that with native-image the @Id property isn't found when its on a MappedSuperclass, and that ended up as a NPE in BeanPropertyAssocOne.
2025-04-01 20:29:26 +13:00
Rob BygraveandGitHub 996239c29f Merge pull request #3610 from ebean-orm/feature/configure-explain
Add support to configure EXPLAIN options for query plan capture
2025-04-01 08:07:46 +13:00
Rob Bygrave caf2772fb3 Put Postgres explain back to default format text for now 2025-04-01 08:07:04 +13:00
Rob Bygrave 1482c4c84f Add support to configure EXPLAIN options for query plan capture
e.g. DatabaseBuilder.queryPlanExplain("explain (verbose)")

Also changes Postgres default explain to be:
explain (analyze, costs, verbose, buffers, format json)
2025-03-31 23:41:16 +13:00
Rob BygraveandGitHub 792d52b794 Merge pull request #3609 from ebean-orm/feature/queryPlanInit
Change QueryPlanInit to support thresholdMicros per hash
2025-03-30 21:41:53 +13:00
Rob Bygrave aa4ea4904f Change QueryPlanInit to support thresholdMicros per hash
Effectively means that we can provide a thresholdMicros per query plan hash [for the plans that we want collected]
2025-03-30 21:35:20 +13:00
Rob Bygrave bab839fb38 Change QueryPlanInit to support thresholdMicros per hash
Effectively means that we can provide a thresholdMicros per query plan hash [for the plans that we want collected]
2025-03-30 18:33:13 +13:00
Rob BygraveandGitHub dde2567ccd Merge pull request #3608 from ebean-orm/feature/bump-postgres-16
Test only - align sqlserver test configuration
2025-03-26 22:50:48 +13:00
Rob Bygrave 7e4d070b75 Test only - update sqlserver test docker image to 2017-CU31-ubuntu-18.04 2025-03-26 22:50:22 +13:00
Rob Bygrave 3151e3f82b Test only - align sqlserver test configuration 2025-03-26 22:41:00 +13:00
Rob BygraveandGitHub c630aaff0e Merge pull request #3607 from ebean-orm/feature/bump-postgres-16
Test only - align mariadb test configuration
2025-03-26 22:37:34 +13:00
Rob Bygrave 67ec848f15 Test only - align mariadb test configuration 2025-03-26 22:37:09 +13:00
Rob Bygrave 57f0734381 Test only - align mariadb test configuration 2025-03-26 22:32:18 +13:00
Rob BygraveandGitHub cbd5bf23c9 Merge pull request #3606 from ebean-orm/feature/bump-postgres-16
Test only - align mysql and db2 test configuration
2025-03-26 22:31:51 +13:00
Rob Bygrave 5dc664a63f Test only - align mysql and db2 test configuration 2025-03-26 22:27:35 +13:00
Rob BygraveandGitHub d9b53677f2 Merge pull request #3605 from ebean-orm/feature/bump-postgres-16
Test only - add logging for datasource to BaseTestCase
2025-03-26 22:17:56 +13:00
Rob Bygrave f55c2cf3b6 Test only - add logging for datasource to BaseTestCase 2025-03-26 22:14:24 +13:00
Rob BygraveandGitHub c98def7ab7 Merge pull request #3604 from ebean-orm/feature/bump-postgres-16
Test only - add logging for datasource to BaseTestCase
2025-03-26 22:06:58 +13:00
Rob Bygrave 705e158a70 Test only - add logging for datasource to BaseTestCase 2025-03-26 22:06:35 +13:00
Rob BygraveandGitHub 569e782e99 Merge pull request #3603 from ebean-orm/feature/bump-postgres-16
Update Postgres and Postgis test containers to default to 16
2025-03-26 22:05:59 +13:00
Rob Bygrave 265b92fb12 Update Postgres and Postgis test containers to default to 16 2025-03-26 21:43:08 +13:00
Rob Bygrave 74311fad0a Update test postgres docker image to 16 2025-03-26 21:34:31 +13:00
Rob BygraveandGitHub 1eded5682a Merge pull request #3599 from ebean-orm/feature/bump-datasource-dependency2
Bump ebean-datasource dependency to 9.3
2025-03-21 18:42:53 +13:00
Rob Bygrave ff21bfe1de Bump ebean-datasource dependency to 9.3 2025-03-21 00:35:41 +13:00
Rob BygraveandGitHub 86db7fadfd Merge pull request #3598 from ebean-orm/feature/tidy-QueryCacheEntry
Tidy QueryCacheEntry, final class and use accessors
2025-03-20 23:58:56 +13:00
Rob Bygrave e48b327967 Tidy QueryCacheEntry, final class and use accessors 2025-03-20 23:57:56 +13:00
Rob BygraveandGitHub 964b3ccf8e Merge pull request #3597 from ebean-orm/feature/3515-extend
#3515 Bug in QueryCache invalidation
2025-03-20 23:55:10 +13:00
Rob Bygrave eb6906ad2b #3515 Bug in QueryCache invalidation
Effectively the bug fix is in SqlTreeNodeRoot.dependentTables() to include the baseTable in the set of dependent tables
2025-03-20 23:47:21 +13:00
Rob BygraveandGitHub 86e5ea3627 Merge pull request #3596 from ebean-orm/feature/tidy-future-queries
Change findFuture queries such that they can use the read only DataSource
2025-03-19 23:06:38 +13:00
Rob Bygrave 3a5e8290e0 Change findFuture queries such that they can use the read only DataSource
Prior to this change they made an explicit transaction if one was needed, and this would always use the Main DataSource.

With this change, when there is no transaction assigned to the query and no active transaction, then the find future query will use the ReadOnly DataSource if it has been configured (e.g. ReadOnly DataSource might point to a read replica database instance).
2025-03-19 23:00:19 +13:00
Rob BygraveandGitHub 929604e33d Merge pull request #3593 from LeComptoirDesPharmacies/feature/findFutureMap
Add feature findFutureMap
2025-03-19 22:12:06 +13:00
Rob BygraveandGitHub 2eed68ad61 Merge pull request #3595 from ebean-orm/feature/bump-avaje-config2
Bump avaje-config dependency to 4.0
2025-03-19 20:57:13 +13:00
Rob Bygrave f705560b8b Bump avaje-config dependency to 4.0 2025-03-19 20:56:40 +13:00
Rob Bygrave 6d791c7b50 Add BeanAccessException extends UnsupportedOperationException
And:

LazyInitialisationException extends BeanAccessException ...
UnmodifiableEntityException extends BeanAccessException ...
2025-03-18 22:54:34 +13:00
Rob BygraveandGitHub 1afe42f4c6 Merge branch 'master' into feature/improved-readOnly-immutable 2025-03-18 22:43:00 +13:00
Rob BygraveandGitHub 4e7f3c13a0 Merge pull request #3592 from ebean-orm/feature/improved-readOnly-immutable-part2
Remove readOnly, migrate to unmodifiable (or use normal mutable)
2025-03-18 22:41:12 +13:00
Thomas a35db6bdee Add feature findFutureMap 2025-03-18 09:19:15 +01:00
Rob Bygrave d7366dec0f Tidy readOnly removal 2025-03-18 20:59:04 +13:00
Rob Bygrave ceee1d7489 Remove readOnly from Query 2025-03-18 20:49:26 +13:00
Rob Bygrave 1b23319fa4 Remove readOnly from EntityBeanIntercept and BeanCollection 2025-03-18 20:32:22 +13:00
Rob Bygrave 6f726973ea Remove most internal use of readOnly 2025-03-18 19:53:13 +13:00
Rob Bygrave 82284b19d5 Bean cache sharable instances as unmodifiable + bean cache queries can also be unmodifiable
Entities without *any* relationships can support "sharable instances" with bean caching. This change restores that and uses unmodifiable instances (rather than the old ReadOnly).

Currently, for a query to get shared instances it now needs to explicitly use setUnmodifiable(true) where as before it defaulted to shared instances so that is a behaviour change.

Additionally, bean cache queries were not honouring setUnmodifiable(true) and with these changes they now do.
2025-03-16 23:19:54 +13:00
Rob Bygrave 798d01abd1 LazyInitialisationException, plus javadoc 2025-03-16 21:12:25 +13:00
Rob Bygrave 5136a5a708 Support unmodifiable Embedded and EmbeddedId 2025-03-13 22:52:45 +13:00
Rob Bygrave fa25d7cc8a Using Query Cache now implies unmodifiable
- Query Cache now holds unmodifiable collections
- Can no longer have readOnly=false with queryCache=true
- Reference beans now also honor unmodifiable
- Effectively no longer does bean cache lookup for reference beans (which it defaulted to when cacheSharableBeans true, e.g. Country entity bean)
2025-03-11 23:50:34 +13:00
Rob Bygrave c13e09257c Version 14.10.0 2025-03-11 21:26:00 +13:00
Rob BygraveandGitHub ed65433640 Merge pull request #3574 from ebean-orm/feature/3459-postgres-varchar
#3459 Postgres varchar default to no length (aka text)
2025-03-11 20:01:26 +13:00
Rob BygraveandGitHub 08890e9d5a Merge pull request #3590 from ebean-orm/feature/3580-lookwriter-logWarn
Adjust LookupWriter to log at WARN rather than ERROR due to Quarkus dev mode
2025-03-10 23:56:19 +13:00
Rob Bygrave 4273c4af6a Adjust LookupWriter to log at WARN rather than ERROR due to Quarkus dev mode
Die to Quarkus dev mode (#3541 #3582) we want to log FilerException at WARN level rather than ERROR. This is because Quarkus dev mode will invoke the annotation processor more than usual, so we expect to fail with the FilerException.
2025-03-10 23:42:38 +13:00
Rob BygraveandGitHub 51424d9eea Merge pull request #3580 from SentryMan/feature/lookup-generation
[querybean-generator] Generate lookup for modules
2025-03-10 23:31:35 +13:00
Rob BygraveandGitHub cf2ab33903 Merge pull request #3589 from ebean-orm/feature/bump-ebean-agent-dependency
Bump ebean-agent to 14.10.0
2025-03-10 23:28:05 +13:00
Rob Bygrave 90d8b4fb04 Bump ebean-agent to 14.10.0 2025-03-10 23:27:02 +13:00
Rob BygraveandGitHub ff4eeff264 Merge pull request #3588 from ebean-orm/feature/3586-querybean-gen
[query bean generation] #3586 public constructor for Embedded bean
2025-03-10 08:02:03 +13:00
Rob Bygrave 64ba343e35 [query bean generation] #3586 public constructor for Embedded bean 2025-03-10 07:59:33 +13:00
Rob BygraveandGitHub af3c59c0fd Merge pull request #3587 from ebean-orm/feature/bump-test-containers-77
Bump ebean-test-containers dependency - improved SQL Server handling
2025-03-10 07:40:31 +13:00
Rob Bygrave ae55d28026 Bump ebean-test-containers dependency - improved SQL Server handling
Improvments around collation changes that end up making SQL Server startup flaky
2025-03-10 07:40:02 +13:00
Rob BygraveandGitHub ddffc8eee2 Merge pull request #3581 from apflieger/#3573-initfields-prevent-secondary-query
OneToMany initialisation via List.of() - was Tests only - new test on multiple many joins
2025-03-10 07:30:40 +13:00
Rob Bygrave 7f1a3a46cf #3581 ebean-agent 14.10.0 handling for OneToMany initialisation 2025-03-10 07:12:20 +13:00
Rob BygraveandGitHub a59f75a468 Merge pull request #3585 from nedge/feature/Create_test_entities
Simple Test Entities in preparation for type scoped loading
2025-03-05 08:06:39 +13:00
Eddie Mc Greal 6f1c66ecd6 Simple Test Entities in preparation for type scoped loading 2025-03-04 14:17:08 +01:00
Rob Bygrave 25f6fb6d6f test only - Almost fix the model for test_manyNonRoot_RootHasNoMany
The test was using field access??? when that isn't valid unless we specifically turn on enhancement to support that.

Using proper method access though stops the test from failing.
2025-03-03 21:42:15 +13:00
Rob Bygrave 852def8536 test only - use assertThat hasSize instead of assertEquals for test_manyNonRoot_RootHasNoMany 2025-03-03 21:34:22 +13:00
Rob BygraveandGitHub dfb29fd75f Merge pull request #3578 from mkurz/fix_3577
Work around `mysqldump` bug by moving comment one line up
2025-03-03 21:26:40 +13:00
Rob BygraveandGitHub 80c3501197 Merge pull request #3583 from ebean-orm/feature/revert-3541-3582
[querybean-generator] #3582 - Revert #3541 "FilerException trying to write EntityClassRegister with Quarkus dev mode / hot reload "
2025-03-03 21:25:39 +13:00
Rob BygraveandGitHub b4ff5748fc Merge pull request #3579 from FOCONIS/rollbac-or-commit-before-close
Rollback/Commit raw connections before close
2025-03-03 21:25:12 +13:00
Rob Bygrave 64f01f0543 [querybean-generator] #3582 - Revert #3541 "FilerException trying to write EntityClassRegister with Quarkus dev mode / hot reload "
This reverts commit 69c25309 and applies the required "Fix" in the initModuleInfoBean() method to catch FilerException and log it at WARN level
2025-03-03 20:49:19 +13:00
Arnaud Pflieger fee6e0f480 Tests only - new test on multiple many joins
This test reproduce the problem of #3573
The field initialization `= List.of();` prevents eager secondary query.
2025-02-28 12:20:18 +01:00
Josiah Noel 50b44c4529 Update LookupWriter.java 2025-02-28 00:29:03 -05:00
Josiah Noel f0c2ba0e28 [Feature] Generate lookup for modules
Generate Lookup Class for modular projects
2025-02-27 20:47:16 -05:00
Roland Praml 7643dc9b22 Rollback/Commit raw transactions before close 2025-02-27 10:56:41 +01:00
Matthias Kurz c49a1b3d71 Work around mysqldump bug by moving comment one line up
It seems like mysqldump just adds ;; to the last line and does not
check if that line is a comment. To work around that it's good enough
to move the comment one line up - as long as the END does not end with ;
(which here it does not so that is ok)
2025-02-26 15:36:20 +01:00
Rob BygraveandGitHub 11e783938c Merge pull request #3576 from ebean-orm/feature/bump-ebean-test-containers
#3511 bump ebean-test-containers dependency
2025-02-26 23:18:43 +13:00
Rob Bygrave 3845861e24 test only - Fix tests due to automatic inline comment included in generated sql like:
select /* TestQueryDefaultBatchSize.test_findEach_details__lazy */ t0.order_id, t0.id,

select /* TestQueryDefaultBatchSize.test_findEach_details__lazy */ t0.order_id
2025-02-26 23:15:51 +13:00
Rob Bygrave d04181865c test only - update TestOrderByWithMany which is flaky 2025-02-26 23:10:55 +13:00
Rob Bygrave 00d7db31d6 test only - update TestQueryFindIterate which is flaky 2025-02-26 23:07:53 +13:00
Rob Bygrave 6880b5673a #3511 bump ebean-test-containers dependency
ebean-test-containers version 7.6 supports extraDb for MySql and MariaDb, resolving #3511 with extraDb configuration for each extra schema/database required with MySql or MariaDb.
2025-02-26 22:24:05 +13:00
Rob BygraveandGitHub e18b59a9dd Remove deprecated ExtendedServer.setClock() migrate to DatabaseBuilder.clock() (#3566)
So we can no longer dynamically change the Clock being used and instead for testing purposes need to create the Database with a test clock instance as needed.

Refer to the ExtendedServerTest for an example
2025-02-26 22:16:12 +13:00
Rob BygraveandGitHub cc48dced09 #3572 DDL support for non-nullable JoinColumn column (#3575) 2025-02-26 21:13:50 +13:00
Rob Bygrave b13bdc95be #3459 Postgres varchar default to no length (aka text)
Change Postgres platform to default a String to varchar [with no length defined] rather than varchar(255)
2025-02-26 18:53:08 +13:00
Rob Bygrave 0a5c3ced21 Test only - update TestQueryMultiManyOrder sql asserts
No effective change.
2025-02-26 00:59:57 +13:00
Rob Bygrave 8ff5f7f72a Recursive freeze on entity beans
Noting that the freeze needs to occur after secondary queries have executed
2025-02-26 00:00:07 +13:00
Rob Bygrave 71944bb8fa Rename flags -> loaded, add message with property name to UnmodifiableEntityException 2025-02-23 22:25:46 +13:00
Rob Bygrave 24888fc01e Change InterceptReadWrite to use UnmodifiableEntityException
Add unmodified to DefaultOrmQuery query plan description
Fix incorrect merge conflict
2025-02-21 22:24:48 +13:00
Rob BygraveandGitHub 645d5bb613 Merge branch 'master' into feature/improved-readOnly-immutable 2025-02-21 22:08:38 +13:00
Rob Bygrave 4a6f1a39e0 Add UnloadedPropertyException and UnmodifiableEntityException, change existing use of IllegalStateException
- Adds new exceptions UnloadedPropertyException and UnmodifiableEntityException
- Change InterceptReadOnly to use these exception instead of IllegalStateException
- Change collections BeanSet, BeanList, BeanMap from using IllegalStateException to UnsupportedOperationException [to bring these in line with JDK unmodifiable collections]
2025-02-21 22:05:49 +13:00
Rob BygraveandGitHub 40637bd68c Allow OneToOne to map to ManyToOne (#3569) 2025-02-19 20:00:15 +13:00
8dd438be61 #3564 Fix for nested transaction with batch-mode does not flush (#3565)
* ADD: Testcase for showing nested transaction with batch-mode not flushing batch on commit

* Update test only - TestNestedTransaction.test_txn_nestedWithInnerBatch()

Update the test to show that we desire the nested transaction changes to be "visible" after a commit regardless of flushOnQuery etc

* #3564 Fix for nested transaction with batch-mode does not flush

- Adds flush() into ScopeTrans.commitTransaction()
- Related fixes in DefaultServer execute() and executeCall() where it was performing extra unnecessary nesting on PersistenceException

* Touch

---------

Co-authored-by: Jonas Pöhler <jonas.poehler@foconis.de>
2025-02-18 07:33:48 +13:00
Rob Bygrave 5e1ad29c5d Build - add workflow_dispatch trigger to main build 2025-02-17 07:46:20 +13:00
Rob Bygrave 9eeb137907 Tests only - update test-kotlin dependency 2025-02-17 07:33:56 +13:00
Rob Bygrave 578a041c9e Version 14.9.0 2025-02-12 19:56:14 +13:00
Rob Bygrave b0b2a0d320 Bump ebean-agent to 14.9.0 with module path support for @Transactional 2025-02-12 19:36:48 +13:00
de81dfc067 Feature: Add a MethodHandles.Lookup SPI (#3535)
* ServiceLoad lookups

* remove more reflection

* address comments

* Update DefaultTypeManager.java

* Javadoc and format changes

---------

Co-authored-by: Rob Bygrave <robin.bygrave@gmail.com>
2025-02-12 19:30:05 +13:00
Rob BygraveandGitHub 2bd53cb52b Merge pull request #3560 from ebean-orm/feature/3533-aop-transactional
#3533 Support @Transactional on module path
2025-02-12 18:53:57 +13:00
Rob BygraveandGitHub a6d792de64 Merge pull request #3563 from ebean-orm/feature/remove-deprecated-queryOrder
Remove deprecated order() migrate to orderBy()
2025-02-12 18:52:53 +13:00
Rob BygraveandGitHub c73d83ef33 Merge pull request #3562 from ebean-orm/feature/remove-deprecated-queryUpdTxn
Remove deprecated query.update(txn) & query.delete(txn)
2025-02-12 18:52:18 +13:00
Rob Bygrave 9f1b4ba758 Remove deprecated order() migrate to orderBy() 2025-02-12 18:47:16 +13:00
Rob BygraveandGitHub 1f7117da25 Merge pull request #3561 from ebean-orm/feature/remove-deprecated-servletContextListener
Remove deprecated ServletContextListener
2025-02-12 18:43:55 +13:00
Rob Bygrave f0ceab43bf Remove deprecated query.update(txn) & query.delete(txn)
Migrate to query.usingTransaction(txn)
2025-02-12 18:42:23 +13:00
Rob Bygrave 1107e4ea4c Remove deprecated ServletContextListener 2025-02-12 18:38:17 +13:00
Rob BygraveandGitHub 4dd8a5dfea Merge pull request #3558 from ebean-orm/feature/3557-filterMany-removal
#3557 [Query beans] Remove deprecated filterMany(String expressions, Object... params) from generated query beans
2025-02-12 18:01:39 +13:00
Rob BygraveandGitHub 195edf0355 Merge pull request #3514 from ebean-orm/feature/querybean-txn-ctor
Remove deprecated QueryBean constructor that takes transaction, migrate to query.usingTransaction()
2025-02-12 18:01:03 +13:00
Rob BygraveandGitHub e9c438adab Merge branch 'master' into feature/querybean-txn-ctor 2025-02-12 15:05:57 +13:00
Rob Bygrave e45cf5fab9 #3533 Bump ebean-agent to use the new AOPTransactionScope 2025-02-12 00:27:07 +13:00
Rob BygraveandGitHub 1bf9d1dd4f Merge pull request #3559 from ebean-orm/feature/findCount-noId
FindCount on entity bean without @Id + platform wants column alias
2025-02-12 00:01:24 +13:00
Rob Bygrave 657920c4a2 #3533 Support @Transactional on module path
As HelpScopeTrans isn't in an exported package it's use fails with an error in module path. This adds AOPTransactionScope in the exported package io.ebean.plugin and moves the required methods from SpiEbeanServer to SpiServer to support this move.

This also requires an associate change in ebean-agent to support this feature which will be in ebean-agent 14.9.0.
2025-02-11 23:57:18 +13:00
Rob Bygrave 6c47107436 FindCount on entity bean without @Id + platform wants column alias
Internally in CQueryBuilder only use query.setSelectId(); for findCount when the entity bean has a @Id property [which it doesn't strictly need and likely won't have for view based entities]
2025-02-11 23:04:02 +13:00
Rob Bygrave 88cf4e001a #3557 [Query beans] Remove deprecated filterMany(String expressions, Object... params) from generated query beans, migrate to filterManyRaw() 2025-02-11 22:06:20 +13:00
Rob BygraveandGitHub 7f1fcbcf92 Merge pull request #3556 from ebean-orm/feature/test-containers-bump
Bump ebean-test-containers to 7.5
2025-02-10 21:55:18 +13:00
Rob Bygrave 95d5d5e467 Bump ebean-test-containers to 7.5 2025-02-10 21:54:54 +13:00
Rob BygraveandGitHub 2dde23d577 Merge pull request #3555 from ebean-orm/feature/3503-kotlin-querybean-gen-DbMap
#3503 - Fix kotlin-querybean-generator for use of @DbMap
2025-02-10 14:01:09 +13:00
Rob Bygrave 1ec26d13f9 #3503 - Fix kotlin-querybean-generator for use of @DbMap 2025-02-10 11:35:44 +13:00
Rob Bygrave bb1b55e897 Reduce frequency of running yugabyte CI test 2025-02-09 22:45:10 +13:00
Rob Bygrave fb07447df4 Fix test only - test-kotlin bump kotlin-querybean-generator version 2025-02-09 22:43:02 +13:00
Rob Bygrave ad18b6573c Version 14.8.2 2025-02-09 22:07:28 +13:00
Rob BygraveandGitHub 11632c3a6e Merge pull request #3554 from ebean-orm/feature/3536-kotlin-querybean-generator
#3536 kotlin-querybean-generator update for filterMany() changes
2025-02-09 21:37:38 +13:00
Rob Bygrave b066f9c072 #3536 kotlin-querybean-generator update for filterMany() changes
Brings the kotlin-querybean-generator up to date with the [java] querybean-generator in terms of how it has specific "associated beans" for ToOne and ToMany type relationships
2025-02-09 21:24:51 +13:00
Rob Bygrave 1e38ed9efc Test only, add Embedded bean as an inner class for querybean-generation 2025-02-09 21:19:39 +13:00
Roland PramlandGitHub 2d48dd2fef Pass create/configOptions to DB2 test container (#3550)
This allows to pass collation/pagesize settings via the
`ebean.test.createOptions=` property to the container
2025-02-08 19:47:20 +13:00
Rob BygraveandGitHub 60aa899a34 #3552 Column alias required for SQL Server + findCount + distinct (#3553)
* #3552 Column alias required for SQL Server + findCount + distinct

- Modifies CQueryBuilder with the main fix which is to use the database platform selectCountWithColumnAlias for all distinct queries [and later disable it for single column case]

- Modifies SqlTreeBuilder because we need to NOT use the column alias for the count distinct SINGLE COLUMN case. So change here to:
  - build the root SqlTreeNode first as part of constructor
  - use rootNode.isSingleProperty() to NOT use column alias for the single column case
  - Hence need to initialise DefaultDbSqlContext AFTER the root SqlTreeNode

  - Modifies DefaultDbSqlContext with no effective change, just columnIndex++ ONLY when we are actually using column alias

 - Modifies H2Platform to also use selectCountWithColumnAlias true

* #3552 selectCountWithColumnAlias true for MariaDB and MySql

Plus fix TestRowCount for Oracle platform
2025-02-08 19:33:03 +13:00
Rob BygraveandGitHub c38c75fdec Merge pull request #3549 from ebean-orm/feature/3546
#3546 Reduce compiler warning on query bean generated code
2025-01-28 23:34:23 +13:00
Rob Bygrave cf275f4edd #3546 Reduce compiler warning on query bean generated code
This method is effectively internal and called by generated code that also is Deprecated(forRemoval = true)
2025-01-28 23:31:23 +13:00
Rob Bygrave 121f4afed8 #3545 Support @SQL entity with a OneToOne with EmbeddedId
- @Sql entity
- Has a OneToOne or ManyToOne to a bean that uses @EmbeddedId
2025-01-28 23:26:09 +13:00
Rob Bygrave c8621c3a29 Put back the querybean-generator version 2025-01-16 21:42:02 +13:00
Rob BygraveandGitHub f83da15d5e Merge pull request #3542 from ebean-orm/feature/3542-quarkus
[querybean-generator] FilerException trying to write EntityClassRegister with Quarkus dev mode / hot reload #3541
2025-01-16 16:46:46 +13:00
Rob Bygrave 52729d9802 Missing import and adjust warning message 2025-01-16 16:40:43 +13:00
Rob Bygrave 69c25309da [querybean-generator] FilerException trying to write EntityClassRegister with Quarkus dev mode / hot reload #3541
Drop to log at WARN level when we catch FilerException such that Quarkus dev mode / hot reload works
2025-01-16 16:31:52 +13:00
Rob Bygrave 723a12fd66 #3538 Restoring batchMode etc with nested transaction scopes
This change is a simplification such that these batch attributes are always stored and restored for nested ScopeTrans.

There are no expensive side effects of doing it this way.

This fixes issues where the batch attributes are changed after the ScopeTrans is created (like the test for this PR).
2025-01-16 08:15:22 +13:00
Noemi Praml 5cf74f1ee9 Add: failing Unittest 2025-01-08 14:43:49 +01:00
Rob Bygrave 2c18b4fe97 Version 14.8.1 2024-12-20 15:34:07 +13:00
Rob Bygrave 9c9fb70999 Bump ebean agent to align 2024-12-20 15:24:08 +13:00
Rob BygraveandGitHub 18e6374a60 Merge pull request #3532 from ebean-orm/feature/sql-play-ebean
#3408 play-ebean inline sql comment in test generated scripts
2024-12-20 14:59:54 +13:00
Rob Bygrave 3fea5ce93d #3408 play-ebean inline sql comment in test generated scripts 2024-12-20 14:58:10 +13:00
Rob BygraveandGitHub 43675468ae Merge pull request #3523 from FOCONIS/streaming-tests
set defaultFetchBuffer in findEach/findList in SQL and DTO Queries
2024-12-19 11:04:01 +13:00
Rob BygraveandGitHub 1c038f4629 Merge pull request #3408 from mkurz/meta_datastored-procedures-DDL
Add metadata to stored procedures for 3rd party libs
2024-12-19 10:47:14 +13:00
Rob BygraveandGitHub 49b6f3dec9 Merge pull request #3530 from SentryMan/fix/dto-lookup
FIX: IllegalAccessError on modular DTO queries
2024-12-19 09:07:45 +13:00
Josiah Noel 346e30217a Merge remote-tracking branch 'upstream/master' into fix/dto-lookup 2024-12-18 14:56:15 -05:00
Rob Bygrave 5dc165debf Fix test TestLazyJoin2 2024-12-19 08:42:37 +13:00
Josiah Noel d5cb7c3ff1 fix illegal access error on modular dtos
When using a dto query on a JPMS application, I get an IllegalAccessError even though I export and open my package.
2024-12-18 00:20:08 -05:00
Roland Praml 4d08dce033 set defaultFetchBuffer in findEach/findList in relational/orm Queries 2024-11-27 17:05:15 +01:00
Roland Praml beef4407e3 Add failing testcase 2024-11-27 17:02:15 +01:00
Matthias Kurz e99f922de6 Add metadata to stored procedures for 3rd party libs
This way a third party can parse the meta data and knows how
to handle the bodies of a stored procedure
2024-11-26 23:36:30 +01:00
Rob Bygrave 1fef4f7c11 Add explicit query.setUnmodifiable(true) [for readOnly=true + disableLazyLoad=true]
Although this is ok, makes me think that another option is just to have query.setReadOnly(true)
to mean ... readOnly + disableLazyLoad + error reading unloaded property or collection. As in,
readOnly true without these extra things does not that good [as in the existing readOnly does
not seem very good/safe/useful to use].
2024-11-20 23:01:59 +13:00
Rob BygraveandGitHub 103e8323f2 Merge pull request #3519 from FOCONIS/no-codechange-test-cleanup
No productive code change: cleanup basic test data
2024-11-07 21:32:35 +13:00
Noemi Praml 59ed0bb015 fix delete contacts 2024-11-05 14:04:32 +01:00
Noemi PramlandNoemi Praml c0eb896e1f No productive code change: cleanup basic test data (#114)
* Erste Tests bereinigt

* fix

* noch mehr Tests bereinigt

* modify output

* reformat
2024-11-05 13:16:47 +01:00
Noemi Praml 3ab3f81fa3 Add failing concurrent test 2024-10-31 08:21:37 +01:00
Rob Bygrave ddb4b9d3e5 Remove deprecated QueryBean constructor that takes transaction, migrate to query.usingTransaction()
Remove the constructor for QueryBean that takes transaction. Migrate code to use query.usingTransaction() instead.
2024-10-31 18:22:43 +13:00
Rob Bygrave 7035b4c74c tests only: Update versions in test / test-kotlin maven plugin and apt 2024-10-31 18:19:36 +13:00
Rob BygraveandGitHub 85a575e353 Merge pull request #3513 from ebean-orm/feature/bump-parent-javadoc
Bump java11-oss parent and tidy javadoc
2024-10-31 17:14:52 +13:00
robin.bygrave eb05be286c Bump java11-oss parent and tidy javadoc 2024-10-31 14:55:43 +13:00
Rob BygraveandGitHub 9f5a77fdaa Merge pull request #3509 from FOCONIS/javadoc-fixes
RFC: Fix some javadoc issues
2024-10-31 14:47:46 +13:00
Roland Praml 42ee75f212 RFC: Fix some javadoc issues 2024-10-25 08:46:34 +02:00
Rob Bygrave 4610dbb26e Version 14.8.0 2024-10-25 14:28:58 +13:00
Rob BygraveandGitHub b26382f99c Merge pull request #3507 from ebean-orm/feature/agent-1480
Bump ebean-agent to 14.8.0
2024-10-25 14:18:20 +13:00
Rob Bygrave 2fba89f846 Bump ebean-agent to 14.8.0
This ebean agent is required to support the fluid QueryBuilder API change.
2024-10-25 14:17:46 +13:00
Rob Bygrave e4f13da868 Merge branch 'dynamic-property-group-by' 2024-10-24 16:13:01 +13:00
Rob Bygrave 32cd081fce #3504 Tidy test only and final method 2024-10-24 16:12:45 +13:00
Rob Bygrave e6f92eaceb ReadOnly Immutable query WIP 2024-10-24 16:02:50 +13:00
Rob Bygrave f6da332998 Add test for TestReflectiveModificationUpdate 2024-10-24 08:37:02 +13:00
Alexander Wagner d8f321d87b Fix: dynamic property group by with alias 2024-10-22 13:24:12 +02:00
Rob Bygrave c868d8a23b Fix test for Postgres TestDistinctOnQuery 2024-10-22 19:00:52 +13:00
Rob Bygrave d77c14d866 Fix test for Postgres TestDistinctOnQuery 2024-10-22 08:14:01 +13:00
Rob BygraveandGitHub 423d906848 Merge pull request #3499 from ebean-orm/feature/3489
Potentially breaking change: Throw PersistenceException for unknown property in select clause
2024-10-18 19:25:46 +13:00
Rob Bygrave 100d33cc94 Potentially breaking change: Throw PersistenceException for unknown property in select clause 2024-10-18 19:12:53 +13:00
Rob BygraveandGitHub 20cf6a9c00 Merge pull request #3498 from ebean-orm/feature/migrate-avaje-lang-to-jspecify
Migrate to JSpecify NullMarked/Nullable from avaje.lang NonNullApi/Nullable
2024-10-18 16:56:19 +13:00
Rob BygraveandGitHub e2c12268f7 Merge branch 'master' into feature/migrate-avaje-lang-to-jspecify 2024-10-18 16:52:53 +13:00
Rob BygraveandGitHub 937f6296e1 Merge pull request #3497 from ebean-orm/feature/fluid-self-querybuilder
Fix SELF of QueryBuilder, QueryBean, IQueryBean for fluid use
2024-10-18 16:48:26 +13:00
Rob Bygrave 24749567d2 Migrate to JSpecify NullMarked/Nullable from avaje.lang NonNullApi/Nullable 2024-10-18 16:46:41 +13:00
Rob Bygrave 7045240778 Merge branch 'transaction-readonly' 2024-10-18 16:27:18 +13:00
Rob Bygrave 6ceea85b94 Move markNotQueryOnly() into init transaction methods of PersistRequest 2024-10-18 16:26:49 +13:00
Rob Bygrave e04ac50800 Fix SELF of QueryBuilder, QueryBean, IQueryBean for fluid use
Currently, the SELF response type of QueryBuilder returns as Object when really we want it to return the SELF generic type of QueryBuilder, QueryBean, IQueryBean etc

Note that this change requires an updated ebean-agent
2024-10-18 16:18:39 +13:00
Noemi Praml a452fc0e21 call request.markNotQueryOnly 2024-10-17 16:30:42 +02:00
Noemi Praml 4438d5db7d Fixes in DefaultPersister 2024-10-17 16:19:19 +02:00
Noemi Praml 9ca6fa31e5 more tests 2024-10-17 16:19:03 +02:00
Rob BygraveandGitHub e0a00bea34 Merge pull request #3496 from mumbler6/fix-flaky
fixed flaky test in ToStringBuilderTest.java
2024-10-17 21:36:15 +13:00
mumbler6 b24b549298 fixed flaky test in ToStringBuilderTest.java 2024-10-15 22:41:51 -05:00
Rob Bygrave 51d0f4efcc Fix test TestOrderedList for Postgres ANY 2024-10-15 22:14:45 +13:00
Noemi Praml e08985d7c5 suggested solution 2024-10-14 16:53:48 +02:00
Noemi Praml 4f984ff2d4 add: failing test 2024-10-14 16:53:00 +02:00
Rob Bygrave b6843c6db0 Version 14.7.0 2024-10-10 23:48:29 +13:00
Rob Bygrave 57782c05b5 Update ebean-agent to 14.7.0 (Updates to ASM 9.7.1) 2024-10-10 23:46:37 +13:00
Rob BygraveandGitHub a2ee8b61f8 Merge pull request #3487 from FOCONIS/batch-ordering-bug
Bug: Batch ordering - Regression introduced in version 13.26.1, insertAll() leaves batchMode=true enabled ... when it should not
2024-10-10 22:31:15 +13:00
Rob BygraveandGitHub 1225a2776f Merge pull request #3485 from FOCONIS/ordercolumn-cache-queries
Fix orderBy for cached many requests
2024-10-10 22:30:23 +13:00
Rob BygraveandGitHub a499c8c26a Merge pull request #3493 from ebean-orm/feature/3490
#3490 filterMany generates invalid sql when the many side uses @EmbeddedId to model composite primary key
2024-10-10 22:27:58 +13:00
Rob Bygrave 8e627c756f #3490 filterMany generates invalid sql when the many side uses @EmbeddedId to model composite primary key 2024-10-10 22:24:24 +13:00
Rob Bygrave 45cc78bb0a #3490 filterMany generates invalid sql when the many side uses @EmbeddedId to model composite primary key 2024-10-10 22:11:20 +13:00
Rob Bygrave 38a8e95b36 #3491 Update javadocs and SqlQuery Postgres ANY tests 2024-10-10 20:08:03 +13:00
Rob BygraveandGitHub bca381104b Merge pull request #3491 from ajcamilo/master
Add setArrayParameter to SqlQuery
2024-10-10 20:07:08 +13:00
André Camilo 7e0c6795ff add setArrayParameter to SqlQuery 2024-10-09 13:24:52 +01:00
Roland Praml 8b4804be22 Fix: after DB.inserAll, transaction may stay in batchmode 2024-10-08 13:16:37 +02:00
Roland Praml a8418a3d75 Created test for batch escalation 2024-10-08 13:16:32 +02:00
Rob BygraveandGitHub bb0f63e38a Merge pull request #3488 from ebean-orm/dependabot/maven/ebean-test/commons-io-commons-io-2.14.0
Bump commons-io:commons-io from 2.7 to 2.14.0 in /ebean-test
2024-10-08 18:28:32 +13:00
Rob Bygrave 978ed26b78 Update ebean-agent 14.6.1 for #3484 2024-10-08 18:23:46 +13:00
Rob Bygrave 5cfa7295f8 Update tests for test-kotlin with latest agent 2024-10-08 18:17:08 +13:00
Noemi Praml 88d8b4fb5e Fix orderBy for cached many requests 2024-10-07 15:04:46 +02:00
dependabot[bot]andGitHub 93155d3c8f Bump commons-io:commons-io from 2.7 to 2.14.0 in /ebean-test
Bumps commons-io:commons-io from 2.7 to 2.14.0.

---
updated-dependencies:
- dependency-name: commons-io:commons-io
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-10-03 18:46:07 +00:00
Rob Bygrave 6d5f740337 TestQueryPaging example to H2 and Postgres due to use of nulls first
nulls first isn't supports by mysql
2024-09-20 21:21:57 +12:00
Rob Bygrave bd06b57144 Add valhalla EA build 2024-09-18 20:49:40 +12:00
Rob Bygrave 77383f4d29 Version 14.6.0 2024-09-17 22:23:13 +12:00
Rob Bygrave 29fcbbfe97 Bump ebean-agent to 14.6.0 2024-09-17 22:09:44 +12:00
Rob BygraveandGitHub d9e0a35efb Merge pull request #3481 from ebean-orm/feature/boostrap-service
Use io.ebean.service.BootstrapService as common marker interface for service loading bootstrapped services
2024-09-17 22:03:52 +12:00
Rob BygraveandGitHub 0c01ecbac7 Merge pull request #3478 from ebean-orm/feature/3462
#3462 Add Paging as alternative to maxRows + firstRow + orderBy
2024-09-17 22:03:13 +12:00
Rob BygraveandGitHub 5095583cc8 Merge pull request #3473 from ebean-orm/feature/3455-query-beans-improvement
#3455 - Improve query beans such that filterMany() expressions are only on ToMany relationships
2024-09-17 22:02:40 +12:00
Rob Bygrave 92f04a2353 Use io.ebean.service.BootstrapService as common marker interface for service loading bootstrapped services 2024-09-17 21:58:19 +12:00
Rob BygraveandGitHub acbce35182 Merge pull request #3480 from ebean-orm/feature/emptylist
Change EmptyPagedList to be deprecated from public use
2024-09-16 21:07:40 +12:00
Rob Bygrave d6165f4b17 Change EmptyPagedList to be deprecated from public use
This should never have been public really
2024-09-16 20:58:40 +12:00
Rob Bygrave 95656360a9 Mark OrderBy constructors as deprecated
The plan is to migrate OrderBy into an interface
2024-09-15 19:21:17 +12:00
Rob Bygrave 65d7df5488 #3462 Add Paging as alternative to maxRows + firstRow + orderBy
Paging is an alternative to specifying the maxRows + firstRow + orderBy on a query.

Example:
```java

    var orderBy = OrderBy.of("lastName desc nulls first, firstName asc");
    var paging = Paging.of(0, 100, orderBy);

    DB.find(Contact.class)
      .setPaging(paging)
      .where().startsWith("lastName", "foo")
      .findList();
```
2024-09-12 22:54:35 +12:00
Rob Bygrave 12648cd37d Fix test TestQueryFilterMany 2024-09-12 20:31:37 +12:00
Rob Bygrave edbd13c075 Version 14.5.2 2024-09-11 20:58:13 +12:00
Rob BygraveandGitHub 0964980a69 Merge pull request #3474 from ebean-orm/feature/3453
#3453 - Different filterMany behavior when no matches found
2024-09-11 20:27:50 +12:00
Rob Bygrave dc7d349366 #3453 - Different filterMany behavior when no matches found 2024-09-10 23:11:44 +12:00
Rob Bygrave a2e66bcb89 #3455 - Improve query beans such that filterMany() expressions are only on ToMany relationships
Use protected helper methods on TQAssocBean for the filterMany() methods generated onto AssocMany beans.
2024-09-10 00:24:41 +12:00
Rob Bygrave 4d79815779 #3455 - Improve query beans such that filterMany() expressions are only on ToMany relationships
Changes the query bean code generation for "Associated beans" to have separate AssocOne and AssocMany for *ToOne and *ToMany relationships.

Moves the filterMany() expressions such that they are only available on the *ToMany relationships.
2024-09-09 23:26:13 +12:00
Rob BygraveandGitHub cbac00a89f Merge pull request #3472 from ebean-orm/feature/3461-take-2
#3461 - Add also() for query beans
2024-09-09 22:18:40 +12:00
Rob Bygrave 33b2c398f6 #3461 - Add also() for query beans 2024-09-09 22:13:04 +12:00
Rob BygraveandGitHub 416f50e782 Merge pull request #3471 from ebean-orm/feature/bump-agent
Bump ebean-agent, will support future improvement to query beans with…
2024-09-09 21:59:20 +12:00
Rob Bygrave 2e8a6ceb53 Bump ebean-agent, will support future improvement to query beans with AssocOne AssocMany 2024-09-09 21:54:09 +12:00
Rob Bygrave f0fd9003ad Version 14.5.1 2024-09-02 22:03:55 +12:00
Rob Bygrave dfeffb7c5e Bump ebean-agent, no effective change 2024-09-02 21:50:21 +12:00
Rob BygraveandGitHub 4b0fcb1d29 Merge pull request #3469 from ebean-orm/feature/orderBy2
#3466 - Duplicated entities in findMany when a ManyToOne relation is fetched
2024-09-02 20:53:42 +12:00
Rob Bygrave a7fe5d2b84 #3466 - Duplicated entities in findMany when a ManyToOne relation is fetched (Postgresql)
Internally in OrmQueryDetail.markQueryJoins() the SpiQueryManyJoin is determined and returned. This change uses this and effectively removes the code from OrmQueryRequest.determineMany() and BeanDescriptor.manyProperty() which was the source of this issue (performing a similar task but not correctly taking the full path into account and hence the source of this bug).
2024-09-02 19:28:11 +12:00
Rob BygraveandGitHub 30327fe33e Improve existing test asserts around order by clause (#3467) 2024-09-02 08:25:19 +12:00
Rob Bygrave 1e013331d4 Improve existing test asserts around order by clause 2024-09-02 08:19:02 +12:00
Rob BygraveandGitHub f8964707d9 #3463 - Ignore queryBean.select(null) calls (#3464) 2024-08-27 21:01:51 +12:00
Rob BygraveandGitHub 86c7de2de8 ebean-test: Modify postgis platform to support both net.postgis and og.postgis (#3449)
* ebean-test: Modify postgis platform to support both net.postgis and org.postgis

Use Class.forName() to test existence of net.postgis.jdbc.DriverWrapperLW and if available use that driver rather than the older org.postgis.DriverWrapperLW one.

Also support explicitly specifying the driver to use via test property - ebean.test.postgis.driver

* Update test for net postgis to use a separate container

* Remove NetPostgisSetup as PostgisSetup handles both cases now
2024-08-27 20:44:03 +12:00
Michael BenzandGitHub 53b4d94933 Update README.md fixing broken Foconis logo (#3457)
Updated the Foconis AG logo with the new Foconis Analytics URL which was broken because of a deep link to a Yoomla logo that is no longer available.
2024-08-27 20:40:36 +12:00
Rob Bygrave b0ec23e53c Update tests to ensure ResetBasicData.reset() was called early 2024-08-04 18:59:46 +12:00
Rob Bygrave 20caae532c Adjust ResetBasicData with more output 2024-08-04 18:15:22 +12:00
Rob Bygrave 4369481c1a Adjust ResetBasicData with more output 2024-08-04 18:11:36 +12:00
Rob Bygrave c94426b6b4 Update tests config for ebean-net-postgis-types 2024-07-22 22:01:42 +12:00
Rob Bygrave b2ff32e88c Update tests config for ebean-net-postgis-types 2024-07-22 21:47:48 +12:00
Rob Bygrave 3bd8dfa7bf Update tests config for ebean-net-postgis-types 2024-07-22 20:12:27 +12:00
Rob Bygrave 0e7abdd137 Version 14.5.0 2024-07-22 08:33:34 +12:00
Ryszard TrojnackiandGitHub 9135f2cd3e New Postgis types / Java modules (#3448)
* Added modules `ebean-net-postgis-types`, `ebean-net-postgis` for new `net.postgis` geometry types without support for GeoLatte.

* Added missing `uses` entry in `module-info.java` for `io.ebean.api`.
2024-07-22 07:31:30 +12:00
Rob Bygrave 6785d5703e Update tests for DB2 forUpdate() 2024-07-17 08:01:26 +12:00
Rob Bygrave 0a95ac7fa0 Update tests for DB2 forUpdate() 2024-07-16 22:18:29 +12:00
Rob BygraveandGitHub bbd5636689 #3444 - DBName with hyphens creates invalid code (#3447) 2024-07-16 20:22:08 +12:00
Noemi PramlandGitHub 9f0eaef3d8 Db2 forupdate fix (#3446)
* ADD failing test for db2

* ADD: possible fix
2024-07-16 19:37:20 +12:00
Rob Bygrave a5d2a574d3 #3433 - Put test back from desc -> description as desc as a column name isn't widely supported by other databases 2024-07-08 21:54:35 +12:00
Rob BygraveandGitHub 6e7adbb8e4 #3433 - Entity property called desc used with query order by desc generates bad sql (#3438) 2024-07-04 00:05:01 +12:00
Rob BygraveandGitHub 8913bead89 [ebean-migration] #3434 - Connection is closed error running migration with MySql and Hikari (#3437) 2024-07-02 23:47:14 +12:00
Rob BygraveandGitHub cdf1cd8487 [ebean-redis] Fix for #3432 empty value for natural keys (#3436) 2024-07-02 22:06:57 +12:00
Rob BygraveandGitHub 2582c4b653 Bump to ebean-agent 14.5.0/15.5.0 with ASM 9.7 for JDK 22 and 23 support (#3435) 2024-07-02 18:08:08 +12:00
Rob Bygrave a9e3e2ea43 Version 14.4.0 2024-06-26 22:33:04 +12:00
Rob Bygrave 834ce971b3 Bump ebean-agent, no functional change 2024-06-26 22:19:58 +12:00
Rob BygraveandGitHub 5c27f89677 Change includeLabelInSql to default to true (#3431)
To disable this use ebean.includeLabelInSql=false or set this via
`DatabaseBuilder.includeLabelInSql(false)``
2024-06-26 20:32:19 +12:00
Rob BygraveandGitHub bfbbb7e7a7 Bump ebean-datasource dependency to 9.0 with automatic Lambda mode detection (#3430)
* Bump ebean-datasource dependency to 9.0 with automatic Lambda mode detection

ebean-datasource 9.0 automatically detects when it is running in AWS Lambda
and will set validateOnHeartbeat to false. In Lambda we don't want to validate
connections in background threads that can suspend in Lambda.
2024-06-26 20:27:49 +12:00
Rob BygraveandGitHub a8947c7d2f Bump ebean-migration dependency to 14.1.0 with fastMode enabled by default (#3429)
ebean-migration 14.1.0 defaults fastMode to true. This means that it first
runs a fast check that all migrations have been run. If that does not succeed
for any reason it runs the normal migration process.
2024-06-26 20:15:21 +12:00
Rob BygraveandGitHub d5401efb08 #3423 JtaTransactionManager keeps reference to already closed scope (and Transaction/connection ThreadLocal) when JtaTxnListener#afterCompletion is called by a different thread (#3424)
Bugfix for "Long/slow transaction reaper" in Wildfire that can close/rollback a transaction in a different thread. Fix is to use active flag to inactivate the transaction and detect that case in JtaTransactionManager.getCurrentTransaction()
2024-06-21 07:57:31 +12:00
Rob Bygrave 925ceaf441 Update build actions/setup-java@v4 2024-06-14 21:47:43 +12:00
Rob Bygrave c5fea13ca5 Update build actions/setup-java@v4 2024-06-14 21:42:06 +12:00
Rob Bygrave 6fa3759786 Add 23 to build 2024-06-14 21:34:54 +12:00
Rob Bygrave 1c5288b6ec Version 14.3.1 2024-06-10 19:26:40 +12:00
Rob Bygrave b485fb7440 Bump ebean-agent to 14.3.1 2024-06-10 19:02:41 +12:00
Rob BygraveandGitHub b07f909dd3 Bump parent pom to 4.2 with EA changes to annotation processing (#3417)
* Bump parent pom to 4.2 with EA changes to annotation processing

Annotation processing needs to be explicitly on in JDK 24 EA builds

* Bump bytebuddy version in ebean-test and use experimental=true for EA builds

* Use parent pom 4.3 with bytebuddy.experimental=true by default for surefire
2024-06-10 18:36:40 +12:00
Rob BygraveandGitHub fa92e7a4b7 Merge pull request #3416 from ebean-orm/feature/querybean-gen-suppresswarnings
Change QueryBean to use protected constructors, suppress warning on generated query beans
2024-06-10 12:39:53 +12:00
Rob Bygrave 1823ef288a Change QueryBean to use protected constructors, suppress warning on generated query beans 2024-06-07 22:48:04 +12:00
Rob BygraveandGitHub 7b2128b02f Merge pull request #3415 from ebean-orm/feature/3412
#3412 Use existing/parent transaction with fetch query on ToMany paths
2024-06-07 22:31:24 +12:00
Rob Bygrave 3c84a902e8 Followup for #3412 - Refactor DefaultBeanLoader move query creation logic into LoadBeanRequest
Move the query creation, using transaction and configure into LoadBeanRequest. This code then looks more like that of LoadManyRequest.
2024-06-07 22:26:48 +12:00
Rob Bygrave 3ce95c34cb #3412 Use existing/parent transaction with fetch query on ToMany paths
Fix such that LoadManyRequest uses the parent requests transaction rather
than obtain a new read only transaction to perform the fetch query.
2024-06-07 22:16:02 +12:00
Rob BygraveandGitHub d817dcb549 Merge pull request #3413 from ebean-orm/feature/fix-logging-naturalKey
Fix logging message for naturalKey MPUT to include the natural key properties
2024-05-31 21:57:24 +12:00
Rob BygraveandGitHub 5f218e1fdb Merge pull request #3409 from kaiyaok2/fix_NIO
Fixed non-idempotent tests in `TestCacheSerialization`
2024-05-31 21:56:33 +12:00
Rob Bygrave 59daf5689a Fix logging message for naturalKey MPUT to include the natural key properties 2024-05-31 21:52:38 +12:00
kaiyaok2 44efed5cd9 fixed non-idempotent tests 2024-05-26 23:57:12 +08:00
Rob Bygrave be28314e31 Update test kotlin to use kotlin-querybean-generator 14.3.0
Fixes the test as we now use QueryBean etc rather than TQRootBean
2024-05-16 00:05:55 +12:00
Rob Bygrave 053d82b54a Version 14.3.0 2024-05-14 22:10:08 +12:00
Rob BygraveandGitHub 0141e2effa Merge pull request #3401 from ebean-orm/feature/agent-14.3.0
Bump to ebean-agent 14.3.0
2024-05-14 21:18:12 +12:00
Rob Bygrave a33bb4d4c8 Bump to ebean-agent 14.3.0 2024-05-14 21:15:13 +12:00
Rob BygraveandGitHub d0348210be Merge pull request #3398 from ebean-orm/feature/NoTimeZone
mysql: Support "NoTimeZone" to bypass MySQL JDBC use of Timezone Calendar
2024-05-01 20:30:56 +12:00
Rob BygraveandGitHub 753cf66cf0 Merge pull request #3397 from ebean-orm/feature/distinctOn
Postgres: Add support for DISTINCT ON query clause
2024-05-01 20:30:41 +12:00
Rob Bygrave 4a8b4dd5fb mysql: Support "NoTimeZone" to bypass MySQL JDBC use of Timezone Calendar
Refer #3393 #3394
2024-05-01 20:24:10 +12:00
robin.bygrave 2faf7008db #3397 DISTINCT ON subquery support 2024-05-01 20:07:16 +12:00
Rob Bygrave 76c25cbe83 Postgres: Add support for DISTINCT ON query clause - fix test ebean.properties 2024-05-01 01:04:33 +12:00
Rob Bygrave 5c36a725f4 Postgres: Add support for DISTINCT ON query clause 2024-05-01 00:50:37 +12:00
Rob BygraveandGitHub b99d4f5a51 Merge pull request #3396 from ebean-orm/feature/limitOffset-with-labelComment
Include inline sql hint and comment in limit/offset sql
2024-04-30 23:57:04 +12:00
Rob Bygrave 7d18942357 Include inline sql hint and comment in limit/offset sql 2024-04-30 23:46:36 +12:00
Rob Bygrave e51d9ba2ab Fix test test-java16 using maven.compiler.release 2024-04-14 22:26:20 +12:00
Rob BygraveandGitHub 1b1dce90ed Merge pull request #3385 from ebean-orm/feature/rename-tqrootbean
Rename TQRootBean to QueryBean
2024-04-12 22:47:07 +12:00
Rob BygraveandGitHub 405834fa45 Merge branch 'master' into feature/rename-tqrootbean 2024-04-12 22:46:55 +12:00
Rob BygraveandGitHub 7720229af9 Merge pull request #3389 from ebean-orm/feature/bump-datasource-2
Bump ebean-datasource, ebean-test-containers, ebean-agent
2024-04-12 21:51:51 +12:00
Rob Bygrave 89a294414e Bump ebean-agent 14.2.1 2024-04-12 21:49:56 +12:00
Rob Bygrave 7bbfc00b86 Bump ebean-datasource and ebean-test-containers
ebean-datasource 8.14 has experimental lambda mode
ebean-test-containers has helper method to create S3Client for Localstack
2024-04-11 23:20:37 +12:00
Rob BygraveandGitHub d6c76de0a2 Merge pull request #3387 from ebean-orm/feature/bump-parent-4_1-byteBuddy
Bump parent to 4.1 with Byte-Buddy net.bytebuddy.experimental=true
2024-04-09 21:32:32 +12:00
Rob Bygrave 36f3986689 Bump avaje junit composite and bytebuddy to 1.14.13 2024-04-09 21:06:52 +12:00
Rob Bygrave f0f4f13ec6 Bump parent to 4.1 with Byte-Buddy net.bytebuddy.experimental=true
Uses maven-surefire-plugin with:
<argLine>-XX:+EnableDynamicAgentLoading -Dnet.bytebuddy.experimental=true</argLine>
2024-04-09 21:03:59 +12:00
Rob Bygrave 08466d42e9 Fix test TestLazyLoadMany with orderBy on query 2024-04-05 22:56:05 +13:00
Rob Bygrave 1f841982a5 Rename TQRootBean to QueryBean 2024-04-05 22:08:26 +13:00
Rob Bygrave b34704a1fa Fix kotlin test to use latest kotlin-querybean-generator 2024-04-05 00:29:17 +13:00
Rob Bygrave 0128d64841 Version 14.1.0 2024-04-04 22:54:23 +13:00
Rob Bygrave 68b313f778 Update ebean-agent to 14.1.0
This version allows for removal of query bean setRoot() which is no longer needed.
2024-04-04 22:42:06 +13:00
Rob BygraveandGitHub fad32c58d8 Merge pull request #3384 from ebean-orm/feature/rename-iquerybean
Rename QueryBean interface to IQueryBean (because we want to rename TQRootBean)
2024-04-04 22:36:59 +13:00
Rob Bygrave 8f1ebdb89a Rename QueryBean interface to IQueryBean (because we want to rename TQRootBean)
We want to rename TQRootBean to QueryBean. I can't do that right now because we need to make ebean-agent aware of that first. So yes, perhaps not ideal with IQueryBean but I think it will make sense once TQRootBean is renamed to QueryBean.
2024-04-04 22:35:55 +13:00
Rob BygraveandGitHub f7703efde2 Merge pull request #3383 from ebean-orm/feature/orderById
#3379 Followup, Move orderById() to common QueryBuilder interface
2024-04-04 22:09:34 +13:00
Rob BygraveandGitHub c5ffccb649 Merge pull request #3382 from ebean-orm/fix/3381-pc-clear
Fix for #3381 - Empty OneToMany when overflowing LazyLoadBatchSize an…
2024-04-04 22:08:57 +13:00
Rob Bygrave 3e65705bf9 #3379 Followup, Move orderById() to common QueryBuilder interface
Effectively this adds it to QueryBeans (where it was missing)
2024-04-04 22:05:17 +13:00
Rob Bygrave 7469a38bbc #3375 Followup, Temporarily add back setRoot() method to allow time for IntelliJ plugin to be released
Adding this means that it will work with an old ebean-agent. It takes a few days to get a new IntelliJ plugin released and we can't wait due to wanting to release the bug fix for #3381
2024-04-04 21:53:18 +13:00
Rob Bygrave 7ea4311662 Fix for #3381 - Empty OneToMany when overflowing LazyLoadBatchSize and mixed queries
14.0.0 via #3295 introduced this bug.

 #3295 introduced a behaviour where bulk updates clear the persistence context. Now the lazy loading of a BeanCollection works with an assumption that the "parent bean" is in the persistence context (and this assumption is broken with that change for this test case). That is, the bulk update is clearing the persistence context - removing the parent bean BEFORE the lazy loading is invoked ... and that doesn't then work because the parent bean isn't in the persistence context.

 This fix means that when lazy loading many's, the parent beans are putIfAbsent into the persistence context.
2024-04-04 20:13:20 +13:00
Rob BygraveandGitHub f556e04f58 Merge pull request #3380 from ebean-orm/feature/deprecate-update-transaction
Deprecate update(transaction) and delete(transaction) - migrate to usingTransaction(transaction)
2024-04-01 20:57:58 +13:00
Rob Bygrave d9c75a60a5 Deprecate update(transaction) and delete(transaction) - migrate to usingTransaction(transaction)
Migrate to usingTransaction(transaction) to set the transaction explicitly on a delete or update query.
2024-04-01 20:35:59 +13:00
Rob BygraveandGitHub 225bec7b28 Merge pull request #3379 from ebean-orm/feature/query-builder-interface
Add QueryBuilder interface as common API for Query and QueryBean
2024-04-01 19:42:34 +13:00
Rob Bygrave da44f7e604 Add QueryBuilder interface as common API for Query and QueryBean 2024-04-01 18:58:57 +13:00
e0eda4f8be #3370 LimitOffsetPagedList add getTotalCount cache (#3373)
* #3370 LimitOffsetPagedList add getTotalCount cache

* Move totalRowCount check to inside the lock

* No change, format only on LimitOffsetPagedList

---------

Co-authored-by: Rob Bygrave <robin.bygrave@gmail.com>
2024-04-01 11:08:57 +13:00
Rob BygraveandGitHub e4e780588c Merge pull request #3378 from ebean-orm/feature/QueryBean-interface
Add QueryBean interface for query beans to implement
2024-04-01 10:59:38 +13:00
Rob Bygrave 7c8f235550 Add QueryBean interface for query beans to implement 2024-04-01 10:56:25 +13:00
Rob BygraveandGitHub 9a77ec1567 Merge pull request #3377 from ebean-orm/feature/3374
querybeans: #3374 - Add copy() method to TQRootBean
2024-04-01 09:09:24 +13:00
Rob Bygrave ff426319f5 Fix deprecated annotation for kotlin-querybean-generator 2024-04-01 09:02:13 +13:00
Rob Bygrave 7f56aff9dd Bump kotlin-querybean-generator 2024-03-31 11:49:58 +13:00
Rob Bygrave cdbdd98d36 querybeans: #3374 - Add copy() method to TQRootBean 2024-03-31 11:44:32 +13:00
Rob BygraveandGitHub 7bf030f59c Merge pull request #3376 from ebean-orm/feature/querybean-txn
Deprecate Query bean constructor that takes transaction - migrate to query.usingTransaction() instead
2024-03-31 11:38:26 +13:00
Rob Bygrave 16dca28831 Deprecate Query bean constructor that takes transaction - migrate to usingTransaction()
Migrate to query.usingTransaction() instead of the constructor that takes a transaction.
2024-03-31 11:37:32 +13:00
Rob BygraveandGitHub 678b43693d Merge pull request #3372 from ebean-orm/feature/1857-SlowQueryBindCapture
#1857 Add bind values capture for SlowQueryEvent / SlowQueryListener
2024-03-31 11:34:18 +13:00
Rob BygraveandGitHub 7ab93a0cdf Merge pull request #3375 from ebean-orm/feature/tidy-tqrootbean
Update TQRootBean with final methods, remove setRoot()
2024-03-31 11:32:54 +13:00
Rob Bygrave 951f942c73 Tidy TQRootBean constructor for alias.
Note that this requires the updated ebean-agent, where it will not longer use the setRoot() method which has now been removed.
2024-03-31 11:19:39 +13:00
Rob Bygrave cf2ec4b81d Modify TQRootBean making root final
Remove the unused setRoot() method
2024-03-31 10:02:41 +13:00
Rob Bygrave 7d1745ba53 Add final modifier to TQRootBean methods
As these are never expected to be overwritten
2024-03-31 09:57:42 +13:00
Rob BygraveandGitHub 7adbdbf532 feat: For SpringJdbcTransactionManager support using CurrentTenantProvider (#3368)
Note that this only works for Multi-Tenant PARTITION mode where the TenantId is a column on the tables (rather than schema or database multi-tenancy mode).
2024-03-26 22:45:39 +13:00
Rob Bygrave 40d9c88e34 #1857 Add bind values capture for SlowQueryEvent / SlowQueryListener
- changes SqlQueryEvent into an interface.
- captures the bind values the slow query used and makes those available via SlowQueryEvent
- also makes the query label and profileLocation available via SlowQueryEvent
2024-03-25 22:52:04 +13:00
Rob Bygrave ab45ad34e0 Version 14.0.2 2024-03-21 22:07:12 +13:00
Rob Bygrave 24b514f851 Bump ebean-agent, no effective change 2024-03-21 21:55:02 +13:00
Rob BygraveandGitHub 582fec7ce4 For #3363 disable flushOnQuery before BeanPersistAdapter post-processors (#3367) 2024-03-21 21:51:10 +13:00
Rob BygraveandGitHub 0b11c541c8 fix: #3142 Cascading a OneToMany, set the relationship when the child isn't new or dirty (#3366)
That is, previously the relationship back from the child to the parent was being updated when the child bean was new or dirty BUT NOT in the case when the child bean was loaded and unchanged.

This fix includes that case updating the ManyToOne side of the relationship on the child when the save is cascaded.
2024-03-21 00:14:54 +13:00
Rob BygraveandGitHub 540ceab96f feat: Add query.setHint() to support sql hint as inline comment in select queries (#3365)
* feat: Add query.setHint() to support sql hint as inline comment in select queries

This is for ORM queries only.

An ORM query like:

    new QCustomer()
      .setHint("FirstRows")
      .select(QCustomer.Alias.id, QCustomer.Alias.name)
      .findList();

Produces SQL that includes the hint as an inline comment like:

  select /*+ FirstRows */ t0.id, t0.name
  from customer t0

* Fix test QOrderTest
2024-03-20 21:48:43 +13:00
Rob BygraveandGitHub 8b858a073a feat: Add includeLabelInSql configuration option to include query label as inline comment in generated sql select (#3362)
* feat: Add includeLabelInSql configuration option to include query label as inline comment in generated sql select

The generated select queries can look like:

select /* MyInnerTest.insert_and_find */ t0.id, ...

Using either query.setLabel() or profile location (which all query beans get by default). This means that tooling looking at sql in the database can more easily relate that sql back to application code.

* More tests for labels with includeLabelInSql=true

* Remove trim when using profileLocation label
2024-03-18 07:38:30 +13:00
Rob BygraveandGitHub 02dafc9838 Merge pull request #3360 from ebean-orm/feature/refactor-DbExpressionRequest
Refactor extract DbExpressionRequest interface for db platform specific expressions
2024-03-08 00:53:56 +13:00
Rob Bygrave 0816810d3b Refactor extract DbExpressionRequest interface for db platform specific expressions
This provides a simpler DbExpressionRequest interface for db platform specific expression adapters (rather than the SpiExpressionRequest which has more features that we don't wish to expose to those expression adapters.
2024-03-07 22:45:21 +13:00
Rob Bygrave 1f6e2ee844 No effective change - update test only ClusterTest, increase wait to 200ms 2024-03-07 20:59:41 +13:00
Rob Bygrave dc00765a98 Merge branch 'fix-for-db2' 2024-03-07 20:45:57 +13:00
Rob Bygrave a48b2f4ebe #3354 Use 4000 for DB Lob detection with distinct query
- Use 4000 to match the DB2 logic for considering a column a lob (for distinct etc)
- Rename distinctNoLobs -> platformDistinctNoLobs
- Rename  isDbLob() -> isLobForPlatform()
- Rename unselectLobs() -> unselectLobsForPlatform()
2024-03-07 20:45:40 +13:00
Rob BygraveandGitHub 837563544f Merge pull request #3357 from ebean-orm/feature/avaje-config-dependency-ContainerConfig
Modify ContainerConfig to remove the avaje-config dependency
2024-03-07 20:23:36 +13:00
Rob Bygrave fd199f406b Modify ContainerConfig to remove the avaje-config dependency
This actually reverts a change that was made in commit:
https://github.com/ebean-orm/ebean/commit/803f1d86428ce3b653276d72207e5a0009b57d16
2024-03-05 21:18:27 +13:00
Roland Praml a48e96c7e9 FIX broken test for DB2 2024-03-04 10:02:05 +01:00
Rob Bygrave 7ba6e5f67d Add howto-deploy-to-central.md 2024-03-03 22:08:47 +13:00
Rob Bygrave 6ce42b1ca3 Version 14.0.1 2024-03-03 20:24:26 +13:00
Rob BygraveandGitHub 89617cefbe Merge pull request #3353 from ebean-orm/feature/bump-migration-14
dep: Bump ebean-migration to 14.0.0, no effective change
2024-03-03 20:19:40 +13:00
Rob Bygrave dd377621a4 dep: Bump ebean-migration to 14.0.0, no effective change
No effective change in that ebean-migration 14.0.0 has no change, it was released to align version numbers with 14.x
2024-03-03 20:19:17 +13:00
Rob Bygrave d844855462 Bump ebean-agent to 14.0.1 2024-03-03 18:32:14 +13:00
Rob BygraveandGitHub f68c25d5f3 Merge pull request #3352 from ebean-orm/feature/dep-common-components
dep: Update the common components to 14.0.0 ebean-joda-types, ebean-jackson-jsonnode
2024-03-03 18:29:15 +13:00
Rob Bygrave 61cfc7a979 dep: Update the common components to 14.0.0 ebean-joda-types, ebean-jackson-jsonnode 2024-03-03 17:01:36 +13:00
Rob BygraveandGitHub 3c98ee7f1b Merge pull request #3351 from ebean-orm/dep/bump-config
Bump test dependencies only - logback and ebean-test-containers
2024-03-03 16:54:56 +13:00
Rob Bygrave 0738316f15 Bump test dependencies only - logback and ebean-test-containers 2024-03-03 16:54:22 +13:00
Rob BygraveandGitHub ceb83befa3 Merge pull request #3350 from ebean-orm/dep/bump-config
dep: Bump avaje-config to 3.12 - supports AWS AppConfig & Dynamic Logback
2024-03-03 15:42:59 +13:00
Rob Bygrave a0b04cceda dep: Bump avaje-config to 3.12 - supports AWS AppConfig & Dynamic Logback
This version of avaje-config supports using AWS AppConfig as a configuration source (via avaje-aws-appconfig). It also supports dynamic changing Logback logging levels (via avaje-dynamic-logback).
2024-03-03 15:38:14 +13:00
Rob Bygrave 03edfb5454 git workflow trigger on push to master and pull_request 2024-03-03 15:33:39 +13:00
Rob BygraveandGitHub 62015451df Merge pull request #3349 from ebean-orm/feature/dep-ebean-datasource
dep: Bump ebean-datasource to 8.12
2024-03-03 15:32:36 +13:00
Rob Bygrave ed9113efe6 dep: Bump ebean-datasource to 8.12
This adds the option to register a JVM shutdown hook (which we generally will not use with ebean as the ebean io.ebean.Database shutdown wants to shutdown the DataSource after any background tasks have completed).

This also adds an experimental feature for use with AWS Lambda to check for old idle connections due to lambda suspension.
2024-03-03 15:24:44 +13:00
Rob Bygrave 334793667e Add deployment error message for ManyToMany with one of the related beans missing an @Id property 2024-03-03 14:14:23 +13:00
Rob BygraveandGitHub 351a1c4739 Merge pull request #3348 from ebean-orm/feature/3313-fetchGroup-with-config
#3313 Ability to configure fetch batch size when using FetchGroups and query beans
2024-03-03 13:53:52 +13:00
Rob Bygrave b2de333dcc #3313 Ability to configure fetch batch size when using FetchGroups and query beans
We can do this currently using string paths and properties, this adds support for doing this when using query beans and strong types
2024-03-03 13:47:49 +13:00
Rob Bygrave 6091f7b683 No effective change - tidy test TestJsonImplicitLoaded 2024-03-03 12:25:25 +13:00
Rob BygraveandGitHub 43fb84cbc0 Merge pull request #3345 from FOCONIS/jsonwrite-loaded-props
NEW: Allow control of jsonwrite-loadedprops
2024-03-03 12:23:17 +13:00
Rob BygraveandGitHub 52a4e9e19b Merge pull request #3347 from ebean-orm/feature/3337-querybean-imports
#3337 Fix querybean-generation to not import the entity bean type
2024-03-03 12:17:42 +13:00
Rob Bygrave a2cdea24ed #3337 Fix querybean-generation to not import the entity bean type
Use the full canonical name of the entity bean in the generated code.
2024-03-03 12:13:49 +13:00
Rob Bygrave cd780208e5 Javadoc format only for io.ebean.Database 2024-03-03 11:45:36 +13:00
Rob BygraveandGitHub 9ce0e923d7 Merge pull request #3346 from ebean-orm/feature/lengthCheck-postgres
#3341 String length validation with Postgres PGobject (JSON/JSONB)
2024-03-02 10:26:52 +13:00
Rob Bygrave 9e461e4708 #3341 String length validation with Postgres PGobject (JSON/JSONB) 2024-03-02 10:06:22 +13:00
Rob Bygrave 5fa09a6f90 #3341 String length validation with Postgres PGobject (JSON/JSONB) 2024-03-02 09:52:04 +13:00
Rob Bygrave 6babb2e6f5 Add ebean.lengthCheck for mariadb test run 2024-03-02 09:39:25 +13:00
Rob Bygrave 26abe27e42 Add ebean.lengthCheck for sqlserver17 test run 2024-03-02 09:38:33 +13:00
Rob Bygrave 9b18d46b78 Add ebean.lengthCheck for mysql test run 2024-03-02 09:27:05 +13:00
Roland Praml eed487ad26 NEW: Allow control of jsonwrite-loadedprops 2024-02-29 13:26:22 +01:00
Rob BygraveandGitHub c10865dfaf Merge pull request #3344 from ebean-orm/feature/bump-avaje-config-311
Bump avaje-config to 3.11
2024-02-27 21:22:38 +13:00
Rob Bygrave 2352df309c Bump avaje-config to 3.11 2024-02-27 21:21:58 +13:00
Rob Bygrave feb2bd1e15 String length validation tidy up 2024-02-27 21:04:19 +13:00
Rob Bygrave 11c9bdfc6f Squashed commit of the following:
commit 20152e16891582f8ff466a93ec2cf01871824d6d
Author: Rob Bygrave <robin.bygrave@gmail.com>
Date:   Tue Feb 27 20:59:51 2024 +1300

    #3341 Update DatabaseConfig for fluid style + javadoc

commit 1c495a7384
Author: Roland Praml <roland.praml@foconis.de>
Date:   Mon Feb 26 10:25:42 2024 +0100

    Fix: Compile errors

commit 574876b758
Merge: df7b04877 77634fc3e
Author: Roland Praml <roland.praml@foconis.de>
Date:   Fri Feb 23 16:16:39 2024 +0100

    Merge branch 'master-rob' into FOCONIS-string-length-validation

commit df7b04877d
Author: Rob Bygrave <robin.bygrave@gmail.com>
Date:   Mon Jun 26 21:16:32 2023 +1200

    #3121 BindMaxLength validation

    At deploy time derive a BindMaxLength property to use
    per BeanProperty

commit 4683877e0b
Merge: 9a4b9d4be d0020ab8c
Author: Rob Bygrave <robin.bygrave@gmail.com>
Date:   Fri Jun 23 16:51:34 2023 +1200

    Merge branch 'string-length-validation' of github.com:FOCONIS/ebean into FOCONIS-string-length-validation

commit d0020ab8ce
Author: Roland Praml <roland.praml@foconis.de>
Date:   Tue Jun 20 14:47:20 2023 +0200

    Length validation less invasive

commit 9b3b8ad46a
Author: Roland Praml <roland.praml@foconis.de>
Date:   Tue Jun 20 13:03:04 2023 +0200

    extended DataBind, so that it could return the last bound object

commit ca3c02bc1c
Author: Roland Praml <roland.praml@foconis.de>
Date:   Mon Jun 19 09:52:52 2023 +0200

    Failing test for SqlServer
2024-02-27 21:04:06 +13:00
Rob BygraveandGitHub 4a6fc98395 Merge pull request #3339 from ebean-orm/fix/3338
Fix for #3338 Potential shutdown hang with SpringContextShutdownHook …
2024-02-26 21:58:39 +13:00
Rob Bygrave 7322030e90 Fix for #3338 Potential shutdown hang with SpringContextShutdownHook and ebean ShutdownHook 2024-02-26 08:32:44 +13:00
Rob BygraveandGitHub 77634fc3eb Merge pull request #3336 from ebean-orm/feature/bump-postgresql-4272
Bump postgresql dependency to 42.7.2
2024-02-21 16:11:24 +13:00
robin.bygrave ed8d4b5fc4 Bump postgresql dependency to 42.7.2 2024-02-21 16:05:13 +13:00
Rob BygraveandGitHub 187cc0903d Merge pull request #3329 from ebean-orm/feature/bump-test-dependencies
Bump test dependencies for assertj and bytebuddy
2024-02-19 22:04:56 +13:00
Rob Bygrave 1d7a14c8f4 Bump test dependencies for assertj and bytebuddy 2024-02-19 21:51:38 +13:00
Rob Bygrave c58b7d3da3 Test ebean.properties config values 2024-02-15 22:51:26 +13:00
Rob Bygrave 6b2cdc14aa Version 14.0.0 2024-02-15 22:48:38 +13:00
Rob Bygrave 6d712a92a0 Bump ebean-agent to 14.0.0, no functional change 2024-02-15 22:21:09 +13:00
Rob BygraveandGitHub ea11b0c3b6 Merge pull request #3289 from FOCONIS/fix-nested-user-objects
Change semantic of userObjects in nested transaction
2024-02-15 22:10:45 +13:00
Rob BygraveandGitHub 08e8402d05 Merge pull request #3301 from ebean-orm/feature/3295-PC-clear-on-bulk-update
#3295 Clear PersistenceContext on execution of bulk updates or deletes
2024-02-15 22:09:16 +13:00
Rob BygraveandGitHub 006ad79379 Merge branch 'master' into feature/3295-PC-clear-on-bulk-update 2024-02-15 22:09:03 +13:00
Rob BygraveandGitHub 0e063549cd Merge pull request #3327 from ebean-orm/feature/remove-deprecated-commitTransaction
Remove deprecated database.commitTransaction(), migrate to transaction.commit()
2024-02-15 22:07:32 +13:00
Rob BygraveandGitHub 4f0d2cabfb Merge pull request #3325 from ebean-orm/feature/default-batchSize-100
Change default persistBatchSize from 20 to 100 (as a better default value)
2024-02-15 22:07:14 +13:00
Rob Bygrave 80b2d9f983 Remove deprecated database.commitTransaction(), migrate to transaction.commit()
Remove the deprecated methods:
- DB.commitTransaction()
- DB.rollbackTransaction()
- DB.endTransaction()
- database.commitTransaction()
- database.rollbackTransaction()
- database.endTransaction()

Migrate to using try-with-resources and transaction.commit(), transaction.rollback()
2024-02-15 21:56:57 +13:00
Rob Bygrave 287d0c467d #3326 Update the test example of Postgres DML with RETURNING clause to use explicit transactions and transaction.addModification() 2024-02-11 14:25:01 +13:00
Rob Bygrave a8835379e7 #3326 Add test as example of Postgres DML with RETURNING clause 2024-02-11 13:18:19 +13:00
Rob Bygrave e4df20b9dc Update test TestPersistCascade with default batch size 100 2024-02-10 13:28:04 +13:00
Rob Bygrave 261b13ef4b Version 13.26.1 2024-02-10 12:40:30 +13:00
Rob Bygrave 7639034d7c Bump ebean-agent to 13.26.1 (no functional change here) 2024-02-10 12:17:47 +13:00
Rob Bygrave e6e53e0d93 Change default persistBatchSize from 20 to 100 (as a better default value)
This is the batch size used with PreparedStatement executeBatch() with
batched inserts, updates and deletes. 20 is really on the low side and
bumping this default to 100 seems good and right.
2024-02-10 12:15:50 +13:00
Rob BygraveandGitHub c71971eb5c Merge pull request #3322 from ebean-orm/fix/3319
(fix) Future queries do not trigger flush on BatchedPstmtHolder for #3319
2024-02-10 12:12:47 +13:00
Rob BygraveandGitHub 357af58db4 Merge pull request #3324 from ebean-orm/feature/postgres_insertOnConflict
Add support for Postgres INSERT ON CONFLICT update | nothing
2024-02-10 12:08:44 +13:00
Rob BygraveandGitHub 0abdb1550a Merge pull request #3310 from Ichtil/one_to_many_list_clear_test
Previous entities are not deleted when replacing OneToMany collection with a new one
2024-02-10 12:03:16 +13:00
Rob Bygrave c32fc814f6 Add support for insert/insertAll with both options and explicit transaction 2024-02-10 12:00:32 +13:00
Rob Bygrave 8e035939dc Add support for Postgres INSERT ON CONFLICT update | nothing
Adds InsertOptions with ability to control the options used
for insert with Postgres around ON CONFLICT.
2024-02-10 01:07:44 +13:00
Rob Bygrave edf98ee250 Fix test OneToManyListMarkAsDirtyTest with some wait time 2024-02-09 15:46:34 +13:00
Rob Bygrave 5f0a75a130 No effective change, update test renaming internal variables 2024-02-09 15:26:28 +13:00
Rob Bygrave d2f16cbf6a #3310 Fix for orphanRemoval with updated parent and 'vanilla collection'
The issue fixed here is a timing one where the parent bean is being updated.
The updated parent bean has its internal state reset before the cascade down
to the SaveManyBeans where for this case it needs to identify is the 'vanilla'
collection has set (via setChildren(new ArrayList()).

This fix is a change that for updated beans the dirtyProperties is always obtained
and then use this for the isChangedProperty() check.
2024-02-09 15:24:47 +13:00
Rob Bygrave 04ba81d12f #3310 Update test only, reuse existing entity beans
- Reuse the existing OmBeanListParent and child
- Simplify the test setup code
- Rename test methods to maybe better reflect what I think is failing

Noting that markAsDirty doesn't specifically have anything to do with this bug but it's more on whether the parent bean is dirty or dirty (markAsDirty is just a way to make the parent bean dirty).
2024-02-09 08:30:42 +13:00
Rob Bygrave f63e7ed5af Add test only for orphan removal to TestOrphanRemovalOverwrite
Using clear() and add() when the same id value is used
2024-02-08 00:14:22 +13:00
Rob Bygrave 66940c0f14 Update tests only for BeanList BeanSet BeanMap
Use Product entity with equals/hashCode implementation added via ebean enhancement
2024-02-07 22:29:05 +13:00
Rob Bygrave 1f48b3a6b3 (fix) Future queries do not trigger flush on BatchedPstmtHolder for #3319
This change is that findFutureCount, findFutureList, findFutureIds do not trigger a flush on BatchedPstmtHolder.

This is to address the possible ConcurrentModificationException that could occur at BatchedPstmtHolder.closeStatements(BatchedPstmtHolder.java:153)
2024-02-03 08:20:58 +13:00
Rob BygraveandGitHub 7d368097e9 Merge pull request #3321 from ebean-orm/feature/tidy-OrmQueryRequest-readOnly
Tidy OrmQueryRequest isReadOnly, just use query.isReadOnly instead
2024-02-02 14:44:06 +13:00
Rob Bygrave c849e29316 Tidy OrmQueryRequest isReadOnly, just use query.isReadOnly instead 2024-02-02 14:43:31 +13:00
Rob BygraveandGitHub c78a3dd6c4 Merge pull request #3318 from FOCONIS/fix-db2-test
Exclude test for DB2
2024-01-31 22:57:49 +13:00
Noemi Praml a4455ddbf2 Exclude test for DB2 2024-01-31 10:17:16 +01:00
Rob BygraveandGitHub 9787af77e4 Merge pull request #3315 from FOCONIS/db2-select-for-update
ADD: DB2 supports select .. for update queries
2024-01-30 22:53:19 +13:00
Noemi Praml 3786fb09a5 ADD: DB2 supports select .. for update queries 2024-01-29 15:12:21 +01:00
Rob Bygrave f34e7b6003 Version 13.26.0 2024-01-20 22:01:30 +13:00
Rob BygraveandGitHub 089dd8e364 Merge pull request #3311 from ebean-orm/feature/findSingleAttributeOrEmpty
enh: Add findSingleAttributeOrEmpty() returning Optional
2024-01-19 15:23:27 +13:00
Rob Bygrave 44770382fb enh: Add findSingleAttributeOrEmpty() returning Optional 2024-01-19 10:41:54 +13:00
Rob Bygrave 6645e5b9ec Update the test comments in TestPersistenceContextQueryScope
To reflect the behaviour with #3295
2024-01-19 08:58:19 +13:00
Rob BygraveandGitHub 2a62d413cc Merge pull request #3308 from Incanus3/fix/querybean_or_with_exists
fix TQRootBean.exists() when used with .or()
2024-01-19 08:29:29 +13:00
Rob Bygrave 0046d983cb Adjust test such that table alias does not clash
The .raw("contact.customer_id = customer.id") clashes as "customer.id" is
a logical path from contact
2024-01-19 08:14:58 +13:00
Jan Klička 006e33cb3e One to many replacing collection failing test cases 2024-01-18 17:29:24 +01:00
Jan Klička e80e8e027a One to many replacing collection failing test cases 2024-01-18 16:49:04 +01:00
Jakub Kaláb 2e1b52d7d4 WIP: fix TQRootBean.exists() when used with .or() 2024-01-18 11:32:34 +01:00
Rob BygraveandGitHub 09d5163396 Merge pull request #3307 from ebean-orm/feature/bump-avaje-config-310
Bump avaje-config to version 3.10
2024-01-18 22:30:42 +13:00
Rob Bygrave a6a38b9a92 Bump avaje-config to version 3.10 2024-01-18 22:30:09 +13:00
Rob BygraveandGitHub bd4521b240 Merge pull request #3306 from ebean-orm/feature/querybean-deprecated
Add forRemoval=true for existing Deprecated methods in query beans
2024-01-18 22:28:23 +13:00
Rob Bygrave 8a7379879b Add forRemoval=true for existing Deprecated methods in query beans 2024-01-18 20:15:57 +13:00
Rob BygraveandGitHub b78dd6f79a Merge pull request #3304 from ebean-orm/feature/3296-querybean-copy
#3296 Add copy() method to query beans
2024-01-15 22:38:30 +13:00
Rob Bygrave 4ebb5fd112 #3296 Add copy() method to query beans 2024-01-15 22:30:17 +13:00
Rob Bygrave 487368976f Tidy SimpleQueryBeanWriter internals 2024-01-15 22:03:17 +13:00
Rob Bygrave c6defceec9 Add additional test for filterMany() with fetch() 2024-01-15 21:02:47 +13:00
Rob Bygrave 3576aafffc #3295 When isAutoPersistUpdates is used do NOT clear the PersistenceContext
Also make improvements to the test asserts in TestPersistenceContextQueryScope
2024-01-10 23:23:47 +13:00
Rob Bygrave 66234249c6 #3295 Clear PersistenceContext on execution of bulk updates or deletes
Using SqlUpdate or an ORM Update query clear the appropriate part of
the PersistenceContext. The effect is that ORM queries executed after
a bulk update will effectively load a fresh copy of the data from the
database and will not reuse an instance from the persistence context
if the bean in question had already been loaded.
2024-01-09 07:44:27 +13:00
Rob BygraveandGitHub 8ed3b765ec Merge pull request #3299 from ebean-orm/feature/3294-warnings
#3294 Suppress compiler warnings on generated query bean `filterMany()`
2023-12-22 08:33:31 +13:00
Rob BygraveandGitHub fcbcc53e27 Merge pull request #3298 from ebean-orm/feature/add-usingConnection-dtoQuery
Add usingConnection() to DtoQuery and SqlQuery
2023-12-22 08:25:48 +13:00
Rob Bygrave b377e1a618 #3294 Suppress compiler warnings on generated query bean filterMany() 2023-12-22 08:24:54 +13:00
Rob Bygrave a0f612ed71 Add usingConnection() to DtoQuery and SqlQuery
For the case where we have a java.sql.Connection and wish
to execute a DtoQuery or SqlQuery using that connection.
2023-12-21 21:24:02 +13:00
Roland Praml 6f64821584 Change semantic of userObjects in nested transaction 2023-12-08 14:50:30 +01:00
Rob Bygrave 47e97a77a8 Version 13.25.2 2023-12-07 20:18:40 +13:00
Rob Bygrave e8d3f50bb4 Bump ebean-agent to 13.25.2 2023-12-07 19:57:55 +13:00
Rob BygraveandGitHub 716cfaf938 Merge pull request #3286 from ebean-orm/feature/dbarray-instant-and-localdate
Add support for LocalDate and Instant with DbArray
2023-12-07 08:57:40 +13:00
robin.bygrave 7cd9e5ee03 Add support for LocalDate and Instant with DbArray 2023-12-06 14:54:30 +13:00
Rob Bygrave f9c9bea623 Follow up for #3248 - add betweenProperties on query bean 2023-12-06 00:40:57 +13:00
Rob Bygrave 720832122c Follow up for #3248 - add betweenProperties on query bean 2023-12-05 23:32:16 +13:00
Rob BygraveandGitHub 7b635acf56 Merge pull request #3284 from raphaelNguyen/master
Expose betweenProperties on query bean
2023-12-05 23:21:26 +13:00
Raphael Nguyen 6b7efe65d7 Expose betweenProperties on query bean 2023-12-05 15:08:16 +11:00
Rob BygraveandGitHub 03cd4000f0 Merge pull request #3282 from ebean-orm/dependabot/maven/ch.qos.logback-logback-classic-1.3.12
Bump ch.qos.logback:logback-classic from 1.2.11 to 1.3.12
2023-11-30 13:59:21 +13:00
Rob BygraveandGitHub dfd6434b59 Merge pull request #3281 from ebean-orm/dependabot/maven/tests/test-java16/ch.qos.logback-logback-classic-1.3.12
Bump ch.qos.logback:logback-classic from 1.2.11 to 1.3.12 in /tests/test-java16
2023-11-30 13:59:08 +13:00
Rob BygraveandGitHub 4e7480237b Merge pull request #3283 from ebean-orm/dependabot/maven/tests/test-kotlin/ch.qos.logback-logback-classic-1.3.12
Bump ch.qos.logback:logback-classic from 1.2.11 to 1.3.12 in /tests/test-kotlin
2023-11-30 13:58:52 +13:00
dependabot[bot]andGitHub 9bfcf07486 Bump ch.qos.logback:logback-classic in /tests/test-kotlin
Bumps [ch.qos.logback:logback-classic](https://github.com/qos-ch/logback) from 1.2.11 to 1.3.12.
- [Commits](https://github.com/qos-ch/logback/compare/v_1.2.11...v_1.3.12)

---
updated-dependencies:
- dependency-name: ch.qos.logback:logback-classic
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-29 22:15:53 +00:00
dependabot[bot]andGitHub b1f1344057 Bump ch.qos.logback:logback-classic from 1.2.11 to 1.3.12
Bumps [ch.qos.logback:logback-classic](https://github.com/qos-ch/logback) from 1.2.11 to 1.3.12.
- [Commits](https://github.com/qos-ch/logback/compare/v_1.2.11...v_1.3.12)

---
updated-dependencies:
- dependency-name: ch.qos.logback:logback-classic
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-29 22:13:26 +00:00
dependabot[bot]andGitHub 07201c1519 Bump ch.qos.logback:logback-classic in /tests/test-java16
Bumps [ch.qos.logback:logback-classic](https://github.com/qos-ch/logback) from 1.2.11 to 1.3.12.
- [Commits](https://github.com/qos-ch/logback/compare/v_1.2.11...v_1.3.12)

---
updated-dependencies:
- dependency-name: ch.qos.logback:logback-classic
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-29 22:13:04 +00:00
Rob BygraveandGitHub 455a9fdffc Merge pull request #3280 from ebean-orm/feature/typequery-imports-tqrootbean
QueryBean generation - use full class names for TQRootBean, TQAssocBean
2023-11-29 01:21:00 +13:00
Rob Bygrave 3f67425727 QueryBean generation - conditionally fully qualify the property types
If there is an entity bean short name clash like PString, PLong, etc then
fully qualify all the property types in the generated code, otherwise use
imports for the property types.
2023-11-29 00:46:56 +13:00
Rob Bygrave 3fd9ae06db QueryBean generation - use fully qualify use of DB 2023-11-29 00:22:45 +13:00
Rob Bygrave a8ce726e47 QueryBean generation - use full class names for TQRootBean, TQAssocBean
Rather than imports, such that these are not possible name clashes with
beans of the exact same name.
2023-11-28 21:51:07 +13:00
Rob BygraveandGitHub 29cd1a143d Merge pull request #3277 from ebean-orm/feature/bump-datasource2
Bump ebean-datasource to 8.11 with support for Driver by class
2023-11-23 23:34:23 +13:00
Rob Bygrave 6a19c6a0ce Bump ebean-datasource to 8.11 with support for Driver by class
- Can specify explicit driver by class or instance
- Can use a DataSource as connection source
2023-11-23 23:31:29 +13:00
Rob BygraveandGitHub eaec515cc1 Merge pull request #3276 from ebean-orm/feature/skipCheckForReadOnly
skipDataSourceCheck() when using readOnlyDatabase
2023-11-23 23:27:21 +13:00
Rob Bygrave 97709d3493 skipDataSourceCheck() when using readOnlyDatabase
As we don't want the warning logged in this case:
DataSource [{0}] has autoCommit defaulting to true!
2023-11-23 23:23:53 +13:00
Rob Bygrave 87ad874621 Read the readOnlyDatabase property via loadSettings() 2023-11-23 23:15:58 +13:00
Rob Bygrave dfe95f6fc0 Version 13.25.1 2023-11-22 17:50:09 +13:00
Rob Bygrave 05feccfeb6 Bump ebean-agent 2023-11-22 17:46:54 +13:00
Rob BygraveandGitHub 196cb09c66 Merge pull request #3274 from ebean-orm/feature/3269
#3268 - @DbComment on @ManyToOne fields are ignored (ddl-generator)
2023-11-21 23:54:26 +13:00
Rob Bygrave 589e198301 #3268 - @DbComment on @ManyToOne fields are ignored (ddl-generator) 2023-11-21 23:53:29 +13:00
Rob BygraveandGitHub b2b81677e8 Merge pull request #3273 from ebean-orm/feature/3269
#3269 - @JoinColumns set ForeignKey is none in ddl , but is not work
2023-11-21 23:42:06 +13:00
Rob Bygrave f032aad22e #3269 - @JoinColumns set ForeignKey is none in ddl , but is not work 2023-11-21 23:40:21 +13:00
Rob Bygrave c48e5428c5 #3265 Fix for Update Query logging to trim large values in bind log 2023-11-21 22:32:35 +13:00
Rob Bygrave cbca940611 Merge branch 'FOCONIS-findsingleattribute-beanfindcontroller' 2023-11-21 22:05:12 +13:00
Rob Bygrave 0da3772ae9 #3270 Fix for use with BeanFindController and attribute queries
The existence of a BeanFindController should not break the use of
single attribute queries + still allow auto-tuning.
2023-11-21 22:04:47 +13:00
Rob Bygrave 496ef36b11 Merge branch 'findsingleattribute-beanfindcontroller' of github.com:FOCONIS/ebean into FOCONIS-findsingleattribute-beanfindcontroller 2023-11-21 21:40:09 +13:00
Rob BygraveandGitHub a4a2aba56f Merge pull request #3272 from ebean-orm/feature/readOnlyDatabase
Refactor tidy internals of DbPrimary, DatabaseFactory, ContainerConfi…
2023-11-21 21:20:35 +13:00
Rob Bygrave 803f1d8642 Refactor tidy internals of DbPrimary, DatabaseFactory, ContainerConfig, ClusterManager 2023-11-20 22:18:53 +13:00
Rob BygraveandGitHub ff1c73e20d Merge pull request #3266 from ebean-orm/feature/readOnlyDatabase
Add read only database configuration/builder option
2023-11-17 14:10:51 +13:00
Noemi Praml 7afd37cd98 Failing Tests with CustomerFindController 2023-11-14 17:05:42 +01:00
Rob Bygrave 24bb364d40 Add read only database configuration/builder option
When using DatabaseBuilder.readOnlyDatabase(true) then
ebean will:
- Set the DataSourceBuilder to use autoCommit=true and readOnly=true
- Use the same DataSource instance for both dataSource and readOnlyDataSource

This is to simplify the setup/configuration for creating a Database that
will only have read-only use.

Note that readOnly=true is a JDBC hint and for example H2 database effectively
ignores that hint where as Postgres will enforce the read-only true nature.
2023-11-13 23:12:05 +13:00
Rob Bygrave 5d54a238bd Bump ebean-agent to 13.25.0 2023-11-06 20:09:35 +13:00
Rob Bygrave b50ce5fc3f Version 13.25.0 2023-11-06 20:08:00 +13:00
Rob Bygrave 624e92840c Adjust "for testing purposes" log messages 2023-11-06 12:55:22 +13:00
Rob Bygrave b03adc412c Adjust "for testing purposes" log messages 2023-11-06 12:52:35 +13:00
Rob BygraveandGitHub e794f5e916 Merge pull request #3264 from ebean-orm/feature/DatabaseBuilder_Settings
Fix to return DataSourceBuilder.Settings for getDataSourceConfig() an…
2023-11-06 12:50:37 +13:00
Rob Bygrave a2551ce718 Bump ebean-datasource to 8.9 2023-11-06 12:50:14 +13:00
Rob Bygrave 5b0a3607f6 Fix to return DataSourceBuilder.Settings for getDataSourceConfig() and getReadOnlyDataSourceConfig()
That is, existing code using DataSourceConfig has access to the getter
methods of DataSourceConfig. The DataSourceBuilder interface only has
the setter methods and DataSourceBuilder.Settings has both getters and
setter methods.

That is, the refactor to extract the DataSourceBuilder interface also
split off the getter methods to the DataSourceBuilder.Settings interface
(because most of the time when using the builder we only need the
setter methods and effectively hiding the getter methods behind the settings()
is useful to simplify the API for users).
2023-11-06 12:14:27 +13:00
Rob Bygrave bcf7bd17be Version 13.14.0-jakarta 2023-11-05 22:21:20 +13:00
Rob BygraveandGitHub 102d8d5979 Merge pull request #3263 from ebean-orm/feature/DatabaseBuilder-take-2
DatabaseBuilder take 2
2023-11-05 22:11:26 +13:00
Rob Bygrave 3edc232003 Update test BeanDescriptor_registerTest with DatabaseBuilder use 2023-11-05 22:03:25 +13:00
Rob Bygrave 043dc5c51f Add setters without the set prefix to DatabaseBuilder with deprecation
So add `name(String name)` as preferred to `setName(String name)` etc
2023-11-05 22:01:02 +13:00
Rob Bygrave e2d666df35 Use fluid setters for DatabaseConfig and DatabaseBuilder 2023-11-04 13:05:22 +13:00
Rob Bygrave 314e0a14b8 Move the internal serviceObjectKey() methods back into DatabaseConfig
They were incorrectly extracted to the interface as default methods
2023-11-03 23:00:29 +13:00
Rob Bygrave 1f9cf1e4b7 Split DatabaseBuilder interface separating the setters n getters adding DatabaseBuilder.Settings
So DatabaseBuilder.Settings has all the getters for code looking to read
the configuration that has been set. So DatabaseBuilder now just has the
setter methods.

Use DatabaseBuilder.settings() to access the settings and read the config
that has been set.
2023-11-03 22:58:11 +13:00
Rob Bygrave 12029ed06e Refactor extract interface DatabaseBuilder from DatabaseConfig
First step in supporting the builder pattern for creating Database
2023-11-03 21:17:55 +13:00
Rob BygraveandGitHub 89741b9312 Merge pull request #3262 from ebean-orm/feature/improve-javadoc-deprecated
Improve the javadoc for deprecated methods (to assist IDE quick-fix actions)
2023-11-03 20:05:41 +13:00
Rob Bygrave ae962c2e08 Improve the javadoc for deprecated methods (to assist IDE quick-fix actions) 2023-11-03 20:04:25 +13:00
Rob BygraveandGitHub 4e3501972a Merge pull request #3260 from ebean-orm/feature/bump-migration2
Bump ebean-migration to 13.11.1 (with fastMode option and index file support)
2023-11-03 19:52:00 +13:00
Rob Bygrave a65ba41850 Bump ebean-migration to 13.11.1 (with fastMode option and index file support) 2023-11-03 18:33:02 +13:00
Rob Bygrave 3b11c1cb6b Merge branch 'master' of github.com:ebean-orm/ebean 2023-11-03 18:31:31 +13:00
Rob Bygrave 41185eeb5c Bump ebean-datasource to 8.8 with DataSourceBuilder
First step in migrating the ebean-datasource API to use builder pattern.
DataSourceConfig (concrete type) migrating to DataSourceBuilder (interface).

A followup step will deprecate the use of DataSourceConfig.
2023-11-03 18:31:11 +13:00
Rob BygraveandGitHub e97ff54ab2 Merge pull request #3259 from ebean-orm/feature/loadMode_safer
Change loadMode to be 'safer' (for Grafana etc). e.g. change "(+lazy) " to "__lazy"
2023-11-02 09:00:38 +13:00
robin.bygrave 97fae09c52 Tidy SpiQuery.setProfilePath() internal implementation 2023-11-01 15:48:27 +13:00
robin.bygrave 8b0f58b3c2 Change loadMode to be 'safer' (for Grafana etc). e.g. change "(+lazy)" to "__lazy"
The loadMode ends up as a suffix to some query metrics.

For example "foo.findIt_baz(+lazy)", and the (+lazy) part isn't safe/friendly to tools
like Grafana. So change to instead of (+lazy) use __lazy.
2023-11-01 15:20:18 +13:00
Rob Bygrave 70eb557929 Version 13.23.2-jakarta 2023-10-27 22:13:05 +13:00
Rob Bygrave fdb3a3759b Bump ebean-agent to 13.23.2 2023-10-27 22:10:40 +13:00
Rob BygraveandGitHub 7a5e8d0e17 Merge pull request #3256 from ebean-orm/feature/upgrade-antlr4-4_13_1
Upgrade ANTLR4 from version 4.8-1 to 4.13.1
2023-10-27 21:45:37 +13:00
robin.bygrave a0748f8139 Upgrade ANTLR4 from version 4.8-1 to 4.13.1 2023-10-26 13:52:44 +13:00
Rob BygraveandGitHub 9f65673f54 Merge pull request #3255 from ebean-orm/feature/bump-junit-bytebuddy
Bump io.avaje:junit and bytebuddy version to support JDK 22+
2023-10-25 22:12:49 +13:00
Rob Bygrave 8f6a3c59d1 Bump io.avaje:junit and bytebuddy version to support JDK 22+ 2023-10-25 21:58:19 +13:00
Rob BygraveandGitHub 05210ec411 Merge pull request #3254 from ebean-orm/feature/query-plan-capture-yuga
Use DIST with query plan capture for Yugabyte plus simplify
2023-10-25 08:23:01 +13:00
Rob Bygrave faffda8318 Use DIST with query plan capture for Yugabyte plus simplify
Change QueryPlanLoggerExplain to take the options for PG, Yugabyte and others
2023-10-25 08:22:25 +13:00
Rob BygraveandGitHub af3901ce01 Merge pull request #3253 from ebean-orm/feature/3251
#3251 - QueryBeans: Entities can not have same name as some Ebean API…
2023-10-25 08:11:40 +13:00
Rob Bygrave acd538207f #3251 - QueryBeans: Entities can not have same name as some Ebean API classes 2023-10-24 23:08:30 +13:00
Rob Bygrave 84f0ef9fce Use querybean-generator via provided scope rather than maven compiler plugin
This is because when releasing both jakarta and javax versions these
need to have their versions adjusted
2023-10-24 23:07:14 +13:00
Rob BygraveandGitHub 7ab447b21c Merge pull request #3252 from ebean-orm/feature/querybean-generator-provided
Use querybean-generator via provided scope rather than maven compiler plugin
2023-10-24 22:23:56 +13:00
Rob Bygrave 6f8805a6b3 Use querybean-generator via provided scope rather than maven compiler plugin
This is because when releasing both jakarta and javax versions these
need to have their versions adjusted
2023-10-24 22:17:28 +13:00
Rob Bygrave 0171c1afef Version 13.23.1 2023-10-18 15:47:04 +13:00
Rob Bygrave 31c106f604 Bump ebean-agent to 13.23.1 2023-10-18 15:16:20 +13:00
Rob BygraveandGitHub 20d2838be4 Merge pull request #3250 from ebean-orm/feature/bump-parent
Make Jackson a transitive dependency of ebean-jackson-mapper
2023-10-17 23:25:43 +13:00
Rob Bygrave 4238a951ca Make Jackson a transitive dependency of ebean-jackson-mapper
So jackson-core and jackson-databind are both transitive dependencies
of ebean-jackson-mapper.
2023-10-17 23:25:09 +13:00
Rob BygraveandGitHub b5d4bed615 Merge pull request #3249 from ebean-orm/feature/bump-parent
Support native-image via querybean-generator
2023-10-17 23:18:17 +13:00
Rob Bygrave 3ef715ef64 Support native-image via querybean-generator 2023-10-17 23:09:18 +13:00
Rob BygraveandGitHub aea39528ab Merge pull request #3248 from ebean-orm/feature/bump-parent
Bump dependency for avaje-config to 3.9
2023-10-17 22:39:04 +13:00
Rob Bygrave dd498409e0 Bump dependency for avaje-config to 3.9 2023-10-17 22:38:33 +13:00
Rob BygraveandGitHub bae33101df Merge pull request #3247 from ebean-orm/feature/bump-parent
Bump parent pom
2023-10-17 22:37:53 +13:00
Rob Bygrave e1972ac544 Bump parent pom 2023-10-17 22:37:20 +13:00
Rob Bygrave c7241ba3dc Fix test for java 16+ annotation processor version 2023-10-16 23:30:45 +13:00
Rob Bygrave 73416ed65a For testing java 16+ include JDK 17 and 21 only 2023-10-16 23:19:48 +13:00
Rob Bygrave cd70c178f1 For testing java 16+ include JDK 17 and 21 only 2023-10-16 23:17:25 +13:00
Rob Bygrave aa298235f3 For testing java 16+ include JDK 21 and 22 2023-10-16 23:15:32 +13:00
Rob BygraveandGitHub 8733fed14b Merge pull request #3246 from ebean-orm/feature/annotation-processing-jdk-22
Explicit annotation processors required with JDK 22
2023-10-16 22:06:20 +13:00
Rob Bygrave 169d170247 Explicit annotation processors required with JDK 22
JDK 22 changes such that annotation processors are not found by default on
the classpath. As such they either need to be explicitly registered with
the compiler (e.g. maven-compiler-plugin) or use -proc:full
2023-10-16 21:54:32 +13:00
Rob Bygrave d0ee42e0de Include <compilerArgument>-proc:full</compilerArgument> for JDK 22 EA build 2023-10-16 20:32:41 +13:00
Rob BygraveandGitHub 91ecc074a7 Merge pull request #3243 from ebean-orm/feature/postgis-dependency
Fix ebean-bom dependencies for ebean-test
2023-10-11 20:04:12 +13:00
Rob Bygrave c2b381af1e Fix ebean-bom dependencies for ebean-test
Fix by removing the scopes test and provided in the ebean-bom
2023-10-11 20:03:12 +13:00
Rob BygraveandGitHub eeb0a15617 Merge pull request #3242 from ebean-orm/feature/postgis-dependency
Add missing dependency for ebean-postgis-types to ebean-postgis
2023-10-11 19:59:48 +13:00
Rob Bygrave 6abed0dd73 Add missing dependency for ebean-postgis-types to ebean-postgis 2023-10-11 19:58:12 +13:00
1363 changed files with 61387 additions and 11938 deletions
+9 -5
View File
@@ -1,7 +1,11 @@
name: Build
on: [push, pull_request]
on:
workflow_dispatch:
pull_request:
push:
branches: master
jobs:
build:
@@ -17,14 +21,14 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'zulu'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
@@ -36,5 +40,5 @@ jobs:
# - name: Maven single test
# run: mvn --batch-mode clean verify -Dtest="io.ebeaninternal.server.core.DefaultServer_getReferenceTest" -DfailIfNoTests=false
- name: Build with Maven
run: mvn -T 8 clean test
run: mvn -T 8 clean test -Pdefault
+3 -3
View File
@@ -20,14 +20,14 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'adopt'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
+3 -3
View File
@@ -20,14 +20,14 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'zulu'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
+3 -3
View File
@@ -20,14 +20,14 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: oracle-actions/setup-java@v1
with:
website: jdk.java.net
release: ${{ matrix.java_version }}
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
@@ -37,5 +37,5 @@ jobs:
- name: Maven version
run: mvn --version
- name: Build with Maven
run: mvn -T 8 test
run: mvn test -Pea
+4 -4
View File
@@ -20,19 +20,19 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'adopt'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
path:
~/.m2
key: build-${{ env.cache-name }}
- name: mariadb 10.6
- name: mariadb 10.11
run: mvn -T 8 clean test -Dprops.file=testconfig/ebean-mariadb.properties
+3 -3
View File
@@ -17,14 +17,14 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'adopt'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
+5 -3
View File
@@ -20,20 +20,22 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'zulu'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
path:
~/.m2
key: build-${{ env.cache-name }}
- name: Maven version
run: mvn --version
- name: Build with Maven
run: mvn package
+3 -3
View File
@@ -20,14 +20,14 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'adopt'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
+3 -3
View File
@@ -20,14 +20,14 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'zulu'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
+3 -3
View File
@@ -20,14 +20,14 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'adopt'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
+3 -3
View File
@@ -17,14 +17,14 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'adopt'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
+5 -5
View File
@@ -20,19 +20,19 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'adopt'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
path:
~/.m2
key: build-${{ env.cache-name }}
- name: sqlserver 2017
run: mvn -T 8 clean test -Dprops.file=testconfig/ebean-sqlserver17.properties
- name: sqlserver 2022
run: mvn -T 8 clean test -Dprops.file=testconfig/ebean-sqlserver.properties
+41
View File
@@ -0,0 +1,41 @@
name: Valhalla EA
on:
workflow_dispatch:
schedule:
- cron: '39 2 * * 3'
jobs:
build:
runs-on: ${{ matrix.os }}
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
java_version: [valhalla]
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v4
- name: Set up Java
uses: oracle-actions/setup-java@v1
with:
website: jdk.java.net
release: ${{ matrix.java_version }}
- name: Maven cache
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
path:
~/.m2
key: build-${{ env.cache-name }}
- name: Maven version
run: mvn --version
# - name: Prepare
# run: ./jakarta-to-valhalla.sh
- name: Build with Maven
run: mvn package
+4 -4
View File
@@ -4,7 +4,7 @@ name: Yugabyte
on:
workflow_dispatch:
schedule:
- cron: '10 3 * * *'
- cron: '10 3 * * 3'
jobs:
build:
@@ -20,14 +20,14 @@ jobs:
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java_version }}
distribution: 'adopt'
- name: Maven cache
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: maven-cache
with:
+14 -6
View File
@@ -3,6 +3,7 @@
[![Maven Central : ebean](https://maven-badges.herokuapp.com/maven-central/io.ebean/ebean/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.ebean/ebean)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/ebean-orm/ebean/blob/master/LICENSE)
[![Multi-JDK Build](https://github.com/ebean-orm/ebean/actions/workflows/multi-jdk-build.yml/badge.svg)](https://github.com/ebean-orm/ebean/actions/workflows/multi-jdk-build.yml)
[![GraalVM Native Image](https://img.shields.io/badge/GraalVM-Native%20Image%20Ready-darkgreen?logo=graalvm)](https://www.graalvm.org/)
##### Build with database platforms
[![H2Database](https://github.com/ebean-orm/ebean/actions/workflows/h2database.yml/badge.svg)](https://github.com/ebean-orm/ebean/actions/workflows/h2database.yml)
@@ -56,12 +57,7 @@ Work at the highest level of abstraction and drop down levels as needed.
<tr>
<td align="center" valign="middle">
<a href="https://www.foconis.de/" target="_blank">
<img width="222px" src="https://www.foconis.de/templates/yootheme/cache/foconis_logo_322-709da1de.png">
</a>
</td>
<td align="center" valign="middle">
<a href="https://www.payintech.com/" target="_blank">
<img width="222px" src="https://ebean.io/images/sponsor_PayinTech-logo-noir.png">
<img width="222px" src="https://group.foconis.com/download/ci/logo/png-72dpi/logo-quer/foconis-analytics-quer.png">
</a>
</td>
<td align="center" valign="middle">
@@ -85,6 +81,18 @@ or [github discussions](https://github.com/ebean-orm/ebean/discussions)
## Documentation
Goto [https://ebean.io/docs/](https://ebean.io/docs/)
## Guides
Library reference (capabilities, scope, and AI guidance): [docs/LIBRARY.md](docs/LIBRARY.md)
Step-by-step guides for common tasks: [docs/guides/](docs/guides/README.md)
Available guides:
- [Maven POM setup](docs/guides/add-ebean-postgres-maven-pom.md)
- [Database configuration](docs/guides/add-ebean-postgres-database-config.md)
- [Test container setup](docs/guides/add-ebean-postgres-test-container.md)
- [DB migration generation](docs/guides/add-ebean-db-migration-generation.md)
- [Lombok with Ebean entity beans](docs/guides/lombok-with-ebean-entity-beans.md)
## Maven central
[Maven central - g:io.ebean](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22io.ebean%22%20)
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-clickhouse</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-postgres</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-db2</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-h2</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-hana</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-mariadb</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-mysql</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+85
View File
@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
<name>ebean-net-postgis</name>
<description>ebean-net-postgis composite</description>
<artifactId>ebean-net-postgis</artifactId>
<properties>
<postgis.jdbc.version>2023.1.0</postgis.jdbc.version>
<postgres.jdbc.version>42.7.2</postgres.jdbc.version>
</properties>
<dependencies>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-datasource</artifactId>
<version>${ebean-datasource.version}</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-migration</artifactId>
<version>${ebean-migration.version}</version>
</dependency>
<!-- Technically optional but most expected to use query beans -->
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-postgres</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-net-postgis-types</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgres.jdbc.version}</version>
<exclusions>
<!-- exclude unnecessary checker framework -->
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.postgis</groupId>
<artifactId>postgis-jdbc</artifactId>
<version>${postgis.jdbc.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,7 @@
package io.ebean.postgis.assembly;
/**
* Nothing interesting here - required placeholder for javadoc.
*/
public class Assembly {
}
@@ -0,0 +1,10 @@
module io.ebean.postgis {
requires transitive io.ebean.api;
requires transitive io.ebean.core;
requires transitive io.ebean.datasource;
requires transitive io.ebean.querybean;
requires transitive io.ebean.platform.postgres;
// requires transitive io.ebean.postgis.types;
}
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-nuodb</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-oracle</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+85
View File
@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
<name>ebean-pgvector</name>
<description>ebean-pgvector composite</description>
<artifactId>ebean-pgvector</artifactId>
<properties>
<pgvector.version>0.1.6</pgvector.version>
<postgres.jdbc.version>42.7.2</postgres.jdbc.version>
</properties>
<dependencies>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-datasource</artifactId>
<version>${ebean-datasource.version}</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-migration</artifactId>
<version>${ebean-migration.version}</version>
</dependency>
<!-- Technically optional but most expected to use query beans -->
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-postgres</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-pgvector-types</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgres.jdbc.version}</version>
<exclusions>
<!-- exclude unnecessary checker framework -->
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.pgvector</groupId>
<artifactId>pgvector</artifactId>
<version>${pgvector.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,7 @@
package io.ebean.pgvector.assembly;
/**
* Nothing interesting here - required placeholder for javadoc.
*/
public class Assembly {
}
@@ -0,0 +1,9 @@
module io.ebean.pgvector {
requires transitive io.ebean.api;
requires transitive io.ebean.core;
requires transitive io.ebean.datasource;
requires transitive io.ebean.querybean;
requires transitive io.ebean.platform.postgres;
}
+12 -6
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -14,7 +14,7 @@
<properties>
<postgis.jdbc.version>2.5.1</postgis.jdbc.version>
<postgres.jdbc.version>42.6.0</postgres.jdbc.version>
<postgres.jdbc.version>42.7.2</postgres.jdbc.version>
</properties>
<dependencies>
@@ -22,13 +22,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -47,13 +47,19 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-postgres</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-postgis-types</artifactId>
<version>16.10.0</version>
</dependency>
<dependency>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-postgres</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-sqlite</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-sqlserver</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,13 +17,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -42,13 +42,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-postgres</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+8 -8
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
<relativePath>../..</relativePath>
</parent>
@@ -17,31 +17,31 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-api</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-core</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-joda-time</artifactId>
<version>13.18.0</version>
<version>14.0.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-jackson-jsonnode</artifactId>
<version>13.18.0</version>
<version>14.0.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-jackson-mapper</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
@@ -60,13 +60,13 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-querybean</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-platform-all</artifactId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</dependency>
</dependencies>
+3 -1
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</parent>
<artifactId>composites</artifactId>
@@ -24,6 +24,8 @@
<module>ebean-oracle</module>
<module>ebean-postgres</module>
<module>ebean-postgis</module>
<module>ebean-net-postgis</module>
<module>ebean-pgvector</module>
<!-- <module>sqlanywhere</module>-->
<module>ebean-sqlite</module>
<module>ebean-sqlserver</module>
+248
View File
@@ -0,0 +1,248 @@
# Ebean ORM Library Definition
Ebean is an ORM library for Java and Kotlin focused on relational data access, type-safe query construction, and production-friendly SQL behavior.
## Identity
- **Name**: Ebean ORM
- **Package**: `io.ebean`
- **Primary Maven Group**: `io.ebean`
- **Category**: ORM / Data Access
- **Repository**: https://github.com/ebean-orm/ebean
- **Issues**: https://github.com/ebean-orm/ebean/issues
- **Discussions**: https://github.com/ebean-orm/ebean/discussions
- **Website**: https://ebean.io/
- **Documentation**: https://ebean.io/docs/
- **License**: Apache 2.0
## Version & Requirements
- **Repository Version (this checkout)**: `16.5.0` (from repository `pom.xml`)
- **Minimum Java Version**: 11+
- **Languages**: Java, Kotlin
- **Build Tooling in this docs set**: Maven-focused examples
## Core Artifacts
| Artifact | Purpose |
|------|------|
| `io.ebean:ebean` | Core ORM runtime and API |
| `io.ebean:ebean-postgres` | PostgreSQL platform bundle used in setup guides |
| `io.ebean:ebean-test` | Test support, including Docker-backed database testing |
| `io.ebean:querybean-generator` | Generates `Q*` type-safe query beans |
| `io.ebean:ebean-maven-plugin` | Bytecode enhancement for entities at build time |
| `io.ebean:ebean-migration` | Runtime migration runner (often transitive via platform artifact) |
## Core APIs & Annotations
### Database and transaction APIs
| API | Purpose | Example |
|------|------|------|
| `DB.getDefault()` | Access default `Database` | `Database db = DB.getDefault();` |
| `DB.byName("...")` | Access named `Database` | `Database reporting = DB.byName("reporting");` |
| `database.find(...)` | Query entities | `Customer c = database.find(Customer.class, id);` |
| `database.insert/save/update/delete` | Persist entity changes | `database.save(customer);` |
| `database.beginTransaction()` | Manual transaction boundary | `try (Transaction txn = database.beginTransaction()) { ... }` |
| `Database.builder()` | Programmatic `Database` setup | `Database.builder().loadFromProperties().build();` |
### Query APIs
| API | Purpose | Example |
|------|------|------|
| `Q*` query beans | Type-safe query construction | `new QCustomer().status.equalTo(ACTIVE).findList();` |
| `exists()` | Efficient existence checks | `new QCustomer().email.equalTo(email).exists();` |
| `findOne()` | Unique/single-row retrieval | `new QCustomer().id.equalTo(id).findOne();` |
| `findList()` | List retrieval | `new QCustomer().findList();` |
| `asDto(...).findList()` | DTO projection reads | `new QOrder().asDto(OrderSummary.class).findList();` |
### Entity mapping and lifecycle annotations
| Annotation | Purpose |
|------|------|
| `@Entity` | Marks class as persistent entity |
| `@Id` | Primary key mapping |
| `@Version` | Optimistic locking |
| `@WhenCreated` | Creation timestamp management |
| `@WhenModified` | Modification timestamp management |
| `@Transactional` | Declarative transaction boundary |
## Capabilities
### ✅ Included
- Relational ORM with automatic dirty checking and lazy loading (via enhancement)
- Multiple query abstraction levels (ORM query, DTO query, SQL/JDBC)
- Type-safe query beans (`Q*`) with IDE autocomplete
- Built-in migration generation and migration running support
- Transaction APIs for implicit, declarative, and explicit transaction control
- Support for test-time Docker database workflows
- Query tuning and caching features for performance-sensitive workloads
### ❌ Not in scope
- HTTP routing, REST controllers, or web server runtime
- Dependency injection container functionality
- JSON serialization framework responsibilities
- Front-end/UI rendering concerns
Ebean is intentionally focused on persistence and data access. Pair it with a web framework and DI library as needed.
## Use Cases
### ✅ Strong fit
- SQL-backed business applications with rich domain models
- Services that need both ORM productivity and SQL-level control
- Projects requiring type-safe query authoring via generated query beans
- Teams that want migration generation integrated with entity model changes
- Integration test suites that need real database behavior (not only in-memory mocks)
### ⚠️ Consider alternatives if
- You need a full web framework (routing/controllers) rather than a persistence layer
- Your project does not use relational databases as a core storage model
- You want a single library to cover persistence, DI, and HTTP all at once
## Quick Start (Maven)
```xml
<properties>
<ebean.version><!-- use latest stable from Maven Central --></ebean.version>
</properties>
<dependencies>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-postgres</artifactId>
<version>${ebean.version}</version>
</dependency>
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-test</artifactId>
<version>${ebean.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.ebean</groupId>
<artifactId>ebean-maven-plugin</artifactId>
<version>${ebean.version}</version>
<extensions>true</extensions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>io.ebean</groupId>
<artifactId>querybean-generator</artifactId>
<version>${ebean.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
```
## Minimal Example
```java
import io.ebean.DB;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
class Customer {
@Id
private long id;
private String name;
public void setName(String name) {
this.name = name;
}
}
Database database = DB.getDefault(); // or injected
Customer customer = database.find(Customer.class, 42);
customer.setName("Updated");
database.save(customer);
```
## Common Tasks & Guides
| Task | Guide |
|------|------|
| Add Ebean to an existing Maven project | [add-ebean-postgres-maven-pom.md](guides/add-ebean-postgres-maven-pom.md) |
| Configure database and `Database` bean | [add-ebean-postgres-database-config.md](guides/add-ebean-postgres-database-config.md) |
| Add PostgreSQL test container support | [add-ebean-postgres-test-container.md](guides/add-ebean-postgres-test-container.md) |
| Generate DB migrations | [add-ebean-db-migration-generation.md](guides/add-ebean-db-migration-generation.md) |
| Model entity beans correctly | [entity-bean-creation.md](guides/entity-bean-creation.md) |
| Use Lombok safely with entities | [lombok-with-ebean-entity-beans.md](guides/lombok-with-ebean-entity-beans.md) |
| Write type-safe query bean queries | [writing-ebean-query-beans.md](guides/writing-ebean-query-beans.md) |
| Persist changes and manage transactions | [persisting-and-transactions-with-ebean.md](guides/persisting-and-transactions-with-ebean.md) |
| Build test entities quickly | [testing-with-testentitybuilder.md](guides/testing-with-testentitybuilder.md) |
**Guides index**: [guides/README.md](guides/README.md)
## Related Ecosystem Docs
- [Creating DataSource Pools](https://github.com/ebean-orm/ebean-datasource/blob/master/docs/guides/create-datasource-pool.md)
- [AWS Aurora Read-Write Split](https://github.com/ebean-orm/ebean-datasource/blob/master/docs/guides/aws-aurora-read-write-split.md)
- [Connection Validation Best Practices](https://github.com/ebean-orm/ebean-datasource/blob/master/docs/guides/connection-validation-best-practices.md)
## AI Agent Instructions
### For Claude, GPT, and web-based agents
Use this file as the top-level reference when answering Ebean questions.
1. Check this file first for scope and capability fit.
2. Route implementation tasks to the relevant guide in **Common Tasks & Guides**.
3. Treat Ebean as the persistence layer only; avoid implying it provides HTTP/DI features.
4. Prefer type-safe query bean examples when showing query code.
5. For setup and migration changes, follow the Maven-focused guide steps exactly.
### For IDE-based agents (Copilot, Cursor, etc.)
If `docs/LIBRARY.md` is not in context automatically:
1. Read `README.md` for docs entry points.
2. Open `docs/guides/README.md` for task-specific guides.
3. Follow linked guide files directly for concrete implementation steps.
---
## Notes for Maintainers
### When to update this file
- New release that changes requirements or key APIs
- New guide added to `docs/guides/`
- Capability/scope changes that affect "Included" or "Not in scope"
- Significant migration or setup workflow changes
### Maintenance checklist
- [ ] Keep requirements and version references accurate
- [ ] Keep Common Tasks table aligned with `docs/guides/README.md`
- [ ] Keep artifact names/snippets aligned with setup guides
- [ ] Keep AI instructions aligned with current docs structure
### Link from repository README
In `README.md`, include:
```markdown
## Documentation
- [Ebean docs](https://ebean.io/docs/)
- [Library reference](docs/LIBRARY.md)
- [Step-by-step guides](docs/guides/README.md)
```
+23
View File
@@ -0,0 +1,23 @@
# AGENTS.md — Ebean ORM
This project uses [Ebean ORM](https://ebean.io).
## AI Agent Instructions
Step-by-step guides for common Ebean tasks (Maven setup, database config, query writing, transactions, test containers, DB migrations, Lombok) are at:
**https://github.com/ebean-orm/ebean/tree/HEAD/docs/guides/**
Key guides (fetch and follow when performing the relevant task):
- Maven POM setup: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-postgres-maven-pom.md
- Database configuration: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-postgres-database-config.md
- Migrate to `Database.builder()`: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/migrating-to-database-builder.md
- Write queries with query beans: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/writing-ebean-query-beans.md
- Persisting and transactions: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/persisting-and-transactions-with-ebean.md
- Query metrics and naming: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/ebean-query-metrics.md
- Query plan capture: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/ebean-query-plan-capture.md
- Test container setup: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-postgres-test-container.md
- DB migration generation: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-db-migration-generation.md
- Lombok with entity beans: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/lombok-with-ebean-entity-beans.md
Agents: Before performing any Ebean-related task, fetch and follow the relevant guide above.
+201
View File
@@ -0,0 +1,201 @@
# Guides
See also: [AGENTS.md](AGENTS.md) — a minimal template for AI agent onboarding and automation in Ebean ORM projects.
Step-by-step guides written as instructions for AI agents and developers.
For a high-level capability reference (scope, core APIs, and AI guidance), see
[../LIBRARY.md](../LIBRARY.md).
## Adding Ebean ORM with PostgreSQL to an existing Maven project
A three-part guide covering everything needed to wire Ebean + PostgreSQL into an
existing Maven project. Complete the steps in order.
| Step | Guide | Description |
|------|-------|-------------|
| 1 | [Maven POM setup](add-ebean-postgres-maven-pom.md) | Add Ebean dependencies, the enhancement plugin, and the querybean-generator annotation processor to `pom.xml` |
| 2 | [Test container setup](add-ebean-postgres-test-container.md) | Start a PostgreSQL (or PostGIS) Docker container for tests using `@TestScope @Factory` with Avaje Inject; verify the test database works with `mvn verify` before adding production configuration |
| 3 | [Database configuration](add-ebean-postgres-database-config.md) | Configure the production Ebean `Database` bean using `DataSourceBuilder` and `DatabaseBuilder` with Avaje Inject |
## Migration & upgrades
| Guide | Description |
|-------|-------------|
| [Migrate to `Database.builder()`](migrating-to-database-builder.md) | Replace legacy `new DatabaseConfig()` and `DatabaseFactory.create(...)` code with `Database.builder()` and `DatabaseBuilder.build()`. Includes common rewrites, fluent builder equivalents, and manual-review cases for semi-automated upgrades |
## Observability
| Guide | Description |
|-------|-------------|
| [Ebean OpenTelemetry tracing](add-ebean-opentelemetry.md) | Add `ebean-opentelemetry`, register `GlobalOpenTelemetry` once before Ebean databases are built, and troubleshoot missing spans or double-registration errors |
| [Ebean query metrics and naming](ebean-query-metrics.md) | How Ebean query metric names are derived from `setLabel(..)` and profile locations; secondary (lazy/query) load naming; inline SQL comments; collecting metrics at runtime; mapping to avaje-metrics tags |
| [Ebean query plan capture](ebean-query-plan-capture.md) | Enable and configure database query plan (`EXPLAIN`) capture for slow queries; bind capture vs plan capture; periodic and on-demand collection; thresholds, load limits, EXPLAIN dialect, and listeners |
## Entity beans
| Guide | Description |
|-------|-------------|
| [Entity Bean Creation](entity-bean-creation.md) | How to generate clean, idiomatic Ebean entity beans for AI agents; patterns and anti-patterns; field visibility and accessor guidance; minimal boilerplate |
| [Lombok with Ebean entity beans](lombok-with-ebean-entity-beans.md) | Which Lombok annotations to use and avoid on entity beans; why `@Data` is incompatible with Ebean; how to use `@Getter` + `@Setter` + `@Accessors(chain = true)` |
## Querying
| Guide | Description |
|-------|-------------|
| [Write Ebean queries with query beans](writing-ebean-query-beans.md) | Step-by-step guidance for AI agents to write type-safe Ebean queries; choose the right terminal method; tune `select()` / `fetch()` / `fetchQuery()`; and project to DTOs when entity beans are not the right output |
| [Immutable bean cache for read-only references](immutable-bean-cache.md) | Use `ImmutableBeanCache` and `ImmutableBeanCaches.loading(...)` to resolve assoc-one references in read-only/unmodifiable queries, including secondary `fetchQuery`/`fetchLazy` loads |
## Persisting & transactions
| Guide | Description |
|-------|-------------|
| [Persisting and transactions with Ebean](persisting-and-transactions-with-ebean.md) | Step-by-step guidance for AI agents to choose `insert` / `save` / `update` / `delete`; inspect cascades; select the right transaction boundary; and use batch or bulk update for large write sets |
## Testing
| Guide | Description |
|-------|-------------|
| [Testing with TestEntityBuilder](testing-with-testentitybuilder.md) | Rapidly create test entity instances with auto-populated random values; manage relationships and cascades; customize value generation for domain-specific testing needs |
## Database migrations
| Guide | Description |
|-------|-------------|
| [DB migration generation](add-ebean-db-migration-generation.md) | Add `GenerateDbMigration.java` to generate schema diff migrations offline; configure the migration runner; understand `.sql` and `.model.xml` output files; workflow for pending drops |
## Connection Pooling & DataSource Configuration
The [ebean-datasource](https://github.com/ebean-orm/ebean-datasource) project provides
comprehensive guides on connection pool configuration and best practices. These are particularly
useful for production deployments, especially in Kubernetes or AWS environments:
| Guide | Description |
|-------|-------------|
| [Creating DataSource Pools](https://github.com/ebean-orm/ebean-datasource/blob/master/docs/guides/create-datasource-pool.md) | Step-by-step guide for basic, read-only, Kubernetes, and AWS Lambda datasource configurations |
| [AWS Aurora Read-Write Split](https://github.com/ebean-orm/ebean-datasource/blob/master/docs/guides/aws-aurora-read-write-split.md) | Setting up dual DataSources with Aurora read and write endpoints for Ebean integration |
| [Connection Validation Best Practices](https://github.com/ebean-orm/ebean-datasource/blob/master/docs/guides/connection-validation-best-practices.md) | Understanding connection heartbeat strategies and why `Connection.isValid()` is the recommended approach |
---
## Helping AI agents find these guides
### Agent Skills (recommended)
The **ebean-orm skill** packages these guides into a structured format that AI agents
load on-demand. See the [ebean-orm/skills](https://github.com/ebean-orm/skills) repo
for installation instructions. Quick start:
```bash
git clone git@github.com:ebean-orm/skills.git ~/.agents/ebean-skills
mkdir -p ~/.agents/skills
ln -sf ~/.agents/ebean-skills/ebean-orm ~/.agents/skills/ebean-orm
```
This works with [pi](https://github.com/mariozechner/pi-coding-agent),
[Claude Code](https://docs.anthropic.com/en/docs/claude-code), and any harness
that supports the [Agent Skills standard](https://agentskills.io/specification).
### Other approaches
AI coding agents can only follow these guides if they know they exist. Below are
copy-paste snippets for the most common AI tooling configurations. Add whichever
applies to your project.
### llms.txt (fastest bootstrap for any agent)
`https://ebean.io/llms.txt` provides a concise Ebean capability reference and links
to all guides in a format optimised for LLMs. Agents that check `llms.txt` before
starting work will find everything they need without requiring project-level
configuration. This is worth knowing if you are an AI agent reading this file.
### Project `README.md` (universal — works with all AI tools)
Add a section near the top of your project README:
```markdown
## AI Agent Instructions
This project uses [Ebean ORM](https://ebean.io). Step-by-step guides for common
Ebean tasks (Maven setup, database configuration, query writing, transactions,
test containers, DB migrations, Lombok) are at:
**https://github.com/ebean-orm/ebean/tree/HEAD/docs/guides/**
AI agents should fetch and follow the relevant guide before performing Ebean-related
tasks.
```
### Why README is important
Many AI agents (Copilot, Claude, Cursor, Aider) read the project `README.md`
automatically as part of understanding the codebase. A visible link in README is the
most universally effective way to ensure any agent working on your project will
discover the guides without requiring tool-specific configuration files.
------
### GitHub Copilot — `.github/copilot-instructions.md`
```markdown
## Ebean ORM
This project uses [Ebean ORM](https://ebean.io). Step-by-step guides for common
tasks are at: https://github.com/ebean-orm/ebean/tree/HEAD/docs/guides/
Key guides (fetch and follow these when performing the relevant task):
- Maven POM setup: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-postgres-maven-pom.md
- Database configuration: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-postgres-database-config.md
- Migrate to `Database.builder()`: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/migrating-to-database-builder.md
- Write queries with query beans: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/writing-ebean-query-beans.md
- Immutable bean cache for read-only references: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/immutable-bean-cache.md
- Ebean OpenTelemetry tracing: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-opentelemetry.md
- Query metrics and naming: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/ebean-query-metrics.md
- Query plan capture: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/ebean-query-plan-capture.md
- Persisting and transactions: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/persisting-and-transactions-with-ebean.md
- Test container setup: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-postgres-test-container.md
- DB migration generation: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-db-migration-generation.md
- Lombok with entity beans: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/lombok-with-ebean-entity-beans.md
```
### Claude Code — `CLAUDE.md`
Same content as above — Claude Code reads `CLAUDE.md` at the project root.
### AGENTS.md — OpenAI Codex / GitHub Copilot coding agent
Place an `AGENTS.md` at your repo root:
```markdown
## Ebean ORM
This project uses [Ebean ORM](https://ebean.io). Step-by-step guides for common
tasks are at: https://github.com/ebean-orm/ebean/tree/HEAD/docs/guides/
Key guides (fetch and follow these when performing the relevant task):
- Maven POM setup: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-postgres-maven-pom.md
- Database configuration: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-postgres-database-config.md
- Migrate to `Database.builder()`: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/migrating-to-database-builder.md
- Write queries with query beans: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/writing-ebean-query-beans.md
- Persisting and transactions: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/persisting-and-transactions-with-ebean.md
- Test container setup: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-postgres-test-container.md
- DB migration generation: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/add-ebean-db-migration-generation.md
- Entity bean creation: https://raw.githubusercontent.com/ebean-orm/ebean/HEAD/docs/guides/entity-bean-creation.md
```
### Cursor — `.cursor/rules/ebean.mdc`
```markdown
---
description: Ebean ORM task guidance
globs: ["**/*.java", "**/pom.xml"]
alwaysApply: false
---
## Ebean ORM
This project uses Ebean ORM. Before performing any Ebean-related task, fetch and
follow the relevant step-by-step guide from:
https://github.com/ebean-orm/ebean/tree/HEAD/docs/guides/
```
@@ -0,0 +1,366 @@
# Guide: Add Ebean Database Migration Generation to an Existing Maven Project
## Purpose
This guide provides step-by-step instructions for adding Ebean DB migration generation
to an existing Maven project that already uses Ebean ORM. Ebean generates migrations by
performing a diff of the current entity model against the previously recorded model state,
producing platform-specific DDL SQL scripts.
These instructions are designed for AI agents and developers to follow precisely.
---
## Prerequisites
- An existing Maven project with Ebean ORM configured (entity beans present)
- `ebean-test` is already a test-scoped dependency (from POM setup guide)
- The project targets PostgreSQL (adjust `Platform.POSTGRES` for other databases)
---
## Step 1 — Verify migration dependencies
### Generation tooling (`ebean-ddl-generator`)
`ebean-test` (already present as a test dependency) transitively includes
`ebean-ddl-generator`, which provides the `DbMigration` class. No additional dependency
is required for generation.
### Runtime migration runner (`ebean-migration`)
`ebean-migration` is the library that runs migrations on application startup.
It is typically included **transitively** via `io.ebean:ebean-postgres` (or the
equivalent platform dependency). Verify it is on the classpath by running:
```bash
mvn dependency:tree | grep ebean-migration
```
If it is **not** present transitively, add it explicitly as a compile-scope dependency:
```xml
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-migration</artifactId>
<version>${ebean.version}</version>
</dependency>
```
---
## Step 2 — Create `GenerateDbMigration.java`
Create the following class in `src/test/java/main/`. This `main` method is run manually
by a developer (or AI agent) whenever entity beans change and a new migration is needed.
```java
package main;
import io.ebean.annotation.Platform;
import io.ebean.dbmigration.DbMigration;
import java.io.IOException;
/**
* Generate the next database migration based on a diff of the entity model.
* Run this main method after making entity bean changes to produce the migration SQL.
*/
public class GenerateDbMigration {
public static void main(String[] args) throws IOException {
DbMigration migration = DbMigration.create();
migration.setPlatform(Platform.POSTGRES);
migration.setVersion("1.1"); // set to the next migration version
migration.setName("add-customer"); // short description of the change
migration.generateMigration();
}
}
```
### Version naming convention
Ebean supports two common version formats — choose one and apply it consistently:
| Format | Example | Notes |
|--------|---------|-------|
| **Date-based** | `20240820` | `YYYYMMDD`; used when changes are tied to dates; easily sortable |
| **Semantic** | `1.1`, `1.2`, `2.0` | Traditional versioning; useful for release-based workflows |
The version controls execution order — Ebean runs migrations in ascending version order.
### Name convention
The `name` should be a short, lowercase, hyphenated description of the change:
- `add-customer-email`
- `rename-machine-type`
- `drop-unused-columns`
---
## Step 3 — Configure the output path (if needed)
By default, migration files are written to `src/main/resources/dbmigration/` relative
to the **current working directory** when `generateMigration()` is called. This is
usually the module root, which is correct for single-module projects.
For **multi-module projects** where `GenerateDbMigration` is in a submodule but the
resources directory is at a different relative path, specify it explicitly:
```java
// Relative path from the working directory (project root) to the module's resources
migration.setPathToResources("my-module/src/main/resources");
```
---
## Step 4 — Run `GenerateDbMigration` to produce the first migration
Run the `main` method via the IDE or Maven:
```bash
# Run via Maven exec plugin (or use IDE run configuration)
mvn test-compile exec:java \
-Dexec.mainClass="main.GenerateDbMigration" \
-Dexec.classpathScope="test" \
-pl <your-module>
```
Ebean migration generation runs in **offline mode** — no database connection is required.
### Expected output files
After running, two files are created per migration in `src/main/resources/dbmigration/`:
```
src/main/resources/dbmigration/
1.1__add-customer.sql ← DDL SQL to apply (commit this)
model/
1.1__add-customer.model.xml ← logical model diff XML (commit this)
```
Both files must be committed to source control. The `.model.xml` file records the
logical state of the diff and is used by subsequent migration generations to determine
what has changed.
If **no entity beans have changed** since the last migration, the command outputs:
```
DbMigration - no changes detected - no migration written
```
---
## Step 5 — Enable the migration runner
Configure Ebean to run pending migrations automatically on application startup.
### Preferred approach — programmatic via `DatabaseBuilder`
Set `runMigration(true)` directly on the `DatabaseBuilder` when constructing
the `Database` bean. This is the preferred approach as it is explicit, co-located with
the database configuration, and does not rely on external property files.
In the `@Factory` class that builds the `Database` bean (see the database configuration
guide), add `.runMigration(true)` to the builder chain:
```java
@Bean
Database database(ConfigWrapper config) {
var dataSource = DataSourceBuilder.create()
.url(config.getDatabaseUrl())
.username(config.getDatabaseUser())
.password(config.getDatabasePassword())
// ... other datasource settings ...
;
return Database.builder()
.name("db")
.dataSourceBuilder(dataSource)
.runMigration(true) // run pending migrations on startup
.build();
}
```
If migrations should only run in certain environments (e.g., not in production, or
only when a config flag is set), make it conditional:
```java
.runMigration(config.isRunMigrations()) // driven by config value
```
### Alternative — via application properties
If programmatic configuration is not available or not preferred, set the property
in `src/main/resources/application.properties`:
```properties
ebean.migration.run=true
```
Or in `src/main/resources/application.yaml`:
```yaml
ebean:
migration:
run: true
```
For a **named database** (i.e., `Database.builder().name("mydb")`), use the database
name in the property key:
```properties
ebean.mydb.migration.run=true
```
### What the runner does at startup
When migration running is enabled, Ebean will on each application start:
1. Look at the migrations in `src/main/resources/dbmigration/`
2. Compare against the `db_migration` table (created automatically on first run)
3. Apply any migrations that have not yet been executed, in version order
4. Record each successfully applied migration in `db_migration`
---
## Step 6 — Commit the migration files
Add both generated files to source control:
```bash
git add src/main/resources/dbmigration/1.1__add-customer.sql
git add src/main/resources/dbmigration/model/1.1__add-customer.model.xml
git commit -m "Add db migration 1.1: add-customer"
```
---
## Ongoing workflow — generating subsequent migrations
For each future set of entity bean changes:
1. Make changes to the entity bean classes
2. Update `GenerateDbMigration.java` with the **new version** and **new name**:
```java
migration.setVersion("1.2");
migration.setName("add-address-table");
```
3. Run the `main` method — a new `.sql` and `.model.xml` pair is written
4. Review the generated `.sql` to confirm it reflects the intended changes
5. Commit both files
---
## Understanding the output files
### Apply SQL (`.sql`)
The apply SQL file contains the DDL that will be executed against the database:
```sql
-- apply changes
alter table customer add column email varchar(255);
```
### Model XML (`.model.xml`)
The model XML records the logical diff in a database-agnostic format. Ebean uses
this file on the next generation run to determine what has already been captured.
It is not executed against the database.
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<migration xmlns="http://ebean-orm.github.io/xml/ns/dbmigration">
<changeSet type="apply">
<addColumn tableName="customer">
<column name="email" type="varchar(255)"/>
</addColumn>
</changeSet>
</migration>
```
---
## Optional configurations
### Multiple database platforms
To generate migrations for multiple platforms simultaneously, use `addPlatform()`
instead of `setPlatform()`:
```java
migration.addPlatform(Platform.POSTGRES);
migration.addPlatform(Platform.SQLSERVER17);
migration.addPlatform(Platform.MYSQL);
```
Each platform gets its own subdirectory under `dbmigration/`.
### Include index
When enabled the migration generation also generates a file that contains
all the migrations and their associated hashes. This is a performance
optimisation (that will become the default) and means that the migration
runner just needs to read the one resource and has the pre-computed hash
values (so does not need to read each migration resource and compute the
hash for each of those at runtime).
```java
migration.setIncludeIndex(true);
```
### Strict mode
Strict mode (on by default) errors if there are any pending drops not yet applied.
Set to `false` to allow generation to proceed regardless:
```java
migration.setStrictMode(false);
```
### Applying pending drops
Destructive changes (drop column, drop table) are **not** included in the apply
SQL by default — they are recorded as `pendingDrops` in the model XML. This allows
the application to be deployed without immediately dropping columns (important for
rolling deployments).
The migration runner logs a message when pending drops exist:
```
INFO DbMigration - Pending un-applied drops in versions [1.1]
```
When ready to apply the drops, set `setGeneratePendingDrop` to the version that
contains the pending drops:
```java
migration.setVersion("1.3");
migration.setName("drop-pending-from-1.1");
migration.setGeneratePendingDrop("1.1"); // apply drops recorded in version 1.1
migration.generateMigration();
```
### Custom dbSchema
If the project uses a named Postgres schema (set via `ebean.dbSchema` in
`application.properties`), no additional configuration is needed in
`GenerateDbMigration` — Ebean picks up the schema from the application config
automatically when running in offline mode.
```properties
# application.properties
ebean.dbSchema=myschema
```
---
## Troubleshooting
| Symptom | Likely cause | Fix |
|---------|-------------|-----|
| `no changes detected - no migration written` | Entity beans unchanged since last migration | Make entity bean changes first, then re-run |
| `DbMigration - Pending un-applied drops` | A previous migration has drops not yet applied | Either suppress with `setStrictMode(false)` or apply drops with `setGeneratePendingDrop(...)` |
| Generated SQL is empty or wrong | Wrong working directory path | Set `setPathToResources(...)` to the correct module-relative path |
| `ClassNotFoundException` for entity classes | Test classpath not including main classes | Ensure `exec.classpathScope=test` or run via IDE with test classpath |
| Migrations not running on startup | Property key wrong or `ebean-migration` missing | Verify `ebean[.name].migration.run=true` and that `ebean-migration` is on the classpath |
+158
View File
@@ -0,0 +1,158 @@
# Guide: Add Ebean OpenTelemetry tracing
## Purpose
This guide explains how to enable Ebean transaction tracing with OpenTelemetry and,
most importantly, how to order startup so Ebean sees the intended global
OpenTelemetry instance.
Use this guide when adding `ebean-opentelemetry`, diagnosing missing Ebean spans,
or fixing `GlobalOpenTelemetry` double-registration errors.
---
## Overview
`ebean-opentelemetry` provides an Ebean profiling handler that creates transaction
spans as children of the current active OpenTelemetry span. It does not create
top-level request, job, or Lambda invocation spans by itself.
The handler resolves its tracer from `GlobalOpenTelemetry` when the Ebean
`Database` is configured. For that reason, the application must build and register
the OpenTelemetry SDK before any Ebean `Database` beans are created.
Rules of thumb:
- Register the global OpenTelemetry instance once.
- Register it before building Ebean databases.
- Model that ordering as a real DI dependency.
- Do not call `GlobalOpenTelemetry.set(...)` or `buildAndRegisterGlobal()` in
multiple places.
---
## Step 1 - Add the dependency
```xml
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-opentelemetry</artifactId>
<version>${ebean.version}</version>
</dependency>
```
The module registers the Ebean OpenTelemetry profile handler via `ServiceLoader`.
No manual Ebean plugin registration is normally required.
---
## Step 2 - Build OpenTelemetry before Ebean databases
Create one application-owned OpenTelemetry bean. For example, when using
`avaje-metrics-otel`:
```java
import io.avaje.config.Configuration;
import io.avaje.inject.Bean;
import io.avaje.inject.Factory;
import io.avaje.metrics.otel.MetricsOpenTelemetry;
import io.opentelemetry.api.OpenTelemetry;
import java.time.Duration;
@Factory
class OpenTelemetryConfig {
@Bean
OpenTelemetry openTelemetry(Configuration config) {
return MetricsOpenTelemetry.builder()
.endpoint(config.get("otel.endpoint"))
.serviceName(config.get("otel.serviceName", "orders"))
.deploymentEnvironmentName(config.get("app.env", "local"))
.meterInterval(Duration.ofSeconds(30))
.traceInterval(Duration.ofSeconds(30))
.buildAndRegisterGlobal();
}
}
```
If you build the SDK directly, use the same principle: create the SDK once and
register that instance globally before any Ebean databases are built.
---
## Step 3 - Make database beans depend on OpenTelemetry
In DI code, make the `Database` bean method accept `OpenTelemetry`. This parameter
is intentionally present to make startup order deterministic: OpenTelemetry is
created and registered before Ebean configures the database and profile handler.
```java
import io.avaje.config.Configuration;
import io.avaje.inject.Bean;
import io.avaje.inject.Factory;
import io.ebean.Database;
import io.ebean.datasource.DataSourceBuilder;
import io.opentelemetry.api.OpenTelemetry;
@Factory
class DatabaseConfig {
@Bean
Database database(OpenTelemetry openTelemetry, Configuration config) {
var dataSource = DataSourceBuilder.create()
.url(config.get("db.url"))
.username(config.get("db.username"))
.password(config.get("db.password"));
return Database.builder()
.name("db")
.dataSourceBuilder(dataSource)
.build();
}
}
```
For Spring, use the same dependency shape: either inject `OpenTelemetry` into the
database `@Bean` method or use `@DependsOn` to ensure the OpenTelemetry bean is
initialized first.
Do not invert the dependency by making OpenTelemetry depend on the Ebean
`Database`. That creates a startup cycle and can still initialize Ebean before the
global OpenTelemetry instance is ready.
---
## Step 4 - Create a parent span at the application boundary
Ebean transaction spans are child spans. They are only created when a recording
OpenTelemetry span is active on the current thread.
Use HTTP server instrumentation, Lambda instrumentation, or an application-level
root span around the top-level request/job boundary. Ebean will then attach
transaction spans beneath that current span.
---
## Troubleshooting
### `GlobalOpenTelemetry.set has already been called`
This usually means more than one component is trying to register a global SDK, or
some startup path touched the global before the application registered its SDK.
Fixes:
1. Keep exactly one `buildAndRegisterGlobal()` / `GlobalOpenTelemetry.set(...)`
call in the application.
2. Build that OpenTelemetry bean before Ebean `Database` beans.
3. Remove duplicate OTEL setup from tests, helper factories, or secondary modules.
### No Ebean spans appear
Check:
1. `ebean-opentelemetry` is on the runtime classpath.
2. OpenTelemetry is registered before Ebean databases are built.
3. There is a current recording parent span when Ebean transactions run.
4. Sampling is not dropping the parent trace.
@@ -0,0 +1,295 @@
# Guide: Add Ebean ORM (PostgreSQL) to an Existing Maven Project — Step 3: Database Configuration
## Purpose
This guide provides step-by-step instructions for configuring an Ebean `Database` bean
using **Avaje Inject** (`@Factory` / `@Bean`), backed by a PostgreSQL datasource built
with Ebean's `DataSourceBuilder`. Follow every step in order. This is Step 3 of 3.
---
## Prerequisites
- **Step 1 complete**: `pom.xml` already includes `ebean-postgres`, `ebean-maven-plugin`,
and `querybean-generator` (see `add-ebean-postgres-maven-pom.md`)
- **Step 2 complete**: Test container setup is working and `mvn verify` passes
(see `add-ebean-postgres-test-container.md`)
- **Avaje Inject** is on the classpath (e.g. `io.avaje:avaje-inject`)
- A configuration source is available at runtime (e.g. `avaje-config` reading
`application.yml` or environment variables)
- The following configuration keys are resolvable at runtime (adapt names to your project):
| Key | Description |
|-----|-------------|
| `db_url` | JDBC URL for the master/write connection |
| `db_user` | Database username |
| `db_pass` | Database password |
| `db_master_min_connections` | Minimum pool size (default: 1) |
| `db_master_initial_connections` | Initial pool size at startup — set high to pre-warm on pod start (see K8s note below) |
| `db_master_max_connections` | Maximum pool size (default: 200) |
---
## Step 1 — Locate or create the `@Factory` class
Look for an existing Avaje Inject `@Factory`-annotated class in the project
(often named `AppConfig`, `DatabaseConfig`, or similar). If one exists, add the new
`@Bean` method to it. If none exists, create one:
```java
package com.example.configuration;
import io.avaje.inject.Bean;
import io.avaje.inject.Factory;
@Factory
class DatabaseConfig {
// beans will be added in the steps below
}
```
---
## Step 2 — Add the `Database` bean method (minimal — master datasource only)
Add the following `@Bean` method to the `@Factory` class. This creates an Ebean
`Database` backed by a single master (read-write) PostgreSQL datasource.
```java
import io.ebean.Database;
import io.ebean.datasource.DataSourceBuilder;
@Bean
Database database() {
var dataSource = DataSourceBuilder.create()
.url(/* resolve from config, e.g.: */ Config.get("db_url"))
.username(Config.get("db_user"))
.password(Config.get("db_pass"))
.driver("org.postgresql.Driver")
.schema("myschema") // set to your target schema
.applicationName("my-app") // visible in pg_stat_activity
.minConnections(Config.getInt("db_master_min_connections", 1))
.initialConnections(Config.getInt("db_master_initial_connections", 10))
.maxConnections(Config.getInt("db_master_max_connections", 200));
return Database.builder()
.name("db") // logical name for this Database instance
.dataSourceBuilder(dataSource)
.build();
}
```
### Field guidance
| Field | Notes |
|-------|-------|
| `url` | Full JDBC URL, e.g. `jdbc:postgresql://host:5432/dbname` |
| `schema` | The Postgres schema Ebean should use (omit if using `public`) |
| `applicationName` | Shown in `pg_stat_activity.application_name`; helps with DB-side diagnostics |
| `name("db")` | Logical Ebean database name; relevant if multiple Database instances exist |
| `minConnections` | Connections kept open at all times; pool will not shrink below this |
| `initialConnections` | Connections opened at startup; see K8s warm-up note below |
| `maxConnections` | Hard upper limit on concurrent connections |
### Connection pool sizing for Kubernetes (and similar orchestrated environments)
When a pod starts in Kubernetes it will receive live traffic as soon as it passes
readiness checks — often before the connection pool has had a chance to grow to handle
the load. This can cause latency spikes on the first wave of requests while the pool
expands one connection at a time.
Use `initialConnections` to **pre-warm the pool at startup** so it is already sized
for peak load when the pod goes live:
```
minConnections: 2 ← floor; pool will shrink back here when idle
initialConnections: 20 ← opened at pod start, before first request arrives
maxConnections: 50 ← hard ceiling
```
The lifecycle is:
1. **Pod starts** — pool opens `initialConnections` connections immediately.
2. **Pod receives traffic** — pool is already at capacity; no growth latency.
3. **Traffic drops** — idle connections are closed; pool trims back toward `minConnections`.
4. **Next traffic spike** — pool grows again up to `maxConnections` on demand.
Set `initialConnections` to a value high enough that the pool does not need to grow
during the first minute of live traffic. A common starting point is 5075% of
`maxConnections`.
---
## Step 3 — Inject configuration via a constructor or config helper (recommended)
Rather than calling `Config.get(...)` inline, inject a typed config helper or the
Avaje `Configuration` bean if one is available. This makes the factory testable and
keeps the wiring explicit. For example:
```java
@Bean
Database database(Configuration config) {
String url = config.get("db_url");
String user = config.get("db_user");
String pass = config.get("db_pass");
int min = config.getInt("db_master_min_connections", 1);
int init = config.getInt("db_master_initial_connections", 10);
int max = config.getInt("db_master_max_connections", 200);
var dataSource = DataSourceBuilder.create()
.url(url)
.username(user)
.password(pass)
.driver("org.postgresql.Driver")
.schema("myschema")
.applicationName("my-app")
.minConnections(min)
.initialConnections(init)
.maxConnections(max);
return Database.builder()
.name("db")
.dataSourceBuilder(dataSource)
.build();
}
```
If the project has a dedicated config-wrapper class (a `@Component` that reads config
keys), accept it as a parameter instead of `Configuration`.
> **Note:** Injecting `Configuration` requires that `avaje-config` is properly wired
> into the DI context. If you encounter "No dependency provided for
> io.avaje.config.Configuration" errors, use `Config.get(...)` static access instead
> (as shown in Step 2).
---
## Step 4 (Optional) — Add a read-only datasource
For production services that have a separate read-replica, add a second
`DataSourceBuilder` for read-only queries and wire it via
`readOnlyDataSourceBuilder(...)`. The read-only datasource:
- Uses `readOnly(true)` and `autoCommit(true)` (Ebean routes read queries there automatically)
- Typically has a higher max connection count than the master
- Benefits from a prepared-statement cache (`pstmtCacheSize`)
```java
@Bean
Database database(Configuration config) {
String masterUrl = config.get("db_url");
String readOnlyUrl = config.get("db_url_readonly");
String user = config.get("db_user");
String pass = config.get("db_pass");
var masterDataSource = buildDataSource(user, pass)
.url(masterUrl)
.minConnections(config.getInt("db_master_min_connections", 1))
.initialConnections(config.getInt("db_master_initial_connections", 10))
.maxConnections(config.getInt("db_master_max_connections", 50));
var readOnlyDataSource = buildDataSource(user, pass)
.url(readOnlyUrl)
.readOnly(true)
.autoCommit(true)
.pstmtCacheSize(250) // cache up to 250 prepared statements per connection
.maxInactiveTimeSecs(600) // close idle connections after 10 minutes
.minConnections(config.getInt("db_readonly_min_connections", 2))
.initialConnections(config.getInt("db_readonly_initial_connections", 10))
.maxConnections(config.getInt("db_readonly_max_connections", 200));
return Database.builder()
.name("db")
.dataSourceBuilder(masterDataSource)
.readOnlyDataSourceBuilder(readOnlyDataSource)
.build();
}
private static DataSourceBuilder buildDataSource(String user, String pass) {
return DataSourceBuilder.create()
.username(user)
.password(pass)
.driver("org.postgresql.Driver")
.schema("myschema")
.applicationName("my-app")
.addProperty("prepareThreshold", "2"); // PostgreSQL: server-side prepared statements
}
```
### Additional configuration keys for the read-only datasource
| Key | Description | Default |
|-----|-------------|---------|
| `db_url_readonly` | JDBC URL for the read replica | — |
| `db_master_initial_connections` | Initial master pool size at startup | 10 |
| `db_readonly_min_connections` | Minimum pool size | 2 |
| `db_readonly_initial_connections` | Initial pool size at startup | same as min |
| `db_readonly_max_connections` | Maximum pool size | 20 |
---
## Step 5 (Optional) — Enable the migration runner
If the project uses Ebean's built-in DB migration runner to apply SQL migrations on
startup, enable it on the `DatabaseBuilder`:
```java
return Database.builder()
.name("db")
.dataSourceBuilder(dataSource)
.runMigration(true) // run pending migrations on startup
.build();
```
This is equivalent to setting `ebean.migration.run=true` in `application.properties`
but is preferred because it keeps all database configuration in one place. To make it
conditional (e.g. only in non-production environments):
```java
.runMigration(config.getBoolean("db.runMigrations", false))
```
See the DB migration generation guide (`add-ebean-db-migration-generation.md`) for
full details on generating and managing migration files.
---
## See Also
For advanced connection pool configuration, production deployment patterns, and connection
validation best practices, see the [ebean-datasource guides](https://github.com/ebean-orm/ebean-datasource/tree/master/docs/guides/):
- **[Creating DataSource Pools](https://github.com/ebean-orm/ebean-datasource/blob/master/docs/guides/create-datasource-pool.md)** — Covers read-only pools (`readOnly(true)` + `autoCommit(true)`), Kubernetes deployment strategies using `initialConnections`, and AWS Lambda optimization
- **[AWS Aurora Read-Write Split](https://github.com/ebean-orm/ebean-datasource/blob/master/docs/guides/aws-aurora-read-write-split.md)** — Setting up dual DataSources with Aurora reader and writer endpoints, including Ebean secondary datasource routing
- **[Connection Validation Best Practices](https://github.com/ebean-orm/ebean-datasource/blob/master/docs/guides/connection-validation-best-practices.md)** — Why `Connection.isValid()` is the recommended default and when (rarely) explicit `heartbeatSql` is needed
---
## Verification
1. Start the application (or run `mvn test -pl <your-module>`).
2. Look for log output similar to:
```
INFO o.a.datasource.pool.ConnectionPool - DataSourcePool [db] autoCommit[false] min[1] max[5]
INFO io.ebean.internal.DefaultContainer - DatabasePlatform name:db platform:postgres
```
3. If you see `DataSourcePool` and `DatabasePlatform` log lines, Ebean is connected and
the database bean is wired correctly.
---
## Troubleshooting
| Symptom | Likely cause | Fix |
|---------|-------------|-----|
| `ClassNotFoundException: org.postgresql.Driver` | PostgreSQL JDBC driver missing | Add `org.postgresql:postgresql` dependency (see Step 1 guide) |
| `Cannot connect to database` at startup | DB unreachable but `skipDataSourceCheck` is `false` | Set `.skipDataSourceCheck(true)` |
| Ebean enhancement warnings in logs | `ebean-maven-plugin` not configured | Complete Step 1 guide |
| `NullPointerException` reading config key | Config key not defined | Add the key to `application.yml` or environment |
---
## Related
The test container setup (Step 2) should already be complete and passing
before this step. See `add-ebean-postgres-test-container.md`.
+294
View File
@@ -0,0 +1,294 @@
# Guide: Add Ebean ORM (PostgreSQL) to an Existing Maven Project — Step 1: POM Setup
## Purpose
This guide provides step-by-step instructions for modifying an existing Maven `pom.xml`
to add Ebean ORM with PostgreSQL support. Follow every step in order. This is Step 1 of 3.
---
## Prerequisites
- An existing Maven project (`pom.xml` already exists)
- Java 11 or higher
- The project does **not** yet include any Ebean dependencies
---
## Step 0 — Gather requirements from the user
Before modifying any files, ask the user the following questions to determine
the correct setup path. Record the answers — they affect dependency choices
in this step and the approach used in Steps 2 and 3.
### Mandatory gate (do not skip)
- Do **not** continue to Step 1+ until the DI path is explicitly recorded.
- Do **not** infer the **None** path by default. Use **None** only when the user explicitly confirms no DI framework.
- If the user asks for a partial action (for example, "do only step 3"), keep the previously selected DI path; do not switch paths implicitly.
### DI path precedence (when user has not answered yet)
Use this precedence order:
1. Existing project context (highest priority): if dependencies/config already show Avaje Inject or Spring, select that path.
2. Explicit user answer in this guide's questions.
3. Recommended default only when context is genuinely unknown: Avaje Inject.
If context remains ambiguous, ask one multiple-choice clarification question and wait for the answer before editing files.
### Question 1: Dependency injection framework
> "Does this project use (or will it use) a DI framework? If so, which one?"
| Answer | Effect |
|--------|--------|
| **Avaje Inject** | Add `avaje-inject` + `avaje-inject-test` dependencies; use `@TestScope @Factory` for test container (Step 2); use `@Factory`/`@Bean` for production database (Step 3) |
| **Spring** | Use Spring `@TestConfiguration` for test container (Step 2); use Spring `@Configuration`/`@Bean` for production database (Step 3) |
| **None** | Use declarative `application-test.yaml` for test container (Step 2); use programmatic `Database.builder()` directly in application code (Step 3) |
### Question 2: PostGIS
> "Do you need PostGIS spatial extensions (geometry types, spatial queries)?"
| Answer | Effect |
|--------|--------|
| **Yes** | Use `PostgisContainer` in test setup (Step 2); may need `net.postgis:postgis-jdbc` dependency |
| **No** | Use `PostgresContainer` in test setup (Step 2) |
### Question 3: Read replica
> "Does your production environment use a separate read-replica (read-only) database?"
| Answer | Effect |
|--------|--------|
| **Yes** | Configure a read-only `DataSourceBuilder` in production database config (Step 3) |
| **No** | Single datasource only (Step 3) |
### Defaults
If the user is unsure or setting up a new project, recommend:
- **Avaje Inject** (lightweight, fast compile-time DI)
- **No PostGIS** (can be added later)
- **No read replica** (can be added later)
---
## Step 1 — Define the Ebean version property
Open the module's `pom.xml` (the one that will use Ebean directly, i.e. the module
containing the database configuration and entity classes).
Inside the `<properties>` block, add the `ebean.version` property if it does not
already exist:
```xml
<properties>
<!-- add this line; use latest stable from https://github.com/ebean-orm/ebean/releases -->
<ebean.version>17.5.0</ebean.version>
</properties>
```
> If the project has a parent POM that already defines `ebean.version`, skip this step.
---
## Step 2 — Add the PostgreSQL JDBC driver dependency
Inside the `<dependencies>` block, add the PostgreSQL JDBC driver:
```xml
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.8</version>
</dependency>
```
> Check [Maven Central](https://central.sonatype.com/artifact/org.postgresql/postgresql)
> for the latest version. If the parent POM manages the PostgreSQL version, omit the
> `<version>` tag.
---
## Step 3 — Add the Ebean PostgreSQL platform dependency
Inside the `<dependencies>` block, add the Ebean Postgres platform dependency:
```xml
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-postgres</artifactId>
<version>${ebean.version}</version>
</dependency>
```
This single artifact pulls in the Ebean core, the datasource connection pool
(`ebean-datasource`), and all Postgres-specific support.
---
## Step 4 — Add the ebean-test dependency (test scope)
`ebean-test` configures Ebean for tests and enables automatic Docker container management
for Postgres test instances:
```xml
<!-- test dependencies -->
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-test</artifactId>
<version>${ebean.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.avaje</groupId>
<artifactId>junit</artifactId>
<version>1.8</version>
<scope>test</scope>
</dependency>
```
The `io.avaje:junit` bundle includes JUnit Jupiter (API + engine) and AssertJ,
avoiding the need to declare those dependencies separately.
---
## Step 4b — Add DI framework dependencies (if applicable)
If the user chose **Avaje Inject** in Step 0, add the following dependencies and
annotation processor. Skip this step if the user chose Spring or no DI.
### Dependencies
```xml
<dependency>
<groupId>io.avaje</groupId>
<artifactId>avaje-inject</artifactId>
<version>12.5</version>
</dependency>
<dependency>
<groupId>io.avaje</groupId>
<artifactId>avaje-inject-test</artifactId>
<version>12.5</version>
<scope>test</scope>
</dependency>
```
> Check [Maven Central](https://central.sonatype.com/artifact/io.avaje/avaje-inject)
> for the latest version.
### Annotation processor
The `avaje-inject-generator` must be added to the `annotationProcessorPaths` in
`maven-compiler-plugin` (added in Step 6 below). When adding both processors,
the final `<annotationProcessorPaths>` block should include both:
```xml
<annotationProcessorPaths>
<path> <!-- generate ebean query beans -->
<groupId>io.ebean</groupId>
<artifactId>querybean-generator</artifactId>
<version>${ebean.version}</version>
</path>
<path> <!-- generate avaje-inject DI code -->
<groupId>io.avaje</groupId>
<artifactId>avaje-inject-generator</artifactId>
<version>12.5</version>
</path>
</annotationProcessorPaths>
```
---
## Step 5 — Add the ebean-maven-plugin (bytecode enhancement)
Ebean requires bytecode enhancement to provide dirty-checking and lazy-loading.
The `ebean-maven-plugin` performs this enhancement at build time.
Inside the `<build><plugins>` block, add:
```xml
<plugin> <!-- perform ebean enhancement -->
<groupId>io.ebean</groupId>
<artifactId>ebean-maven-plugin</artifactId>
<version>${ebean.version}</version>
<extensions>true</extensions>
</plugin>
```
---
## Step 6 — Add the querybean-generator annotation processor
The `querybean-generator` annotation processor generates type-safe query bean classes
at compile time. It must be registered as an `annotationProcessorPath` inside
`maven-compiler-plugin`.
### Case A — No existing `maven-compiler-plugin` configuration
Add the full plugin entry to `<build><plugins>`:
```xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.15.0</version>
<configuration>
<annotationProcessorPaths>
<path> <!-- generate ebean query beans -->
<groupId>io.ebean</groupId>
<artifactId>querybean-generator</artifactId>
<version>${ebean.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
```
### Case B — `maven-compiler-plugin` already exists with `<annotationProcessorPaths>`
Locate the existing `<annotationProcessorPaths>` block inside the existing
`maven-compiler-plugin` entry and add the new `<path>` inside it. Do **not** add a
second `<configuration>` block or a second `<annotationProcessorPaths>` block.
Example — if the existing block already has a path for, say, `avaje-nima-generator`:
```xml
<annotationProcessorPaths>
<path>
<groupId>io.avaje</groupId>
<artifactId>avaje-nima-generator</artifactId>
<version>${avaje-nima.version}</version>
</path>
<!-- ADD the new path here, inside the existing block -->
<path>
<groupId>io.ebean</groupId>
<artifactId>querybean-generator</artifactId>
<version>${ebean.version}</version>
</path>
</annotationProcessorPaths>
```
---
## Verification
Run the following to confirm the POM is valid and both main and test sources compile:
```bash
mvn test-compile
```
Expected result: `BUILD SUCCESS` with no errors from Ebean or the annotation processor.
Using `test-compile` rather than `compile` ensures test dependencies and test
source files are also verified.
---
## Next Step
Proceed to **Step 2: Test container setup**
(`add-ebean-postgres-test-container.md`) to wire an injectable test `Database`
backed by `ebean-test` containers. Verify with `mvn verify` before continuing
to production database configuration.
@@ -0,0 +1,445 @@
# Guide: Add Ebean ORM (PostgreSQL) to an Existing Maven Project - Step 2: Test Container Setup
## Purpose
This guide provides step-by-step instructions for setting up a PostgreSQL Docker
container for tests, exposing an `io.ebean.Database` instance for use in test
classes. This is Step 2 of 3.
Complete this step before configuring the production database in Step 3. Getting
the test container working first gives you a fast feedback loop - you can verify
entity changes compile, enhance, and persist correctly with `mvn verify` before
wiring up production datasource configuration.
---
## Prerequisites
- **Step 1 complete**: `pom.xml` includes `ebean-postgres`, `ebean-maven-plugin`,
`querybean-generator`, and **`ebean-test`** as a test-scoped dependency
(see `add-ebean-postgres-maven-pom.md`)
- **Step 0 answers recorded**: DI framework choice and PostGIS requirement
- **Docker** is installed and running on the developer machine
---
## Overview: Choosing your approach
The approach depends on the DI framework choice made in Step 0:
| DI framework | Approach | How |
|--------------|----------|-----|
| **Avaje Inject** | Programmatic | `@TestScope @Factory` class with injectable `Database` bean |
| **Spring** | Programmatic | `@TestConfiguration` class with `@Bean` methods |
| **None** | Declarative | `application-test.yaml` + plain JUnit test |
Follow the path that matches your choice below.
---
## Path A — Programmatic with Avaje Inject (recommended)
This approach uses `@TestScope @Factory` to expose the container and `Database`
as injectable beans. It offers more control (image mirrors, custom config) and
makes `Database` directly injectable into test classes.
### A.1 — Verify Avaje Inject test dependencies
Confirm the following are present in `pom.xml` (in addition to `ebean-test`):
```xml
<dependency>
<groupId>io.avaje</groupId>
<artifactId>avaje-inject</artifactId>
<version>${avaje-inject.version}</version>
</dependency>
<dependency>
<groupId>io.avaje</groupId>
<artifactId>avaje-inject-test</artifactId>
<version>${avaje-inject.version}</version>
<scope>test</scope>
</dependency>
```
And the `avaje-inject-generator` annotation processor in `maven-compiler-plugin`:
```xml
<path>
<groupId>io.avaje</groupId>
<artifactId>avaje-inject-generator</artifactId>
<version>${avaje-inject.version}</version>
</path>
```
### A.2 — Create a `@TestScope @Factory` class
Create a new class in the test source tree (e.g., `src/test/java/.../testconfig/TestConfiguration.java`):
```java
package com.example.testconfig;
import io.avaje.inject.Bean;
import io.avaje.inject.Factory;
import io.avaje.inject.test.TestScope;
import io.ebean.Database;
@TestScope
@Factory
class TestConfiguration {
// bean methods added below
}
```
### A.3 — Add a container bean and a Database bean
#### Plain PostgreSQL
```java
import io.ebean.test.containers.PostgresContainer;
@TestScope
@Factory
class TestConfiguration {
@Bean
PostgresContainer postgres() {
return PostgresContainer.builder("17") // Postgres image version
.dbName("my_app") // database to create inside the container
.build()
.start();
}
@Bean
Database database(PostgresContainer container) {
return container.ebean()
.builder()
.build();
}
}
```
#### PostGIS (PostgreSQL + PostGIS extension)
Use `PostgisContainer` instead. The default image is
`ghcr.io/baosystems/postgis:{version}` and the extensions `hstore`, `pgcrypto`,
and `postgis` are installed automatically.
```java
import io.ebean.test.containers.PostgisContainer;
@TestScope
@Factory
class TestConfiguration {
@Bean
PostgisContainer postgres() {
return PostgisContainer.builder("17")
.dbName("my_app")
.build()
.start();
}
@Bean
Database database(PostgisContainer container) {
return container.ebean()
.builder()
.build();
}
}
```
#### Key differences
| | PostgresContainer | PostgisContainer |
|---|---|---|
| Docker image | `postgres:{version}` | `ghcr.io/baosystems/postgis:{version}` |
| Default extensions | `hstore, pgcrypto` | `hstore, pgcrypto, postgis` |
| Default port | 6432 | 6432 |
| Optional LW mode | — | `.useLW(true)` (see Optional section) |
### A.4 — Write a test
Annotate the test class with `@InjectTest` and inject `Database` with `@Inject`:
```java
package com.example.testconfig;
import io.avaje.inject.test.InjectTest;
import io.ebean.Database;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@InjectTest
class DatabaseTest {
@Inject
Database database;
@Test
void database_isAvailable() {
assertThat(database).isNotNull();
}
}
```
### A.5 — Verify
```bash
mvn verify
```
Expected log output:
```
INFO Container ut_postgres running with port:6432 ...
INFO connectivity confirmed for ut_postgres
INFO DataSourcePool [my_app] autoCommit[false] ...
INFO DatabasePlatform name:my_app platform:postgres
INFO Executing db-create-all.sql - ...
```
**Important:** Verify this step passes with `mvn verify` before proceeding to
Step 3 (production database configuration).
---
## Path B — Programmatic with Spring
Use Springs `@TestConfiguration` to provide the container and `Database` beans.
### B.1 — Create a `@TestConfiguration` class
```java
package com.example.testconfig;
import io.ebean.Database;
import io.ebean.test.containers.PostgresContainer;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
@TestConfiguration
class TestDatabaseConfig {
@Bean
PostgresContainer postgres() {
return PostgresContainer.builder("17")
.dbName("my_app")
.build()
.start();
}
@Primary
@Bean
Database database(PostgresContainer container) {
return container.ebean()
.builder()
.build();
}
}
```
For PostGIS, use `PostgisContainer` instead (same pattern as Path A).
### B.2 — Write a test
```java
package com.example;
import io.ebean.Database;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
class DatabaseTest {
@Autowired
Database database;
@Test
void database_isAvailable() {
assertThat(database).isNotNull();
}
}
```
### B.3 — Verify
Run `mvn verify` and confirm the same log output as Path A.
---
## Path C — Declarative (no DI framework)
This is the simplest approach but offers less control. `ebean-test` reads a
YAML config file and automatically manages the Docker container and `Database`
instance. Use this when the project has no DI framework.
### C.1 — Create `application-test.yaml`
Create `src/test/resources/application-test.yaml`:
```yaml
ebean:
test:
platform: postgres
ddlMode: dropCreate
dbName: my_app
```
For PostGIS, use `platform: postgis` instead.
### C.2 — Write a test
Use `DB.getDefault()` to obtain the `Database` instance:
```java
package com.example;
import io.ebean.DB;
import io.ebean.Database;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class DatabaseTest {
@Test
void database_isAvailable() {
Database database = DB.getDefault();
assertThat(database).isNotNull();
}
}
```
### C.3 — Verify
```bash
mvn verify
```
Expected log output:
```
INFO Container ut_postgres running with port:6432 ...
INFO connectivity confirmed for ut_postgres
INFO DataSourcePool [my_app] autoCommit[false] ...
INFO DatabasePlatform name:my_app platform:postgres
```
**Important:** Verify this passes before proceeding to Step 3.
Skip to [Optional configurations](#optional-configurations) or proceed to Step 3.
---
## Optional configurations
### Image mirror (for CI / private registry)
If CI builds pull images from a private registry (e.g., AWS ECR) instead of Docker Hub
or GitHub Container Registry, specify a mirror. The mirror is **only used in CI** -
it is ignored on local developer machines (where Docker Hub / GHCR is used directly).
```java
@Bean
PostgresContainer postgres() {
return PostgresContainer.builder("16")
.dbName("my_app")
.mirror("123456789.dkr.ecr.ap-southeast-2.amazonaws.com/mirrored")
.build()
.start();
}
```
Alternatively, set the mirror globally via a system property or
`ebean.test.containers.mirror` in a properties file, avoiding code changes per project.
### Read-only datasource (for tests using read-replica simulation)
Call `.autoReadOnlyDataSource(true)` on the `DatabaseBuilder` to automatically
create a second read-only datasource pointing at the same container:
```java
@Bean
Database database(PostgresContainer container) {
return container.ebean()
.builder()
.autoReadOnlyDataSource(true) // test read-only queries against same container
.build();
}
```
### Dump metrics on shutdown
Useful for performance analysis during test runs:
```java
@Bean
Database database(PostgresContainer container) {
return container.ebean()
.builder()
.dumpMetricsOnShutdown(true)
.dumpMetricsOptions("loc,sql,hash")
.build();
}
```
### PostGIS: LW mode (HexWKB)
For PostGIS with DriverWrapperLW (HexWKB binary geometry encoding), set `.useLW(true)`.
This switches the JDBC URL prefix to `jdbc:postgresql_lwgis://` and requires the
`net.postgis:postgis-jdbc` dependency on the test classpath:
```xml
<!-- add to pom.xml test dependencies when using useLW(true) -->
<dependency>
<groupId>net.postgis</groupId>
<artifactId>postgis-jdbc</artifactId>
<version>2024.1.0</version>
<scope>test</scope>
</dependency>
```
```java
@Bean
PostgisContainer postgres() {
return PostgisContainer.builder("16")
.dbName("my_app")
.useLW(true) // use HexWKB + DriverWrapperLW
.build()
.start();
}
```
> **Note**: LW mode is not required for most PostGIS use cases. Only enable it if
> your entities use binary geometry types (e.g., `net.postgis.jdbc.geometry.Geometry`)
> that require the `DriverWrapperLW` driver.
---
## Keeping the container running (local development)
By default, `ebean-test` stops the Docker container when tests finish. To keep it
running between test runs (much faster for local development), create a marker file:
```bash
mkdir -p ~/.ebean && touch ~/.ebean/ignore-docker-shutdown
```
On CI servers, omit this file so containers are cleaned up after each build.
---
## Next Steps
- **Add `TestEntityBuilder`** to your test configuration for rapid test data creation
with auto-populated random values. See `testing-with-testentitybuilder.md`.
- **Proceed to Step 3** — production database configuration
(`add-ebean-postgres-database-config.md`). Verify this step passes with
`mvn verify` before continuing.
+262
View File
@@ -0,0 +1,262 @@
# Guide: Ebean query metrics and naming
## Purpose
This guide explains the metrics Ebean captures, how the metric **name** for a query
is derived, and how you influence that name with `setLabel(..)` and **profile
locations**. It also covers secondary (lazy / query) load naming, the inline SQL
comment, collecting metrics at runtime, and how the names map to avaje-metrics tags.
Use this guide when you want to identify a query in metrics/telemetry, when a query
shows up under an unexpected metric name, or when wiring Ebean metrics into a reporter.
---
## Overview
Ebean records timing and counter metrics for the work it does. Every metric has a
**name** whose leading segment identifies the kind of work:
| Prefix | What it measures | Example name |
|---|---|---|
| `orm.` | Entity (ORM) query | `orm.Customer.findList`, `orm.CustomerFinder.byName` |
| `dto.` | DTO query | `dto.CustomerDto.byEmail` |
| `sql.query.` | Raw SQL query | `sql.query.<label>` |
| `sql.update.` / `sql.call.` | Raw SQL update / stored procedure call | `sql.update.<label>` |
| `orm.update.` | ORM update statement | `orm.update.<label>` |
| `iud.` | Bean insert / update / delete | `iud.Customer.insert` |
| `txn.main` / `txn.readonly` / `txn.named.` | Transactions | `txn.main`, `txn.named.processOrders` |
| `l2n.` | L2 cache region | `l2n.customer.hit` |
The rest of this guide focuses on **`orm.` query names**, which is where labels and
profile locations apply.
---
## How an ORM query name is derived
An entity query name has the form `orm.<identifier>`. The `<identifier>` comes from one
of three sources, in priority order:
1. **An explicit `setLabel(..)`** — prefixed with the bean type for disambiguation.
2. **A profile location** — used as-is (it is already a unique `Class.method` identifier).
3. **Neither** — the bean type plus the query type (e.g. `findList`).
| Root query source | Resulting name |
|---|---|
| `setLabel("custMain")` on `Customer` | `orm.Customer.custMain` |
| Profile location `CustomerFinder.byName` | `orm.CustomerFinder.byName` |
| Unlabelled `DB.find(Customer.class).findList()` | `orm.Customer.findList` |
The asymmetry is intentional: an explicit label is a short, ambiguous token (`custMain`
could be used for any bean), so the bean type is prefixed. A profile location is already
unique and type-independent, so it is used as-is.
### Step 1 - Label a query explicitly
```java
List<Customer> customers = DB.find(Customer.class)
.setLabel("custMain")
.findList();
// metric name: orm.Customer.custMain
```
DTO queries support `setLabel(..)` too, and follow the **same naming convention** as
ORM queries — an explicit label is prefixed with the DTO type, a profile location is
used as-is, and an unlabelled DTO query uses just the DTO type:
```java
DB.findDto(CustomerDto.class, sql)
.setLabel("byEmail")
.findList();
// metric name: dto.CustomerDto.byEmail
// profile location only -> dto.<location> (no type prefix)
// unlabelled -> dto.CustomerDto
```
### Step 2 - Use a profile location (preferred for finders / query beans)
A profile location identifies a query by its **call site** (`Class.method`) instead of a
hand-written label.
**The common case is automatic.** With Ebean's byte-code enhancement enabled (the normal
setup when using query beans / finders), Ebean assigns each query a profile location
derived from its call site — no code is required:
```java
List<Customer> customers = new QCustomer()
.status.eq(Status.ACTIVE)
.findList();
// metric name: orm.<CallingClass>.<method> (often with a line number, see below)
```
The enhancer derives the location from the calling code (the method that runs the query),
and for many call sites it includes the **source line number** (e.g.
`CustomerService.find:42`), so distinct call sites — even in the same method — get distinct
names automatically.
**Setting one explicitly.** You can also set a profile location yourself, which is useful
without enhancement or to control the identity:
```java
ProfileLocation LOC = ProfileLocation.create();
List<Customer> customers = DB.find(Customer.class)
.setProfileLocation(LOC)
.where().eq("status", Status.ACTIVE)
.findList();
// metric name: orm.<DeclaringClass>.<method>
```
Factory choices:
- `ProfileLocation.create()` — call site as `Class.method`, **no line number**.
- `ProfileLocation.createWithLine()` — includes the source line number
(e.g. `CustomerService.find:42`), so two queries in the **same method** get
**distinct** names.
- `ProfileLocation.create("label")` — a named location (used for named transactions).
> Note: a location with no line number (`create()`, or a call site the enhancer emits
> without a line) means two different queries in the same method share one name. The
> queried entity is still distinguishable downstream via the avaje-metrics `type` tag
> (see "Mapping to avaje-metrics tags" below). Use `createWithLine()` to separate
> same-method call sites in the name itself.
---
## Secondary (lazy / query) load naming
When a query lazy-loads or `fetchQuery()`-loads an association, Ebean issues a
**secondary** query. Its name **extends the parent query's full name** with the relative
path and the load mode (`lazy` or `query`), joined with `.`:
```
orm.<parent name without the "orm." prefix>.<path>.<loadMode>
```
So a secondary load is always an exact extension of its parent metric name, which makes
the relationship obvious in dashboards.
Example — root labelled `custMain` on `Customer`, chain `Customer -> orders -> details`:
Lazy loading:
```
orm.Customer.custMain
orm.Customer.custMain.orders.lazy
orm.Customer.custMain.orders.lazy.details.lazy
```
Secondary eager `fetchQuery()` loading:
```
orm.Customer.custMain
orm.Customer.custMain.orders.query
orm.Customer.custMain.orders.query.details.query
```
The same applies with a **profile-location** root (no explicit `setLabel`):
```
orm.CustomerFinder.byName
orm.CustomerFinder.byName.contacts.lazy
```
Unlike the root query, the secondary name is **not** bean-type prefixed by the loaded
type — it inherits the parent's name so it relates back to where the load originated.
---
## Inline SQL comment
When `includeLabelInSql` is enabled (the default), Ebean prepends the query's label (or
profile-location label) as an inline SQL comment, which is useful for matching slow
queries in database logs back to application code:
```sql
select /* CustomerFinder.byName */ t0.id, t0.name from be_customer t0 where ...
```
The comment uses the explicit `setLabel(..)` if present, otherwise the profile-location
label. Secondary queries use their full extended name
(e.g. `/* Customer.custMain.contacts.query */`). `EXISTS` / subquery forms are not
commented.
Disable it via the builder:
```java
Database.builder()
.includeLabelInSql(false)
.build();
```
---
## Collecting metrics at runtime
Read collected metrics through `Database.metaInfo()`:
```java
import io.ebean.meta.MetaQueryMetric;
import io.ebean.meta.ServerMetrics;
ServerMetrics metrics = database.metaInfo().collectMetrics(); // resets counters
for (MetaQueryMetric q : metrics.queryMetrics()) {
System.out.printf("%s type=%s count=%d total=%d mean=%d%n",
q.name(), // e.g. orm.Customer.custMain
q.type().getSimpleName(), // the queried bean/DTO type, e.g. Customer
q.count(), q.total(), q.mean());
}
```
Key API:
- `database.metaInfo()``MetaInfoManager`.
- `collectMetrics()` collects and **resets**; `collectMetrics(false)` collects without
reset; `visitMetrics(visitor)` for streaming.
- `ServerMetrics` exposes `queryMetrics()`, `timedMetrics()`, `countMetrics()`.
- `MetaQueryMetric` exposes `name()`, `label()`, `type()` (the queried `Class<?>`),
`sql()`, `hash()`, plus timing `count()` / `total()` / `max()` / `mean()`.
---
## Mapping to avaje-metrics tags
When integrating with **avaje-metrics** (`avaje-metrics-ebean`
`DatabaseMetricSupplier`), the flat `orm.`/`dto.`/`sql.` names are translated to a tagged
form, with the bean type carried as a `type` tag:
```
ebean.query{kind=orm|dto|sql, type=<BeanSimpleName>, label=<rest of the name>}
```
Because the entity is available as the `type` tag, two different-entity queries that
share a profile-location name remain distinct series on tag-aware backends (OpenTelemetry,
Prometheus, StatsD) without needing the bean type in the name.
For the integration setup, see the avaje-metrics guide
[`add-ebean-metrics.md`](https://github.com/avaje/avaje-metrics/blob/master/docs/guides/add-ebean-metrics.md).
To capture the database execution plan (`EXPLAIN`) for slow queries identified by these
metrics, see [Ebean query plan capture](ebean-query-plan-capture.md).
---
## Troubleshooting
### A query shows up as `orm.<Bean>.findList` (no useful identity)
It has neither a label nor a profile location. Add `setLabel(..)` or a
`ProfileLocation`, or apply a profile location on the finder / query bean.
### Two queries in one method share a metric name
This happens when the profile location for those call sites has no line number. With
enhancement, many call sites already include a line number; for those that don't, use
`ProfileLocation.createWithLine()` to separate them by line, or give each an explicit
`setLabel(..)`. On tag-aware backends the avaje-metrics `type` tag already separates
different entity types.
### A secondary (lazy / query) load isn't grouped under its parent
Secondary names extend the parent's full name. If the parent has no label or profile
location, its name falls back to `orm.<Bean>.<queryType>` and the secondary extends
that. Give the root query a label or profile location for a stable parent name.
+233
View File
@@ -0,0 +1,233 @@
# Guide: Ebean query plan capture
## Purpose
This guide explains how to enable and configure **query plan capture** in Ebean — the
mechanism that captures the database's actual execution plan (via `EXPLAIN`) for slow
queries, so you can diagnose missing indexes and poor plans in production.
Use this guide when you want Ebean to record real query plans, when tuning the capture
thresholds and load limits, or when wiring a listener to ship captured plans somewhere.
---
## Overview
Query plan capture is a **two-phase** mechanism:
1. **Bind capture** — when enabled, Ebean watches query executions and, for queries
slower than a threshold, captures the actual **bind values** that were used. This is
cheap: it just remembers the parameters of a slow execution.
2. **Plan capture** — using those captured bind values, Ebean runs `EXPLAIN <sql>`
against the database to obtain the execution plan, producing `MetaQueryPlan` results
that are handed to a `QueryPlanListener`.
Plan capture is split this way so the expensive `EXPLAIN` work (actual database load)
happens periodically or on demand, against representative bind values, rather than on
every slow query.
Two ways to trigger phase 2:
- **Automatic periodic capture** — a background timer collects plans on a schedule.
- **On demand** — call the `MetaInfoManager` API to arm and collect plans yourself
(this is what remote tooling such as ebean-insight uses).
Plan capable queries are:
- **ORM entity SELECT queries** (`orm.*` metrics) — captured via the per-entity `BeanDescriptor`.
- **Native-SQL `DtoQuery`** (`dto.*` metrics) — a `DtoQuery` created from a SQL string
(`DB.findDto(MyDto.class, "select ...")`) has its own bind capture and is `EXPLAIN`'d directly.
- **ORM-backed `DtoQuery`** (`Query.asDto(...)`) — captured via the *underlying* ORM query plan
(`orm.*`), not the `dto.*` plan. The `dto.*` plan itself is **not** armed in this case, so it
does not double-count in `queryPlanInit`.
- **Native-SQL `SqlQuery`** (`sql.query.*` metrics) — a **labelled** `SqlQuery`
(`DB.sqlQuery("select ...").setLabel("myLabel")`) has its own bind capture and is `EXPLAIN`'d
directly. A label is required: without `setLabel(...)` the query produces no metric and no plan.
Specifically **excluded** are:
- **Update / DML** — `orm.update.*`, `iud.*`, `sql.update.*`, `sql.call.*`.
Bind capture is wired into the ORM query path (per-entity `BeanDescriptor`), the native-SQL DTO
path (per-DTO `DtoBeanDescriptor`), and the native-SQL `SqlQuery` path (the relational query
engine); the init/collect API iterates all three. DML — even though it produces timing metrics —
never captures bind values and cannot be `EXPLAIN`'d.
> **Cost when disabled:** SqlQuery plan capture is fully gated on the `queryPlan.enable` master
> switch. When capture is disabled no `SqlQuery` plans are created or cached, so labelled queries
> incur no extra cost beyond their existing timing metric.
---
## Step 1 - Enable bind capture
Bind capture is the master switch; nothing is captured until it is on.
```java
Database database = Database.builder()
.queryPlanEnable(true) // turn on bind capture
.queryPlanThresholdMicros(100_000) // capture binds for queries slower than 100ms
.build();
```
- `queryPlanEnable(boolean)` — enable bind capture. Default **false**.
- `queryPlanThresholdMicros(long)` — global execution-time threshold (microseconds) a
query must exceed before its bind values are captured. Default **`Long.MAX_VALUE`**
(effectively off), so you must either lower it or arm specific plans by hash (Step 3).
Equivalent `application.properties` (avaje-config / properties):
```properties
queryPlan.enable=true
queryPlan.thresholdMicros=100000
```
---
## Step 2 - Enable automatic periodic capture (optional)
To have Ebean periodically run `EXPLAIN` for armed queries and report the plans:
```java
Database database = Database.builder()
.queryPlanEnable(true)
.queryPlanThresholdMicros(100_000)
.queryPlanCapture(true) // turn on the periodic capture timer
.queryPlanCapturePeriodSecs(600) // every 10 minutes (default)
.queryPlanCaptureMaxTimeMillis(10_000) // stop after 10s of capturing per cycle
.queryPlanCaptureMaxCount(10) // at most 10 plans per cycle
.queryPlanListener(capture -> {
for (var plan : capture.plans()) {
System.out.println(plan.label() + "\n" + plan.plan());
}
})
.build();
```
- `queryPlanCapture(boolean)` — enable the background periodic capture. Default **false**.
- `queryPlanCapturePeriodSecs(long)` — capture frequency in seconds. Default **600** (10 min).
- `queryPlanCaptureMaxTimeMillis(long)` — per-cycle time budget; capture stops once
exceeded, bounding the database load. Default **10000** (10s).
- `queryPlanCaptureMaxCount(int)` — max plans captured per cycle. Default **10**.
- `queryPlanListener(QueryPlanListener)` — receives each `QueryPlanCapture`. If not set,
the default listener logs plans to the `io.ebean.QUERYPLAN` logger at `INFO`.
Properties form:
```properties
queryPlan.enable=true
queryPlan.thresholdMicros=100000
queryPlan.capture=true
queryPlan.capturePeriodSecs=600
queryPlan.captureMaxTimeMillis=10000
queryPlan.captureMaxCount=10
```
---
## Step 3 - Capture on demand (foreground)
Instead of (or in addition to) the periodic timer, drive capture through
`database.metaInfo()`. This is useful for targeted capture and is how remote tooling
arms specific slow queries by their plan hash.
```java
import io.ebean.meta.MetaInfoManager;
import io.ebean.meta.MetaQueryPlan;
import io.ebean.meta.QueryPlanInit;
import io.ebean.meta.QueryPlanRequest;
MetaInfoManager meta = database.metaInfo();
// Phase 1: arm bind capture - either all plans or specific hashes
QueryPlanInit init = new QueryPlanInit();
init.setAll(true); // or init.add("<planHash>", 50_000);
init.thresholdMicros(100_000);
List<MetaQueryPlan> armed = meta.queryPlanInit(init);
// ... let the application run so slow executions capture their bind values ...
// Phase 2: collect plans now (runs EXPLAIN)
QueryPlanRequest request = new QueryPlanRequest();
request.maxCount(10);
request.maxTimeMillis(10_000);
request.since(System.currentTimeMillis() - 300_000); // binds at least ~5 min old
List<MetaQueryPlan> plans = meta.queryPlanCollectNow(request);
```
- `QueryPlanInit` arms bind capture. `setAll(true)` arms every plan; `add(hash, micros)`
arms a specific plan (a hash of `"all"` is treated as all).
- `QueryPlanRequest.since(epochMillis)` ensures the captured bind values have existed for
a while, so they better represent the slowest executions. `maxCount` / `maxTimeMillis`
bound the work, mirroring the periodic settings.
`MetaQueryPlan` exposes `beanType()`, `label()`, `profileLocation()`, `sql()`, `hash()`,
`bind()`, `plan()` (the raw EXPLAIN output), `queryTimeMicros()`, `captureCount()`,
`captureMicros()`, and `whenCaptured()`.
---
## Step 4 - EXPLAIN dialect
Ebean chooses the `EXPLAIN` statement per database platform:
| Platform | EXPLAIN used |
|---|---|
| PostgreSQL | `explain (analyze, costs, verbose, buffers) <sql>` |
| YugabyteDB | `explain (analyze, buffers, dist) <sql>` |
| Oracle | `EXPLAIN PLAN FOR <sql>` |
| SQL Server | platform-specific logger |
| H2 / MySQL / other | `explain <sql>` |
Override the prefix with `queryPlanExplain(..)` (or `queryPlan.explain`):
```java
Database.builder()
.queryPlanExplain("explain (costs, verbose)") // omit ANALYZE on Postgres
.build();
```
> **Caution (PostgreSQL / Yugabyte):** the default includes `ANALYZE`, which **actually
> executes** the query to produce real timings. For non-idempotent or expensive queries,
> override with a non-ANALYZE `explain` to avoid side effects and extra load.
---
## Related setting: internal plan TTL
`queryPlanTTLSeconds(int)` (default **300**) is a **different** concept — it is the time to
live for Ebean's *internal* query plan (the object that knows how to execute a query, read
the result set and collect metrics). It is not part of EXPLAIN capture, but is set through
the same builder.
---
## Troubleshooting
### No plans are captured
1. `queryPlanEnable(true)` must be set — it is the master switch.
2. `queryPlanThresholdMicros` defaults to `Long.MAX_VALUE`. Lower it, or arm specific
plans via `QueryPlanInit`, otherwise no execution is ever "slow enough".
3. For periodic capture, also set `queryPlanCapture(true)`.
4. Queries must actually run slower than the threshold to have their binds captured.
### Plans appear but nothing is reported anywhere
No `queryPlanListener` is configured, so plans go to the default `io.ebean.QUERYPLAN`
logger. Set a listener, or enable `INFO` logging for `io.ebean.QUERYPLAN`.
### Capture adds noticeable database load
`EXPLAIN ANALYZE` executes the query. Reduce `queryPlanCaptureMaxCount`, increase
`queryPlanCapturePeriodSecs`, tighten `queryPlanCaptureMaxTimeMillis`, or override
`queryPlanExplain` to a non-ANALYZE form.
### An unlabelled SqlQuery or update metric never offers plan capture
ORM entity SELECT queries (`orm.*`), native-SQL `DtoQuery` (`dto.*`) and native-SQL
**labelled** `SqlQuery` (`sql.query.*`) are plan capable. ORM-backed DTO queries
(`Query.asDto(...)`) are captured via their underlying ORM plan (`orm.*`), not the `dto.*` plan.
An unlabelled `SqlQuery` produces no metric and no plan — add `setLabel(...)` to make it
capturable. Write metrics (`orm.update.*`, `iud.*`, `sql.update.*`, `sql.call.*`) have no bind
capture and are intentionally excluded.
+797
View File
@@ -0,0 +1,797 @@
# Entity Bean Creation Guide for AI Agents
**Target Audience:** AI systems (Claude, Copilot, ChatGPT, etc.)
**Purpose:** Learn how to generate clean, idiomatic Ebean entity beans
**Key Insight:** Ebean entity fields must be non-public (no public fields). Accessors don't need JavaBeans naming conventions; no manual equals/hashCode implementation is needed
**Language:** Java
**Framework:** Ebean ORM
---
## Quick Rules
Before writing entity code, remember:
| Requirement | Needed? | Notes |
|-------------|---------|-----------------------------------------------------------------------------------------------------------------------|
| `@Entity` annotation | ✅ **YES** | Marks class as persistent entity |
| `@Id` annotation | ✅ **YES** | Marks primary key field |
| Getters/setters (or other accessors) | ✅ **YES** | Needed for application code to access fields. Naming can be JavaBeans, fluent, or custom — no specific convention required. |
| Default constructor | ❌ **NO** | Not required. Ebean can instantiate without it. |
| equals/hashCode | ❌ **NO** | Ebean auto-enhances these at compile time. |
| toString() | ❌ **NO** | Ebean auto-enhances this. Don't implement with getters. |
| `@Version` | ⚠️ **OPTIONAL** | Use for optimistic locking. Highly recommended. |
| `@WhenCreated` | ⚠️ **OPTIONAL** | Auto-timestamp creation time. Highly recommended. Use for audit trail. |
| `@WhenModified` | ⚠️ **OPTIONAL** | Auto-timestamp modification time. Highly recommended. Use for audit trail. |
**Critical:**
- Prefer primitive `long` for `@Id` and `@Version`, NOT `Long` object.
- Fields should be non-public: **private**, **protected**, or package-private.
- If you add accessors, they do NOT need to follow Java bean conventions.
---
## Naming Conventions: The D* (Domain) Prefix Pattern
Entity beans represent internal domain/persistence model details. It's a common best practice in Ebean projects to use the **D* prefix** (D for Domain) for entity class names.
**Why use D* prefix?**
1. **Avoid name clashes with DTOs** - Your public API may have `Customer` (DTO), but your entity is `DCustomer` (Domain). They're clearly different.
2. **Signal intent clearly** - The D prefix immediately tells developers "this is an internal domain class, not part of the public API"
3. **Clarify conversions** - When converting `DCustomer``Customer` (DTO), the direction is obvious
4. **Separate concerns** - API classes in one package (no prefix), domain classes in another (with D prefix)
**Example naming pattern:**
- Entity: `DCustomer`, `DOrder`, `DProduct`, `DInvoice`
- DTO: `Customer`, `Order`, `Product`, `Invoice`
- Converter: `DCustomerMapper.toDTO(DCustomer)``Customer`
**Where to place entities:**
- Entities: `com.example.domain.entity` (or `persistence`)
- DTOs: `com.example.api.model` or `com.example.dto`
**When to use D* prefix:**
-**DO** use for entity beans (internal domain model)
-**DO** use when you have parallel DTO classes with similar names
-**DON'T** use for DTOs or public API classes
-**DON'T** use if you have no DTOs and entities are your public API
Example with and without prefix:
```java
// With D* prefix (recommended - allows both entity and DTO to exist)
@Entity
public class DCustomer {
@Id private long id;
private String name;
// ... entity-specific fields and methods
}
// Public API DTO (no D prefix)
public record Customer(long id, String name) {
// ... conversion method
}
// Conversion
public static Customer toDTO(DCustomer entity) {
return new Customer(entity.getId(), entity.getName());
}
```
This naming convention is optional but highly recommended for projects with separate domain and API layers.
---
## Minimal Entity (No Boilerplate)
This is a complete, valid Ebean entity:
```java
@Entity
public class Customer {
@Id
private long id;
private String name;
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
**Why this works:**
-`@Entity` marks it as persistent
-`@Id private long id` is the primary key
- ✅ Private fields (Ebean does NOT support public fields without expert flags enabled)
- ✅ Accessors can follow any naming convention, and can be omitted when field access is preferred
- ✅ No default constructor needed
- ✅ No equals/hashCode needed (Ebean enhances these)
**What Ebean does at compile time:**
- Enhances equals/hashCode based on @Id
- Adds field change tracking
- Enables lazy loading
- Enhances toString()
**Result:** Your entity is now fully functional with zero boilerplate.
---
## Pattern 1: Basic Entity
**Use this when:** You need a simple persistent object.
```java
@Entity
public class Product {
@Id
private long id;
private String name;
private String description;
private BigDecimal price;
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
```
**What you get:**
- Primary key: `id` (private field, accessed via getter)
- Three properties: `name`, `description`, `price` (private fields, accessed via getters/setters)
- Automatic equals/hashCode based on id
- Full ORM functionality
---
## Pattern 2: Entity with Audit Trail
**Use this when:** You need to track who/when created/modified data.
```java
@Entity
public class Order {
@Id
private long id;
@Version
private long version;
@WhenCreated
private Instant createdAt;
@WhenModified
private Instant modifiedAt;
private String orderNumber;
private BigDecimal totalAmount;
public long getId() {
return id;
}
public long getVersion() {
return version;
}
public Instant getCreatedAt() {
return createdAt;
}
public Instant getModifiedAt() {
return modifiedAt;
}
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public BigDecimal getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(BigDecimal totalAmount) {
this.totalAmount = totalAmount;
}
}
```
**What you get:**
- `version`: Optimistic locking (prevents concurrent update conflicts)
- `createdAt`: Automatically set when inserted (Ebean manages this)
- `modifiedAt`: Automatically updated on every modification (Ebean manages this)
**Example usage:**
```java
// Create
Order order = new Order();
order.setOrderNumber("ORD-001");
order.setTotalAmount(new BigDecimal("99.99"));
database.save(order); // createdAt is automatically set by Ebean
// Modify
order.setTotalAmount(new BigDecimal("109.99"));
database.update(order); // version incremented, modifiedAt updated automatically
// Check when modified
System.out.println(order.getModifiedAt()); // Current timestamp
```
---
## Pattern 3: Entity with Constructor
**Use this when:** Domain logic requires initialization or validation.
```java
@Entity
public class Invoice {
@Id
private long id;
@Version
private long version;
private String invoiceNumber;
private String customerName;
private BigDecimal amount;
public Invoice(String invoiceNumber, String customerName, BigDecimal amount) {
this.invoiceNumber = invoiceNumber;
this.customerName = customerName;
this.amount = amount;
}
public long getId() {
return id;
}
public long getVersion() {
return version;
}
public String getInvoiceNumber() {
return invoiceNumber;
}
public String getCustomerName() {
return customerName;
}
public BigDecimal getAmount() {
return amount;
}
}
```
**When to add a constructor:**
- ✅ Required fields must be set during creation
- ✅ Validation needs to happen on initialization
- ✅ Domain logic needs setup
**When NOT to add:**
- ❌ If users will just set fields afterwards anyway
- ❌ If there are many optional fields
---
## Pattern 4: Entity with Relationships
**Use this when:** You need associations to other entities.
```java
@Entity
public class Customer {
@Id
private long id;
@Version
private long version;
@WhenCreated
private Instant createdAt;
private String name;
private String email;
@OneToMany(mappedBy = "customer")
private List<Order> orders; // Use List, not Set
@ManyToOne
private Address billingAddress;
public long getId() {
return id;
}
public long getVersion() {
return version;
}
public Instant getCreatedAt() {
return createdAt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Order> getOrders() {
return orders;
}
public Address getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(Address billingAddress) {
this.billingAddress = billingAddress;
}
}
```
**Important:**
- Use `List<>` not `Set<>` for collections (Set calls equals/hashCode before beans have IDs)
- `mappedBy` means Order.customer is the owner
- Relationships are lazy-loaded by default
---
## What NOT to Do (Anti-Patterns)
### ❌ Anti-Pattern 1: Public Fields
**DON'T:**
```java
@Entity
public class Customer {
@Id public long id; // ❌ Public field - not supported
public String name; // ❌ Public field - not supported
}
```
**DO:**
```java
@Entity
public class Customer {
@Id
private long id; // ✅ Private field with getter
private String name; // ✅ Private field with accessors
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
**Why:** Ebean does NOT support public fields. Fields must be private and accessed via getters/setters or other accessor methods. Public fields bypass Ebean's tracking mechanisms and will cause data consistency issues.
---
### ❌ Anti-Pattern 2: Use Long Object Instead of Primitive
**DON'T:**
```java
@Entity
public class Customer {
@Id
private Long id; // ❌ Object type
private String name;
}
```
**DO:**
```java
@Entity
public class Customer {
@Id
private long id; // ✅ Primitive type
private String name;
}
```
**Why:** Performance, nullability semantics, Ebean optimization.
---
### ❌ Anti-Pattern 3: Implement equals/hashCode
**DON'T:**
```java
@Entity
public class Customer {
@Id
private long id;
private String name;
@Override
public boolean equals(Object o) { // ❌ Unnecessary
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Customer customer = (Customer) o;
return id == customer.id;
}
@Override
public int hashCode() { // ❌ Unnecessary
return Objects.hash(id);
}
}
```
**DO:**
```java
@Entity
public class Customer {
@Id
private long id;
private String name;
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Ebean enhances equals/hashCode automatically
}
```
**Why:** Ebean's enhancement is optimized for ORM operations. Your implementation might conflict with Ebean's tracking.
---
### ❌ Anti-Pattern 4: Use Set for Collections
**DON'T:**
```java
@Entity
public class Customer {
@Id
private long id;
@OneToMany(mappedBy = "customer")
private Set<Order> orders; // ❌ Set calls equals/hashCode before IDs assigned
}
```
**DO:**
```java
@Entity
public class Customer {
@Id
private long id;
@OneToMany(mappedBy = "customer")
private List<Order> orders; // ✅ List doesn't require equals/hashCode on unsaved beans
}
```
**Why:** Set calls equals/hashCode immediately. New beans don't have IDs yet, causing issues.
---
### ❌ Anti-Pattern 5: toString() with Getters
**DON'T:**
```java
@Entity
public class Customer {
@Id
private long id;
private String name;
@Override
public String toString() { // ❌ Uses getters
return "Customer{" +
"id=" + getId() +
", name='" + getName() + '\'' +
'}';
}
public long getId() { return id; }
public String getName() { return name; }
}
```
**Why:** In a debugger, toString() is called automatically. Getters can trigger lazy loading, changing debug behavior.
**DO:** Either don't implement toString(), or access fields directly:
```java
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
```
---
### ❌ Anti-Pattern 6: @Column(name=...) for Naming Convention
**DON'T:**
```java
@Entity
public class Customer {
@Id
private long id;
@Column(name = "first_name") // ❌ Unnecessary
private String firstName;
}
```
**DO:**
```java
@Entity
public class Customer {
@Id
private long id;
private String firstName; // ✅ Ebean uses naming convention: first_name
}
```
**Why:** Ebean's naming convention handles this automatically. Only use @Column when your database column doesn't match the convention.
---
## What Ebean Enhancement Provides
At compile time, Ebean enhances your entity classes:
1. **equals/hashCode** - Based on @Id, optimal for ORM
2. **Field change tracking** - Knows which fields were modified
3. **Lazy loading** - Collections and relationships load on demand
4. **Persistence context** - Manages identity and state
5. **toString()** - Auto-implemented (don't override with getters)
**Result:** Your entity bean is minimal, but fully featured.
---
## Field Types
**Recommended for ID/Version:**
- `long` (primitive) ✅ Use this
- `int` (primitive) ✅ Use this
- `UUID` ✅ Use this
**Not recommended:**
- `Long` object ⚠️ Avoid (use primitive long)
- `Integer` object ⚠️ Avoid (use primitive int)
**For other fields:**
- Use standard Java types: `String`, `BigDecimal`, `Instant`, `LocalDate`, etc.
- Use primitives where nullable semantics don't apply: `int`, `long`, `boolean`
- Use objects where null has meaning: `String`, `BigDecimal`, `LocalDate`
---
## Example: Building an Entity Step by Step
Start minimal, add what you need:
**Step 1: Minimal**
```java
@Entity
public class BlogPost {
@Id long id;
String title;
String content;
public long getId() { return id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
}
```
**Step 2: Add audit trail**
```java
@Entity
public class BlogPost {
@Id long id;
@Version long version;
@WhenCreated Instant createdAt;
@WhenModified Instant modifiedAt;
String title;
String content;
public long getId() { return id; }
public long getVersion() { return version; }
public Instant getCreatedAt() { return createdAt; }
public Instant getModifiedAt() { return modifiedAt; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
}
```
**Step 3: Add author relationship**
```java
@Entity
public class BlogPost {
@Id long id;
@Version long version;
@WhenCreated Instant createdAt;
@WhenModified Instant modifiedAt;
String title;
String content;
@ManyToOne
Author author;
public long getId() { return id; }
public long getVersion() { return version; }
public Instant getCreatedAt() { return createdAt; }
public Instant getModifiedAt() { return modifiedAt; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public Author getAuthor() { return author; }
public void setAuthor(Author author) { this.author = author; }
}
```
**Step 4: Add constructor if needed**
```java
@Entity
public class BlogPost {
@Id long id;
@Version long version;
@WhenCreated Instant createdAt;
@WhenModified Instant modifiedAt;
String title;
String content;
@ManyToOne
Author author;
public BlogPost(String title, String content, Author author) {
this.title = title;
this.content = content;
this.author = author;
}
public long getId() { return id; }
public long getVersion() { return version; }
public Instant getCreatedAt() { return createdAt; }
public Instant getModifiedAt() { return modifiedAt; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public Author getAuthor() { return author; }
public void setAuthor(Author author) { this.author = author; }
}
```
Each step adds only what's necessary for the entity structure. Accessors are always included so application code can use the entity.
---
## Usage Examples
### Creating and saving
```java
Customer customer = new Customer();
customer.setName("Alice");
database.save(customer); // id auto-generated
```
### Finding
```java
Customer found = database.find(Customer.class, 1);
System.out.println(found.getName());
```
### Updating
```java
found.setName("Bob");
database.update(found); // version auto-incremented
```
### Collections (relationships)
```java
Customer customer = database.find(Customer.class, 1);
List<Order> orders = customer.getOrders(); // Lazy loads automatically
```
---
## Summary for AI Agents
When generating Ebean entity beans:
**DO:**
- Use primitive `long` for @Id and @Version
- Keep entities minimal (just fields + @Entity + @Id)
- Use @Version for concurrency control
- Use @WhenCreated/@WhenModified for audit trail
- Use List for collections, not Set
- Add constructors only if domain logic requires it
- Add getters/setters for all fields that application code needs to read or write
**DON'T:**
- Use Long object for @Id/@Version
- Implement equals/hashCode
- Implement toString() with getters
- Use Set for @OneToMany/@ManyToMany
- Add unnecessary @Column annotations
- Add default constructors "just in case"
**Result:** Clean, readable, maintainable entity beans with full ORM functionality and zero boilerplate.
---
## Related Documentation
- Entity Bean Best Practices: `/docs/best-practice/`
- JPA Mapping Reference: `/docs/mapping/jpa/`
- Ebean Extensions: `/docs/mapping/extensions/`
- First Entity Guide: `/docs/intro/first-entity/`
+136
View File
@@ -0,0 +1,136 @@
# Immutable bean cache for read-only references
This guide shows how to use `ImmutableBeanCache` for read-mostly assoc-one
references (for example `Label` references reused across many entities).
Use this when you want:
- fewer lazy-load SQL calls for assoc-one references via caching
- reusable fetch-group-based loading for cache misses
---
## Step 1 - Build an immutable cache (typical via builder)
```java
FetchGroup<Label> fetchGroup = FetchGroup.of(Label.class)
.select("version")
.fetch("labelTexts", "locale, localeText")
.build();
ImmutableBeanCache<Label> labelCache = ImmutableBeanCaches.builder(Label.class)
.loading(database, fetchGroup)
.maxSize(10_000)
.maxIdleSeconds(300)
.maxSecondsToLive(6_000)
.build();
```
`loading(...)` uses the query shape:
- `select(fetchGroup)`
- `setUnmodifiable(true)`
- `where().idIn(ids)`
- `findMap()`
Alternative domain example:
```java
FetchGroup<Customer> customerGroup = FetchGroup.of(Customer.class)
.select("name,version")
.fetch("billingAddress", "line1,city")
.fetch("shippingAddress", "line1,city")
.build();
ImmutableBeanCache<Customer> customerCache = ImmutableBeanCaches.builder(Customer.class)
.loading(database, customerGroup)
.build();
```
---
## Step 2 - Attach cache to the root query
```java
AttributeDescriptor one = DB.find(AttributeDescriptor.class)
.setId(id)
.setUnmodifiable(true)
.using(labelCache)
.findOne();
```
`using(...)` is on the root query. Ebean will use this cache for matching
bean types when resolving references.
---
## Use loading helper for simple memoization
If you don't need policy controls, use the shorthand helper:
```java
ImmutableBeanCache<Label> labelCache =
ImmutableBeanCaches.loading(Label.class, database, FetchGroup.of(Label.class, "version"));
```
With `ebean-core` on the classpath, builder policy settings are backed by core
cache implementation (including periodic trim / eviction).
---
## Unmodifiable vs mutable query behavior
### Unmodifiable query path
`setUnmodifiable(true)` disables lazy loading. If you need association content
in cached beans make sure that is included in the fetch group.
```java
FetchGroup<Label> withTexts = FetchGroup.of(Label.class)
.select("version")
.fetch("labelTexts", "locale, localeText")
.build();
```
### Mutable query path
On a mutable query (no `setUnmodifiable(true)`), references populated from the
immutable cache are still mutable beans in that object graph. Additional
unloaded properties can still lazy load as normal.
Typical pattern:
1. cache serves already-loaded reference properties (for example `version`)
2. later access to unloaded properties (for example `labelTexts`) triggers
normal lazy loading
---
## Understand secondary query behavior (`+query`, `+lazy`)
When root queries execute secondary loads (`fetchQuery(...)` or `fetchLazy(...)`),
the immutable caches configured on the root query are propagated to those
secondary queries.
That means assoc-one references resolved in secondary query paths can still hit
the immutable cache.
---
## Operational note (TTL / max size)
Use `ImmutableBeanCaches.builder(...)` when you need explicit TTL/max-size
policy. `ImmutableBeanCaches.loading(...)` remains the simple helper for
loader-based memoization.
---
## Testing checklist
1. Hit / partial hit / miss behavior for `getAll(ids)`
2. Unmodifiable path: no lazy SQL when reading loaded reference properties
3. Mutable path: additional unloaded properties can still lazy load
4. Secondary `fetchQuery` and `fetchLazy` paths inherit immutable caches
5. If needed associations are in fetch group, assert no extra SQL for those
accesses
@@ -0,0 +1,206 @@
# Guide: Using Lombok with Ebean Entity Beans
## Purpose
This guide explains which Lombok annotations are safe and recommended for Ebean
entity beans, which ones to avoid, and why. It is written as prescriptive instructions
for AI agents and developers.
---
## The Core Rule
> **Do NOT use `@Data` on Ebean entity beans.**
Use `@Getter` + `@Setter` instead, with the optional `@Accessors(chain = true)` for
a fluent setter style.
---
## Why `@Data` is Incompatible with Ebean
`@Data` is a convenience annotation that is equivalent to applying `@Getter`,
`@Setter`, `@RequiredArgsConstructor`, `@ToString`, and `@EqualsAndHashCode` together.
Three of those are problematic for Ebean entity beans:
### 1. `@EqualsAndHashCode` (included in `@Data`) — breaks entity identity
`@Data` generates `hashCode()` and `equals()` based on all non-static, non-transient
fields. Ebean entity beans have identity semantics — two references to the same database
row should be considered equal based on their `@Id` value, not field-by-field comparison.
Problems caused:
- Inconsistent `hashCode` before and after persist (the `@Id` field is `0` on a new
entity, then changes after insert — violating the `hashCode` contract for collections)
- Entities placed in a `Set` or `HashMap` before saving will be unfindable after saving
- Ebean's internal identity map and dirty checking can be confused
### 2. `@ToString` (included in `@Data`) — triggers unexpected lazy loading
`@Data` generates a `toString()` that accesses **all** fields, including
`@OneToMany` and `@ManyToOne` associations. Accessing an unloaded lazy association
outside of a transaction triggers a `LazyInitialisationException` or fires an unexpected
SQL query, which can:
- Cause subtle bugs in logging statements
- Trigger N+1 queries in test output or debug logging
- Fail with an exception if no active transaction exists
### 3. `@RequiredArgsConstructor` (included in `@Data`) — unnecessary for Ebean
Ebean does not require a default constructor — it can construct entity instances without
one. `@RequiredArgsConstructor` therefore adds nothing useful to entity beans.
---
## Recommended Annotation Set
Use exactly these three Lombok annotations on every Ebean entity bean:
```java
@Entity
@Getter
@Setter
@Accessors(chain = true)
@Table(name = "my_table")
public class MyEntity {
// ...
}
```
| Annotation | Purpose |
|---|---|
| `@Getter` | Generates `getFoo()` / `isFoo()` accessor methods |
| `@Setter` | Generates `setFoo(value)` mutator methods; Ebean enhancement intercepts these for dirty tracking |
| `@Accessors(chain = true)` | Makes setters return `this`, enabling fluent/builder-style property setting |
---
## `@Accessors(chain = true)` — Fluent Setter Style
With `chain = true`, setters return `this` instead of `void`, allowing method chaining:
```java
// without chain = true (void setters)
CMachine machine = new CMachine();
machine.setMake("Toyota");
machine.setModel("Hilux");
machine.setStatus("active");
// with @Accessors(chain = true)
CMachine machine = new CMachine()
.setMake("Toyota")
.setModel("Hilux")
.setStatus("active");
```
This is particularly useful when building test data:
```java
CMachine machine = new CMachine()
.setGid(UUID.randomUUID())
.setMachineType("HV")
.setStatus("active")
.setMake("Komatsu")
.setModel("PC200");
database.save(machine);
```
Ebean's bytecode enhancement is fully compatible with chained setters — the
enhancement intercepts each `setFoo()` call to record which fields have been modified
(dirty checking), regardless of whether the setter returns `void` or `this`.
---
## `@Accessors(fluent = true)` — also compatible
`@Accessors(fluent = true)` removes the `get`/`set`/`is` prefix, generating `name()`
(getter) and `name(value)` (setter) instead of `getName()` and `setName(value)`.
Ebean does **not** require JavaBeans naming conventions — it can work with any accessor
method style, including fluent accessors with no prefix. `@Accessors(fluent = true)` is
therefore compatible with Ebean.
`@Accessors(chain = true)` is the more common choice in practice (it keeps the familiar
`get`/`set` prefix while adding method chaining), but `fluent = true` is a valid
alternative if that style is preferred consistently across the codebase.
---
## Full Entity Bean Example
```java
package com.example.repository.data;
import io.ebean.annotation.WhenCreated;
import io.ebean.annotation.WhenModified;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
@Entity
@Getter
@Setter
@Accessors(chain = true)
@Table(name = "machine")
public class CMachine {
@Id
private long id;
@Version
private int version;
@Column(nullable = false, unique = true)
private UUID gid;
@Column(nullable = false, length = 10)
private String machineType;
@Column(length = 200)
private String make;
@Column(length = 200)
private String model;
@WhenCreated
private Instant created;
@WhenModified
private Instant lastModified;
}
```
---
## Summary: Lombok Annotations and Ebean Compatibility
| Lombok Annotation | Compatible? | Notes |
|---|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `@Getter` | ✅ Safe | Use on every entity bean |
| `@Setter` | ✅ Safe | Use on every entity bean; enhancement intercepts these |
| `@Accessors(chain = true)` | ✅ Safe | Recommended for fluent construction style |
| `@ToString` | ❌ Avoid | Ebean does a better job and handles recursion |
| `@EqualsAndHashCode` | ❌ Avoid | Breaks entity identity and `@Id`-based equality |
| `@Data` | ❌ Avoid | Includes `@EqualsAndHashCode` and `@ToString` — both problematic |
| `@Value` | ❌ Avoid | Makes fields final — incompatible with Ebean's field-level bytecode enhancement |
| `@Accessors(fluent = true)` | ✅ Safe | Removes `get`/`set` prefix — Ebean does not require JavaBeans naming conventions and works with any accessor style |
| `@Builder` | ⚠️ Careful | Usable on non-entity helper/factory classes; on entity beans it requires a no-arg constructor alongside it and offers no advantage over `@Accessors(chain = true)` |
---
## Relationship with Ebean Bytecode Enhancement
Ebean's bytecode enhancement (applied by `ebean-maven-plugin` at build time) modifies
the `setXxx()` methods of entity beans to:
1. Mark the field as dirty (changed) so only modified fields are included in UPDATE statements
2. Support lazy loading of associations when a getter is called on an unloaded field
For this to work correctly, Ebean needs:
- Accessor methods for each persistent field (any naming style is fine — `getFoo()`, `foo()`, or no accessors at all; Ebean can also access fields directly)
- No override of `hashCode()` / `equals()` that would interfere with the identity map — which means **no `@Data` or `@EqualsAndHashCode`**
@@ -0,0 +1,242 @@
# Guide: Migrate from `DatabaseConfig` / `DatabaseFactory` to `Database.builder()`
## Purpose
This guide shows how to migrate legacy programmatic database creation code from:
- `new DatabaseConfig()`
- `DatabaseFactory.create(...)`
- old `setXxx(...)` builder-style configuration methods
…to the preferred builder-based style using:
- `Database.builder()`
- fluent `DatabaseBuilder` methods such as `name(...)`, `register(...)`, and `defaultDatabase(...)`
- `DatabaseBuilder.build()`
Use this guide when upgrading older Ebean setup code or when building an automated/semi-automated migration.
---
## Preferred pattern
Prefer code shaped like this:
```java
Database database = Database.builder()
.name("db")
.loadFromProperties()
.dataSourceBuilder(dataSource)
.register(true)
.defaultDatabase(true)
.build();
```
The important points are:
1. Start with `Database.builder()`
2. Configure via `DatabaseBuilder`
3. Finish with `.build()`
---
## Step 1 — Replace `new DatabaseConfig()` with `Database.builder()`
### Before
```java
DatabaseConfig config = new DatabaseConfig();
config.setName("db");
config.loadFromProperties();
```
### After
```java
DatabaseBuilder config = Database.builder()
.name("db")
.loadFromProperties();
```
### Notes
- Prefer the `DatabaseBuilder` type for local variables and parameters when possible.
- If existing code only uses standard builder methods, this change is usually mechanical.
- If existing code later reads configuration back, use `config.settings()`.
---
## Step 2 — Replace `DatabaseFactory.create(config)` with `config.build()`
### Before
```java
DatabaseConfig config = new DatabaseConfig();
config.setName("db");
config.loadFromProperties();
Database database = DatabaseFactory.create(config);
```
### After
```java
DatabaseBuilder config = Database.builder()
.name("db")
.loadFromProperties();
Database database = config.build();
```
### Short form
```java
Database database = Database.builder()
.name("db")
.loadFromProperties()
.build();
```
---
## Step 3 — Replace `DatabaseFactory.create("name")`
### Before
```java
Database database = DatabaseFactory.create("other");
```
### After
```java
Database database = Database.builder()
.name("other")
.loadFromProperties()
.build();
```
### Important
For **named databases**, set `.name("...")` before `.loadFromProperties()` so the named configuration is loaded.
---
## Step 4 — Replace legacy `setXxx(...)` methods with fluent builder methods
`DatabaseBuilder` already exposes preferred fluent names for most configuration methods.
Use those names when migrating older setup code.
| Legacy call | Preferred call |
|---|---|
| `setName("db")` | `name("db")` |
| `setRegister(false)` | `register(false)` |
| `setDefaultServer(false)` | `defaultDatabase(false)` |
| `setContainerConfig(cfg)` | `containerConfig(cfg)` |
| `setDbSchema("app")` | `dbSchema("app")` |
| `setDataSourceConfig(ds)` | `dataSourceBuilder(ds)` |
| `setReadOnlyDataSourceConfig(ro)` | `readOnlyDataSourceBuilder(ro)` |
| `setRunMigration(true)` | `runMigration(true)` |
| `setDisableClasspathSearch(true)` | `disableClasspathSearch(true)` |
| `setPersistBatch(batch)` | `persistBatch(batch)` |
### Full example
#### Before
```java
DatabaseConfig config = new DatabaseConfig();
config.setName("db");
config.setRegister(false);
config.setDefaultServer(false);
config.setDataSourceConfig(dataSource);
Database database = DatabaseFactory.create(config);
```
#### After
```java
Database database = Database.builder()
.name("db")
.register(false)
.defaultDatabase(false)
.dataSourceBuilder(dataSource)
.build();
```
---
## Step 5 — Verify semantics after migration
The migration should preserve behavior, but verify these points:
- `register(true)` is still the default
- `defaultDatabase(true)` is still the default
- call `loadFromProperties()` if the old code loaded configuration from properties
- for named databases, set the name before loading properties
- explicit entity registration via `addClass(...)` / `addAll(...)` is unchanged
- custom datasource wiring via `dataSourceBuilder(...)` and `readOnlyDataSourceBuilder(...)` is unchanged
---
## Manual-review cases
These cases are **not** simple search-and-replace migrations and should be reviewed manually:
### `DatabaseFactory.createWithContextClassLoader(...)`
There is no direct builder shorthand for this today. Keep this as-is for now and migrate the surrounding builder configuration first.
### `DatabaseFactory.initialiseContainer(...)`
This is a container lifecycle concern, not a normal database-builder call. Keep it as-is unless you are intentionally moving the `ContainerConfig` onto the first builder via `containerConfig(...)`.
### `DatabaseFactory.shutdown()`
This is also a lifecycle concern rather than normal builder setup. Leave it alone unless you are making a deliberate lifecycle change.
### Variables or method signatures typed as `DatabaseConfig`
If the code only uses standard builder operations, switch the type to `DatabaseBuilder`.
If the code depends on implementation-specific `DatabaseConfig` methods, review it manually.
### Code that needs read access to builder settings
Use:
```java
DatabaseBuilder builder = Database.builder();
DatabaseBuilder.Settings settings = builder.settings();
```
rather than relying on the concrete `DatabaseConfig` type only to read getters.
---
## Automation notes for AI agents and bulk refactors
This migration is a good candidate for semi-automated upgrading.
### Safe mechanical rewrites
These are usually safe to rewrite automatically:
- `new DatabaseConfig()``Database.builder()`
- `DatabaseFactory.create(builder)``builder.build()`
- `DatabaseFactory.create("name")``Database.builder().name("name").loadFromProperties().build()`
- legacy `setXxx(...)` calls → preferred fluent builder methods
### Flag for manual review
Automatically flag, but do not blindly rewrite:
- `DatabaseFactory.createWithContextClassLoader(...)`
- `DatabaseFactory.initialiseContainer(...)`
- `DatabaseFactory.shutdown()`
- parameters, fields, or return types declared as `DatabaseConfig`
- any use that clearly depends on `DatabaseConfig` implementation details rather than `DatabaseBuilder`
---
## Related guides
- [Database configuration](add-ebean-postgres-database-config.md) — preferred modern setup style using `Database.builder()`
- [Guide index](README.md) — full list of Ebean setup and migration guides
@@ -0,0 +1,447 @@
# Guide: Persist Changes and Manage Transactions with Ebean
## Purpose
This guide gives step-by-step instructions for AI agents and developers to save,
update, delete, and batch changes with Ebean while choosing the correct
transaction boundary.
Use this guide when you need to:
- create a new entity row
- update one or more existing rows
- delete rows safely
- decide between implicit transactions, `@Transactional`, and explicit
transactions
- batch or bulk-write many rows efficiently
The default recommendation is:
1. Choose the correct persistence operation first
2. Use implicit transactions for a single isolated write
3. Use `@Transactional` for multi-step application workflows
4. Use explicit transactions only when you need explicit control
5. Use bulk update or batching for large write sets
---
## Prerequisites
- The project already uses Ebean ORM
- Entity beans and database configuration already exist
- You know which `Database` is being used (`DB.getDefault()` or a named database)
If the project is not yet configured, first follow:
- [`add-ebean-postgres-database-config.md`](add-ebean-postgres-database-config.md)
- [`entity-bean-creation.md`](entity-bean-creation.md)
---
## Step 1 - Choose the correct persistence operation before editing code
Do not start with `database.save(...)` by habit. First decide what kind of change the
caller is making.
| Need | Preferred API | Use when |
|------|---------------|----------|
| Insert a bean that is definitely new | `database.insert(bean)` | New-create flow, seed data, fixture setup |
| Save a bean that may be new or existing | `database.save(bean)` | Common default when bean state determines insert vs update |
| Update a bean that is definitely existing | `database.update(bean)` | Existing row should be updated only |
| Delete one bean | `database.delete(bean)` | Remove a loaded entity bean |
| Update many rows without loading beans | `database.update(...)` or `query.asUpdate()` | Set-based write, not per-row business logic |
| Delete many rows without loading beans | bulk update/delete API or `database.sqlUpdate(...)` | Set-based deletion |
### Agent rule
Choose the operation that matches intent:
- known new row -> `insert`
- known existing row -> `update`
- uncertain/new-or-existing -> `save`
- many rows -> bulk update/delete, not a loop of individual saves
### Style note
Use a `Database` instance for all persistence operations: `database.save(bean)`,
`database.insert(bean)`, `database.update(bean)`, `database.delete(bean)`.
Inject the `Database` bean or obtain it via `DB.getDefault()`. Avoid using the
static `DB.*` convenience methods.
---
## Step 2 - Persist single-bean changes with the correct API
### Example - insert a known new bean
```java
Customer customer = new Customer();
customer.setName("Rob");
customer.setEmail("rob@example.com");
database.insert(customer);
```
### Example - update an existing bean
```java
Customer customer = new QCustomer()
.id.equalTo(customerId)
.findOne();
customer.setStatus(Customer.Status.ACTIVE);
database.update(customer);
```
### When to prefer `insert()` over `save()`
Use `insert()` when the code is creating a brand new row and should fail if the
operation does not behave like an insert.
### When to prefer `update()` over `save()`
Use `update()` when the bean is definitely existing and the method should not
silently behave like an insert.
---
## Step 3 - Check cascade mappings before assuming related beans will persist or delete
Ebean follows cascade rules defined on mapping annotations such as
`@OneToMany`, `@OneToOne`, `@ManyToOne`, and `@ManyToMany`.
The default is **no cascade**.
### Example
```java
@Entity
public class Order {
@ManyToOne
private Customer customer; // no cascade by default
@OneToMany(cascade = CascadeType.ALL)
private List<OrderDetail> details; // save + delete cascade
}
```
```java
database.save(order);
```
With the mapping above:
- `details` are cascaded
- `customer` is **not** cascaded
### Agent rules for cascades
1. Inspect the mapping before writing save/delete logic
2. Do not assume `@ManyToOne` cascades
3. Avoid adding cascade to shared parent references unless ownership is truly
intended
4. If a relationship should not cascade, save/delete related beans explicitly
---
## Step 4 - Let Ebean use an implicit transaction for a single isolated write
If the method performs one isolated persistence operation, Ebean can manage the
transaction implicitly.
### Good fit for implicit transaction
```java
Customer customer = new QCustomer()
.id.equalTo(customerId)
.findOne();
customer.setStatus(Customer.Status.INACTIVE);
database.save(customer);
```
### Good fit
- one save
- one update
- one delete
- small helper method with a single write
### Poor fit
- multiple writes that must commit or roll back together
- query + save + save workflow
- any method where later failure must roll back earlier writes
### Important
Queries also use implicit transactions when needed. You generally do **not**
need to wrap ordinary read queries in an explicit transaction "just in case".
---
## Step 5 - Use `@Transactional` for multi-step service workflows
When multiple Ebean operations belong to one unit of work, use
`@Transactional`.
### Example - service method
```java
import io.ebean.annotation.Transactional;
@Transactional
public void shipOrder(long orderId) {
Order order = new QOrder()
.id.equalTo(orderId)
.findOne();
order.setStatus(Order.Status.SHIPPED);
database.save(order);
Shipment shipment = new Shipment(order, Instant.now());
database.insert(shipment);
}
```
All database work inside the method runs in one transaction and commits only if
the method completes successfully.
### Use `Transaction.current()` only when needed
If the method needs access to the current transaction itself:
```java
Transaction txn = Transaction.current();
```
Do this only for transaction-specific behavior such as comments, savepoints, or
other advanced control. Do not fetch the current transaction if the method does
not need it.
### Agent rules for `@Transactional`
1. Put it on application/service workflow methods, not everywhere by default
2. Keep the transaction focused on database work
3. Avoid remote HTTP calls, message publishing, or long-running CPU work inside
the transaction if those can be moved outside
### Named database note
If the method uses a non-default database, obtain that `Database` instance via
`DB.byName("...")` and consistently use that database for both queries and
writes.
---
## Step 6 - Use `beginTransaction()` when you need explicit control
Use an explicit transaction when you need manual `commit()`, batching, explicit
flush, savepoints, or other low-level transaction control.
### Example - explicit transaction with try-with-resources
```java
try (Transaction txn = database.beginTransaction()) {
Order order = new QOrder()
.id.equalTo(orderId)
.findOne();
order.cancel();
database.save(order);
AuditLog auditLog = new AuditLog("order-cancelled", orderId);
database.insert(auditLog);
txn.commit();
}
```
If `commit()` is not reached, closing the transaction rolls it back.
### Useful explicit controls
- `txn.commit()` - commit current work
- `txn.setRollbackOnly()` - force rollback-only behavior
- `txn.flush()` - push batched statements to the database now
### Agent rule
Prefer `@Transactional` unless explicit transaction control is actually needed.
Do not use `beginTransaction()` only because it feels "safer".
---
## Step 7 - Use `createTransaction()` only for non-thread-local transaction handling
`createTransaction()` creates a transaction that is **not** placed into the
thread-local scope. This is a specialized tool.
Use it when:
- the transaction will be passed explicitly
- you need more than one transaction in the same thread
- you are coordinating work across threads or lower-level APIs
### Example - explicit transaction passed to query and save
```java
Database database = DB.getDefault();
try (Transaction txn = database.createTransaction()) {
Customer customer = new QCustomer(txn)
.email.equalTo(email)
.findOne();
customer.setInactive(true);
database.save(customer, txn);
txn.commit();
}
```
### Agent rule
If you are not deliberately bypassing thread-local transaction scope, do **not**
use `createTransaction()`. Most service code should use `@Transactional` or
`beginTransaction()`.
---
## Step 8 - Use bulk update/delete or JDBC batch for many-row writes
Loops of `database.save(...)` are often the wrong tool for large write sets.
### Prefer bulk update for set-based changes
If the update can be expressed as "change all rows matching this predicate",
perform one bulk update instead of loading and saving each bean.
### Example - bulk update with query beans
```java
var cust = QCustomer.alias();
int rows = new QCustomer()
.status.equalTo(Customer.Status.NEW)
.asUpdate()
.set(cust.status, Customer.Status.ACTIVE)
.update();
```
### Example - bulk update with `database.update(...)`
```java
int rows = database.update(Customer.class)
.set("status", Customer.Status.ACTIVE)
.where()
.eq("status", Customer.Status.NEW)
.update();
```
### Prefer JDBC batch for many individual inserts/updates
If each row has different values and must still go through per-bean persistence,
use batching.
```java
Database database = DB.getDefault();
try (Transaction txn = database.beginTransaction()) {
txn.setBatchMode(true);
txn.setBatchSize(100);
txn.setGetGeneratedKeys(false);
for (Customer customer : customersToInsert) {
database.insert(customer, txn);
}
txn.commit();
}
```
### Alternative - annotation-driven batching
```java
@Transactional(batchSize = 50)
public void importCustomers(List<Customer> customers) {
for (Customer customer : customers) {
database.insert(customer);
}
}
```
### Batch caveats
- Executing a query inside a batched transaction can flush the batch
- Mixing bean persistence and `SqlUpdate` can also flush the batch
- Accessing generated/unloaded properties on batched beans can flush the batch
If the workflow depends on delayed flushing, review the batch-flush rules before
adding more queries inside the same transaction.
---
## Common anti-patterns
### Anti-pattern 1 - Saving many rows one by one without batch or bulk update
If you are changing hundreds or thousands of rows, first ask whether it should
be a bulk update or a batched transaction.
### Anti-pattern 2 - Assuming child beans cascade automatically
Cascade is not automatic. Inspect the mapping first.
### Anti-pattern 3 - Wrapping external calls inside the database transaction
Do not keep transactions open while waiting on HTTP calls, queues, or other
slow external systems unless the design genuinely requires it.
### Anti-pattern 4 - Using `createTransaction()` for ordinary service code
Most service code should not bypass thread-local transaction handling.
### Anti-pattern 5 - Using `save()` when you really need `insert()` or `update()`
If operation intent matters, choose the more specific API.
---
## Troubleshooting
| Symptom | Likely cause | Fix |
|---------|--------------|-----|
| Child beans were not saved or deleted | Missing cascade mapping | Inspect annotations and add explicit save/delete or the correct cascade |
| Earlier writes committed even though later work failed | The whole workflow was not inside one transaction | Wrap the unit of work in `@Transactional` or an explicit transaction |
| `OptimisticLockException` on update/delete | Concurrent modification or stale version | Re-fetch, merge, or handle concurrency explicitly |
| Batch writes flush earlier than expected | Query, mixed SQL, or property access triggered flush | Review batch flush rules and transaction flow |
| Explicit transaction example does not affect the expected database | Mixed default DB and named DB usage | Use the same `Database` instance consistently for query and write |
---
## Summary workflow for AI agents
When asked to add persistence logic:
1. Choose `insert`, `save`, `update`, `delete`, or bulk update based on intent
2. Inspect cascade mappings before assuming related beans will persist/delete
3. Use implicit transactions for one isolated write
4. Use `@Transactional` for multi-step units of work
5. Use `beginTransaction()` only when explicit transaction control is needed
6. Use `createTransaction()` only for explicit, non-thread-local handling
7. Use bulk update or batching for large write sets
---
## Related documentation
- [Entity Bean Creation](entity-bean-creation.md)
- [Testing with TestEntityBuilder](testing-with-testentitybuilder.md)
- [Ebean persist docs](https://ebean.io/docs/persist)
- [Ebean transaction docs](https://ebean.io/docs/transactions)
@@ -0,0 +1,817 @@
# Guide: Testing with TestEntityBuilder
## Purpose
This guide explains how to use `TestEntityBuilder` to rapidly create test entity instances with auto-populated random values. It is written as practical instructions for developers and AI agents building tests for Ebean applications.
`TestEntityBuilder` eliminates boilerplate test setup by automatically generating realistic test data for all scalar fields, while respecting entity constraints and relationships. This is particularly valuable for:
- **Integration tests** that need representative data without caring about specific values
- **Persistence layer tests** that verify save/update/delete operations work correctly
- **Query and filter tests** where you need multiple entities with varied data
- **Rapid test setup** that reduces test code verbosity and improves readability
---
## Setup & Dependencies
### Add ebean-test to Your Project
The `TestEntityBuilder` class is provided by the `ebean-test` module.
**Maven:**
```xml
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-test</artifactId>
<version>${ebean.version}</version>
<scope>test</scope>
</dependency>
```
**Gradle:**
```gradle
testImplementation "io.ebean:ebean-test:${ebeanVersion}"
```
Use a version that matches your Ebean runtime (`ebean.version` /
`ebeanVersion`), or replace with an explicit fixed version if your build does
not centralize dependency versions.
> **Minimum version:** `TestEntityBuilder` was introduced in `ebean-test 17.5.0`. If your
> existing Ebean version is below this, upgrade before proceeding — mismatched Ebean
> runtime and test versions are not supported.
### Import the Class
```java
import io.ebean.test.TestEntityBuilder;
```
---
## Basic Usage
### Create a Builder Instance
`TestEntityBuilder` uses a builder pattern for configuration:
```java
TestEntityBuilder builder = TestEntityBuilder.builder(database).build();
```
The `Database` parameter specifies which Ebean database instance to use for entity type
lookups and persistence operations. Pass the injected `Database` bean (see
[Using with Dependency Injection](#using-with-dependency-injection) below) rather than
`DB.getDefault()` when working in a Spring or Avaje Inject context. For the same reason,
use the injected `database` bean for **all** persistence operations in your tests
(`database.save()`, `database.find()`, etc.) rather than mixing in static `DB.*` calls.
### Build an Entity (In-Memory)
The `build()` method creates an instance with populated fields **without persisting to the database:**
```java
Product product = builder.build(Product.class);
// Fields are populated:
// - id: unset (typically 0 for primitive long, null for boxed Long)
// - name: random UUID-based string
// - price: random BigDecimal
// - inStock: true
// - createdAt: current instant
// - etc.
// Not persisted yet (`@Id` is still unset until the entity is persisted).
```
### Build and Save (Persist to Database)
The `save()` method creates, persists, and returns an entity with the database-assigned `@Id`:
```java
Product product = builder.save(Product.class);
// Entity is now in the database:
assert database.find(Product.class, product.getId()) != null;
```
### Save Multiple Entities
The `saveAll()` method persists multiple pre-built entities in a single call:
```java
Product p1 = builder.build(Product.class);
Product p2 = builder.build(Product.class);
builder.saveAll(p1, p2);
// Both are now in the database with assigned IDs:
assert p1.getId() != null;
assert p2.getId() != null;
```
This is equivalent to `database.saveAll(p1, p2)` but avoids needing a separate
`Database` reference in tests that already hold a `TestEntityBuilder`.
### Access the Underlying Database
The `database()` method returns the `Database` instance used internally by the builder.
This is useful in tests where you want a single injected object (`TestEntityBuilder`) but
still need to perform `find()`, `delete()`, or other database operations:
```java
Product saved = builder.save(Product.class);
// Use builder.database() instead of injecting a separate Database bean:
Product found = builder.database().find(Product.class, saved.getId());
assert found != null;
```
---
## Using with Dependency Injection
Most applications using Ebean also use a DI framework. The recommended pattern is to
register `TestEntityBuilder` as a bean in the test DI context so it can be injected
directly into test classes — eliminating `@BeforeEach` setup boilerplate entirely.
### Avaje Inject — `@TestScope @Factory`
Add a `@Bean` method to your test-scoped `@Factory` class:
```java
import io.ebean.Database;
import io.ebean.test.ContainerDatabase;
import io.avaje.inject.Bean;
import io.avaje.inject.Factory;
import io.avaje.inject.test.TestScope;
import io.ebean.test.TestEntityBuilder;
@TestScope
@Factory
class TestConfiguration {
@Bean
PostgresContainer postgres() {
return PostgresContainer.builder("17") // Postgres image version
.dbName("my_app") // database to create inside the container
.build()
.start();
}
@Bean
Database database(PostgresContainer container) {
return container.ebean()
.builder()
.build();
}
@Bean
TestEntityBuilder testEntityBuilder(Database database) {
return TestEntityBuilder.builder(database).build();
}
}
```
Then inject it directly into test classes using `@InjectTest`:
```java
@InjectTest
class OrderControllerTest {
@Inject Database database;
@Inject TestEntityBuilder builder;
@Test
void findByStatus() {
var order = builder.build(Order.class).setStatus(OrderStatus.PENDING);
database.save(order);
// ... test assertions
}
}
```
Both patterns produce a single shared `TestEntityBuilder` instance, wired
from the managed `Database` bean — no `@BeforeEach` required.
### Spring Boot — `@TestConfiguration`
Add a `@TestConfiguration` class that provides `TestEntityBuilder` as a bean:
```java
@TestConfiguration
class TestConfig {
@Bean
PostgresContainer postgres() {
return PostgresContainer.builder("17") // Postgres image version
.dbName("my_app") // database to create inside the container
.build()
.start();
}
// use @Primary if your main application context also wires a Database bean
// or conditionally wire the main Database bean to exclude it from tests
@Primary
@Bean
Database database(PostgresContainer container) {
return container.ebean()
.builder()
.build();
}
@Bean
TestEntityBuilder testEntityBuilder(Database database) {
return TestEntityBuilder.builder(database).build();
}
}
```
Then inject it directly into test classes:
```java
@SpringBootTest
class OrderControllerTest {
@Autowired Database database;
@Autowired TestEntityBuilder builder;
@Test
void findByStatus() {
var order = builder.build(Order.class).setStatus(OrderStatus.PENDING);
database.save(order);
// ... test assertions
}
}
```
---
## Type-Specific Value Generation
`TestEntityBuilder` generates appropriate random values for each Java/SQL type. Customize this behavior by subclassing `RandomValueGenerator` (see "Custom Value Generators" below).
| Type | Generated Value | Notes |
|------|-----------------|-------|
| `String` | UUID-derived (8 chars by default) | Truncated to column length if `@Column(length=...)` is set |
| Email fields | `uuid@domain.com` format | Detected when property name contains "email" (case-insensitive) |
| `Integer` / `int` | Random in `[1, 1_000)` | |
| `Long` / `long` | Random in `[1, 100_000)` | |
| `Short` / `short` | Random in `[1, 100)` | See note on flag fields below |
| `Double` / `double` | Random in `[1, 100)` | |
| `Float` / `float` | Random in `[1, 100)` | |
| `BigDecimal` | Respects precision and scale | Precision and scale from `@Column(precision=..., scale=...)` |
| `Boolean` / `boolean` | `true` | Override in custom generator if needed |
| `UUID` | Random UUID | Via `UUID.randomUUID()` |
| `LocalDate` | Today's date | Via `LocalDate.now()` |
| `LocalDateTime` | Current datetime | Via `LocalDateTime.now()` |
| `Instant` | Current instant | Via `Instant.now()` |
| `OffsetDateTime` | Current time with zone | Via `OffsetDateTime.now()` |
| `ZonedDateTime` | Current time with zone | Via `ZonedDateTime.now()` |
| `Enum` | First constant | Override in custom generator if needed |
| Other types | `null` | Set these fields manually in tests |
### String Length Constraints
`TestEntityBuilder` respects column length constraints defined in the entity:
```java
@Entity
public class User {
@Column(length = 50)
private String username;
}
User user = builder.build(User.class);
assert user.getUsername().length() <= 50; // ✅ Constraint respected
```
### BigDecimal Precision and Scale
For `BigDecimal` fields, the builder respects the database column precision and scale:
```java
@Entity
public class LineItem {
@Column(precision = 10, scale = 2) // max 99_999_999.99
private BigDecimal amount;
}
LineItem item = builder.build(LineItem.class);
assert item.getAmount().scale() == 2;
```
### Short Fields Used as Boolean Flags
Some legacy schemas use `short` to represent boolean-like flags (e.g. `active = 1`
means active, `0` means inactive). `TestEntityBuilder` generates a random short in
`[1, 100)`, which will be non-zero but not necessarily `1`. If your application
code checks `entity.getActive() == 1` specifically, override the field after building:
```java
Organisation org = builder.build(Organisation.class)
.setActive((short) 1); // explicit override — random short won't do
```
---
## Entity Relationships
### Cascade-Persist Relationships: Recursively Built
Relationships marked with `cascade = PERSIST` are recursively populated:
```java
@Entity
public class Order {
@ManyToOne(cascade = CascadeType.PERSIST)
private Customer customer;
}
Order order = builder.build(Order.class);
// Both order and customer are built:
assert order != null;
assert order.getCustomer() != null;
// Before persist, @Id values are typically unset
// (0 for primitive IDs, null for boxed IDs).
// When saved, cascade handles both:
Order saved = builder.save(Order.class);
assert saved.getId() != null;
assert saved.getCustomer().getId() != null; // parent also saved
```
### Non-Cascade Relationships: Left Null
Relationships without cascade persist are not auto-created — even if marked `optional = false`.
Create and save the related entity first (the builder works well here), then assign it manually
before saving the parent:
```java
@Entity
public class BlogPost {
@ManyToOne
private Author author; // No cascade = left null by builder
}
BlogPost post = builder.build(BlogPost.class);
assert post.getAuthor() == null;
// Use the builder to create the related entity, then set it manually:
Author author = builder.save(Author.class);
post.setAuthor(author);
database.save(post);
```
### Collection Relationships: Left Empty
Collection relationships (`@OneToMany`, `@ManyToMany`) are left empty. On Ebean-enhanced
entities these fields are initialised to empty Ebean-managed lists (not `null`), so calling
`.add()` or `.addAll()` directly is safe:
```java
@Entity
public class Author {
@OneToMany(mappedBy = "author")
private List<BlogPost> posts; // Left empty
}
Author author = builder.build(Author.class);
assert author.getPosts().isEmpty();
// Populate if needed for testing:
author.getPosts().addAll(Arrays.asList(post1, post2, post3));
```
### Cycle Detection: Prevents Infinite Recursion
If two entities reference each other with cascade persist, the builder detects the cycle and breaks it by leaving one reference null:
```java
@Entity
public class Person {
@ManyToOne(cascade = CascadeType.PERSIST)
private Organization org;
}
@Entity
public class Organization {
@ManyToOne(cascade = CascadeType.PERSIST)
private Person founder;
}
Person person = builder.build(Person.class);
// One reference will be null to break the cycle:
// either person.org or person.org.founder is null
```
---
## Custom Value Generators
### Why Customize?
The default `RandomValueGenerator` uses generic random values. For domain-specific testing, you may want:
- Email addresses with your company domain
- Realistic phone numbers
- Product SKUs following a pattern
- Addresses in specific regions
- Monetary amounts within realistic ranges
### Creating a Custom Generator
Subclass `RandomValueGenerator` and override individual `random*()` methods:
```java
class CompanyTestDataGenerator extends RandomValueGenerator {
@Override
protected String randomString(String propName, int maxLength) {
if (propName != null && propName.toLowerCase().contains("email")) {
// Use company domain instead of generic @domain.com
String localPart = UUID.randomUUID().toString().substring(0, 8);
String email = localPart + "@mycompany.com";
if (maxLength > 0 && email.length() > maxLength) {
return email.substring(0, maxLength);
}
return email;
}
return super.randomString(propName, maxLength);
}
// Override other methods as needed:
@Override
protected Object randomEnum(Class<?> type) {
if (type == OrderStatus.class) {
// Bias towards common statuses for realistic test data
return ThreadLocalRandom.current().nextDouble() < 0.8
? OrderStatus.PENDING
: OrderStatus.COMPLETED;
}
return super.randomEnum(type);
}
}
```
### Using a Custom Generator
Pass the custom generator when building:
```java
TestEntityBuilder builder = TestEntityBuilder.builder(database)
.valueGenerator(new CompanyTestDataGenerator())
.build();
User user = builder.build(User.class);
assert user.getEmail().endsWith("@mycompany.com");
```
In a DI context, register this as the bean:
```java
// Spring Boot
@Bean
TestEntityBuilder testEntityBuilder(Database database) {
return TestEntityBuilder.builder(database)
.valueGenerator(new CompanyTestDataGenerator())
.build();
}
```
### Example: Money Type
```java
public class MoneyValueGenerator extends RandomValueGenerator {
@Override
protected BigDecimal randomBigDecimal(int precision, int scale) {
// Generate prices in a realistic range: $5.00 to $999.99
BigDecimal price = BigDecimal.valueOf(
ThreadLocalRandom.current().nextDouble(5.0, 1000.0)
);
return price.setScale(2, RoundingMode.HALF_UP);
}
}
```
---
## Best Practices
### 1. Use for Integration Tests, Not Unit Tests
**Good:** Integration test with database
```java
@Test
void whenSaving_thenCanRetrieve() {
Product product = builder.save(Product.class);
Product found = database.find(Product.class, product.getId());
assertThat(found).isNotNull();
}
```
**Poor:** Validation test requiring specific values
```java
@Test
void whenNameIsBlank_thenThrowException() {
Product product = builder.build(Product.class); // name is random!
product.setName(""); // have to override anyway
// ... test proceeds
}
```
### 2. Override Values for Specific Test Scenarios
When test requirements demand specific field values, manually override after building:
```java
@Test
void whenStockIsLow_thenShowWarning() {
Product product = builder.build(Product.class);
product.setQuantity(2); // Specific value for this test
boolean shouldWarn = product.shouldShowLowStockWarning();
assertThat(shouldWarn).isTrue();
}
```
### 3. Create Fixture Factories for Common Patterns
For shared domain-specific setup, encapsulate build patterns in an instance helper class
rather than a static factory. In a DI context, this class can be registered as a bean
alongside `TestEntityBuilder`:
```java
// Spring Boot
@TestConfiguration
class TestConfig {
@Bean
TestEntityBuilder testEntityBuilder(Database database) {
return TestEntityBuilder.builder(database).build();
}
@Bean
OrderTestFactory orderTestFactory(TestEntityBuilder builder, Database database) {
return new OrderTestFactory(builder, database);
}
}
public class OrderTestFactory {
private final TestEntityBuilder builder;
private final Database database;
public OrderTestFactory(TestEntityBuilder builder, Database database) {
this.builder = builder;
this.database = database;
}
public Order savePendingOrder() {
Order order = builder.build(Order.class);
order.setStatus(OrderStatus.PENDING);
database.save(order);
return order;
}
public Order saveShippedOrder() {
Order order = builder.build(Order.class);
order.setStatus(OrderStatus.SHIPPED);
order.setShippedAt(Instant.now());
database.save(order);
return order;
}
}
// Usage in tests:
@SpringBootTest
class OrderControllerTest {
@Autowired OrderTestFactory orderFactory;
@Test
void whenOrderPending_thenCanUpdate() {
Order order = orderFactory.savePendingOrder();
// ... test logic
}
}
```
### 4. Build Multiple Distinct Instances
Each call to `build()` or `save()` produces a new instance with fresh random values:
```java
@Test
void whenFetchingMultipleOrders_thenAllUnique() {
Order order1 = builder.save(Order.class);
Order order2 = builder.save(Order.class);
Order order3 = builder.save(Order.class);
assertThat(order1.getId()).isNotEqualTo(order2.getId());
assertThat(order2.getId()).isNotEqualTo(order3.getId());
assertThat(order1.getOrderNumber()).isNotEqualTo(order2.getOrderNumber());
}
```
---
## Complete Examples
### Example 1: Integration Test with Spring Boot
Register `TestEntityBuilder` as a `@TestConfiguration` bean, then inject it alongside
the repository under test:
```java
@TestConfiguration
class TestConfig {
@Bean
TestEntityBuilder testEntityBuilder(Database database) {
return TestEntityBuilder.builder(database).build();
}
}
@SpringBootTest
class OrderRepositoryTest {
@Autowired OrderRepository orderRepository;
@Autowired TestEntityBuilder builder;
@Test
void whenFindingOrdersByStatus_thenReturnsMatching() {
Order pending1 = builder.build(Order.class);
pending1.setStatus(OrderStatus.PENDING);
Order pending2 = builder.build(Order.class);
pending2.setStatus(OrderStatus.PENDING);
Order shipped = builder.build(Order.class);
shipped.setStatus(OrderStatus.SHIPPED);
builder.saveAll(pending1, pending2, shipped);
List<Order> pending = orderRepository.findByStatus(OrderStatus.PENDING);
assertThat(pending).hasSize(2);
}
}
```
### Example 2: Integration Test with Avaje Inject
```java
@TestScope
@Factory
class TestConfiguration {
@Bean
TestEntityBuilder testEntityBuilder(Database database) {
return TestEntityBuilder.builder(database).build();
}
}
@InjectTest
class OrderControllerTest {
@Inject TestEntityBuilder builder;
@Test
void whenFindingOrdersByStatus_thenReturnsMatching() {
Order pending1 = builder.build(Order.class);
pending1.setStatus(OrderStatus.PENDING);
Order pending2 = builder.build(Order.class);
pending2.setStatus(OrderStatus.PENDING);
Order shipped = builder.build(Order.class);
shipped.setStatus(OrderStatus.SHIPPED);
builder.saveAll(pending1, pending2, shipped);
// ... test assertions
}
}
```
### Example 3: Recursive Relationship Building
```java
@Test
void whenBuildingOrderWithCustomer_thenBothPopulated() {
Order order = builder.build(Order.class);
// Customer is recursively built because of @ManyToOne(cascade=PERSIST)
assertThat(order.getCustomer()).isNotNull();
// Before persist, @Id values are typically unset
// (0 for primitive IDs, null for boxed IDs).
assertThat(order.getCustomer().getName()).isNotNull();
// Saving cascades to customer:
Order saved = builder.save(Order.class);
assertThat(saved.getId()).isNotNull();
assertThat(saved.getCustomer().getId()).isNotNull();
}
```
### Example 4: Custom Generator for Domain Values
```java
// Custom generator for your domain
class ECommerceTestDataGenerator extends RandomValueGenerator {
@Override
protected BigDecimal randomBigDecimal(int precision, int scale) {
// Product prices typically range $10-$500
return BigDecimal.valueOf(
ThreadLocalRandom.current().nextDouble(10.0, 500.0)
).setScale(2, RoundingMode.HALF_UP);
}
}
@Test
void usingCustomGenerator() {
TestEntityBuilder builder = TestEntityBuilder.builder(database)
.valueGenerator(new ECommerceTestDataGenerator())
.build();
Product product = builder.build(Product.class);
assertThat(product.getPrice())
.isBetween(BigDecimal.TEN, BigDecimal.valueOf(500.0));
}
```
---
## Troubleshooting
### "No BeanDescriptor found for [Class] — is it an @Entity?"
**Cause:** The class you're trying to build is not registered as an Ebean entity.
**Solution:** Ensure the class is annotated with `@Entity` and registered with the Database:
```java
@Entity
@Table(name = "products")
public class Product {
// ...
}
```
### Fields are unset even though I expected them to be populated
**Cause:** `TestEntityBuilder` does **not** populate:
- `@Id` fields (identity/primary key; left unset until persist)
- `@Version` fields (optimistic locking; left unset until persist)
- `@Transient` fields
- `@OneToMany` collections
- Non-cascade `@ManyToOne` relationships
**Solution:** Set only the fields your test scenario cares about, then persist.
`@Id` and `@Version` are usually database-managed and should typically be left
unset before save:
```java
Product product = builder.build(Product.class);
product.setName("specific-name"); // test-specific override
database.save(product); // database assigns @Id/@Version
```
### Building recursive relationships causes StackOverflowError
**Cause:** Two or more entities mutually reference each other without cycle detection.
**Solution:** This should be handled automatically by cycle detection. If not, manually set one reference to null:
```java
Person person = builder.build(Person.class);
person.getOrganization().setFounder(null); // Break cycle
```
### Values generated are "too random" for my test
**Cause:** Default `RandomValueGenerator` uses true random values, which aren't suitable when your test needs predictable data.
**Solution:** Create a custom generator that produces deterministic values:
```java
class DeterministicTestDataGenerator extends RandomValueGenerator {
private int counter = 0;
@Override
protected String randomString(String propName, int maxLength) {
return "test_" + (counter++);
}
}
```
---
## Summary
`TestEntityBuilder` accelerates test development by:
1. **Reducing boilerplate** — No need to manually set every field
2. **Improving readability** — Tests focus on what matters, not setup
3. **Enabling variety** — Each build produces distinct random values
4. **Respecting constraints** — Column lengths and decimal scales are enforced
5. **Supporting customization** — Extend `RandomValueGenerator` for domain needs
+488
View File
@@ -0,0 +1,488 @@
# Guide: Write Ebean Queries with Query Beans
## Purpose
This guide gives step-by-step instructions for AI agents and developers to write
application queries using Ebean query beans.
Use this guide when the project already has Ebean configured and you need to:
- add a repository/service query
- replace string-based ORM queries with type-safe query beans
- tune what data is fetched to avoid over-fetching or N+1 issues
- return DTO projections for list screens or API responses
The default recommendation is:
1. Prefer query beans first
2. Prefer entity queries for domain logic
3. For read-only entity graphs, prefer `setUnmodifiable(true)`
4. Prefer DTO projection for summary/read-model use cases
5. Only drop to raw SQL when the ORM query cannot express the requirement cleanly
---
## Prerequisites
- The project already uses Ebean ORM
- Query bean generation is configured (for Maven this usually means
`querybean-generator` is registered as an annotation processor)
- Entity beans already exist
- A compile/build has run successfully since the last entity model change
If query beans are not yet configured, first follow:
[`add-ebean-postgres-maven-pom.md`](add-ebean-postgres-maven-pom.md)
---
## Step 1 - Verify the generated `Q*` query bean exists
For each entity bean, Ebean generates a query bean with the same name prefixed
with `Q`.
Examples:
- `Customer` -> `QCustomer`
- `Order` -> `QOrder`
- `Contact` -> `QContact`
Import the generated type from the query bean package:
```java
import org.example.domain.query.QCustomer;
```
If the `Q*` type does not exist or the IDE cannot resolve it:
1. Confirm the entity compiled successfully
2. Run a normal project compile/build
3. If the entity was renamed or moved, run a full rebuild rather than relying on
incremental compilation
### Important caveat - entity rename
After refactoring an entity name, old generated query beans can remain on disk
until the next full build. If both old and new `Q*` types appear to exist, do a
clean rebuild before editing application queries.
---
## Step 2 - Choose the terminal query method before writing predicates
Decide what the caller actually needs. This determines the terminal method and
often the right query shape.
| Need | Preferred method | Notes |
|------|------------------|-------|
| Check if at least one row exists | `exists()` | Cheapest choice for boolean existence checks |
| Load exactly one row by ID or unique key | `findOne()` | Only use when the predicate is truly unique |
| Load a list of entity beans | `findList()` | Default for list screens and domain logic |
| Count matching rows | `findCount()` | Prefer over loading entities just to count |
| Load a page plus optional total row count | `findPagedList()` | Use when the caller needs pagination metadata |
| Return DTO/read-model rows | `asDto(...).findList()` | Prefer this over partially loaded entities for API/view models |
### Example - existence check
```java
boolean alreadyUsed = new QCustomer()
.email.equalTo(email)
.exists();
```
### Example - unique lookup
```java
Customer customer = new QCustomer()
.email.equalTo(email)
.findOne();
```
Do **not** use `findOne()` for predicates that can match multiple rows.
---
## Step 3 - Build predicates by traversing properties and associations
With query beans, write predicates directly against properties. When you
traverse an association, Ebean adds the necessary joins automatically.
### Example - root property predicates
```java
List<Customer> customers = new QCustomer()
.status.equalTo(Customer.Status.ACTIVE)
.name.istartsWith("rob")
.findList();
```
### Example - association traversal
```java
List<Customer> customers = new QCustomer()
.billingAddress.city.equalTo("Auckland")
.findList();
```
### Example - collection predicate
```java
List<Customer> customers = new QCustomer()
.contacts.isEmpty()
.findList();
```
### Agent rule
When adding a new query:
1. Start from the root entity that the caller wants back
2. Add predicates with query bean properties
3. Traverse relationships instead of writing manual join SQL
4. Keep property references type-safe; avoid string property names unless the API
specifically requires them
---
## Step 4 - Add ordering, limits, and pagination deliberately
Do not leave list queries unordered unless the call site truly does not care.
For UI lists, APIs, and background jobs, explicit ordering is usually better.
### Example - ordered list with limit
```java
List<Customer> customers = new QCustomer()
.status.equalTo(Customer.Status.ACTIVE)
.orderBy().name.asc()
.setMaxRows(50)
.findList();
```
### Example - offset/limit pagination
```java
List<Customer> customers = new QCustomer()
.status.equalTo(Customer.Status.ACTIVE)
.orderBy().id.asc()
.setFirstRow(offset)
.setMaxRows(pageSize)
.findList();
```
### Example - paged list with total count
```java
PagedList<Customer> page = new QCustomer()
.status.equalTo(Customer.Status.ACTIVE)
.orderBy().id.asc()
.setFirstRow(offset)
.setMaxRows(pageSize)
.findPagedList();
page.loadRowCount();
List<Customer> customers = page.getList();
int totalRowCount = page.getTotalRowCount();
```
### Agent rule
- Use `findList()` when the caller only needs rows
- Use `findPagedList()` when the caller also needs page metadata or total counts
- Pair pagination with a stable `orderBy()` so page boundaries stay predictable
---
## Step 5 - Control fetched data with `select()` and `fetch()`
By default, entity queries can load more of the object graph than the caller
actually needs. Use `select()` and `fetch()` to control the root and association
properties that are loaded.
### Root properties with `select()`
Use `select()` to define which properties should be fetched on the root entity.
### Associated bean properties with `fetch()`
Use `fetch()` to define what should be fetched on associated paths.
### Example - partial entity query
```java
private static final QCustomer CUST = QCustomer.alias();
private static final QContact CONT = QContact.alias();
List<Customer> customers = new QCustomer()
.select(CUST.name, CUST.status, CUST.whenCreated)
.contacts.fetch(CONT.email)
.name.istartsWith("rob")
.findList();
```
In this example:
- `select(...)` tunes the root `Customer` properties
- `contacts.fetch(...)` tunes the associated `Contact` properties
- the query still returns `Customer` entity beans
### Agent rules for partial entity queries
1. Only use `select()`/`fetch()` when you know what the caller will read next
2. Do not treat partially loaded entities like fully populated API DTOs
3. If the caller only needs summary fields, prefer a DTO projection instead
---
## Step 6 - Use `setUnmodifiable(true)` for read-only entity graphs
`setUnmodifiable(true)` turns the returned object graph into an unmodifiable,
read-only graph.
This means:
- setters cannot mutate returned beans
- associated collections are unmodifiable
- lazy loading is disabled
- accessing an unloaded property throws `LazyInitialisationException`
- the query uses `PersistenceContextScope.QUERY`
### Example - read-only entity graph
```java
private static final QCustomer CUST = QCustomer.alias();
private static final QContact CONT = QContact.alias();
List<Customer> customers = new QCustomer()
.select(CUST.name, CUST.status, CUST.whenCreated)
.contacts.fetch(CONT.email)
.status.equalTo(Customer.Status.ACTIVE)
.setUnmodifiable(true)
.findList();
```
### When to prefer `setUnmodifiable(true)`
Use it when the result is meant to be read-only, such as:
- service/query methods returning entity graphs for display or serialization
- query results you want the application to treat as immutable
- cached query results or other shared read models backed by entity graphs
- partial entity graphs where you want accidental lazy loading to fail fast
### When **not** to use it
Do **not** use `setUnmodifiable(true)` when the caller will:
- modify the beans and save them later
- rely on lazy loading of associations or unloaded scalar properties
- treat the result as a working persistence model rather than a read-only view
### Agent rule
If you are returning entity beans for read-only use, `setUnmodifiable(true)`
should be the default recommendation. If the caller needs a mutable model or a
serialized summary shape, choose mutable entities or DTO projection instead.
If you need cached assoc-one references for unmodifiable graphs, see
[Immutable bean cache for read-only references](immutable-bean-cache.md).
---
## Step 7 - Use `fetchQuery()` for to-many paths and `FetchGroup` for reusable query shapes
Ebean applies important SQL rules when translating ORM queries:
1. It does not generate SQL cartesian products
2. It honors `maxRows` in SQL
This means to-many paths often need special handling.
### Use `fetchQuery()` when:
- the query includes a `OneToMany` or `ManyToMany` path
- the query includes `setMaxRows(...)`
- the query loads multiple to-many paths
- you want the query shape to make the secondary-query behavior explicit
### Example - explicit secondary queries for to-many paths
```java
private static final QCustomer CUST = QCustomer.alias();
List<Order> orders = new QOrder()
.customer.fetch(CUST.name)
.lines.fetchQuery()
.shipments.fetchQuery()
.status.equalTo(Order.Status.NEW)
.setMaxRows(100)
.findList();
```
### Use `FetchGroup` when:
- the same fetch shape is reused in multiple places
- you want to separate predicate logic from fetch-shape tuning
- you want an immutable, static query-shape definition
### Example - reusable fetch group
```java
private static final QCustomer CUST = QCustomer.alias();
private static final FetchGroup<Customer> CUSTOMER_SUMMARY =
QCustomer.forFetchGroup()
.select(CUST.name, CUST.status, CUST.whenCreated)
.billingAddress.fetch()
.buildFetchGroup();
List<Customer> customers = new QCustomer()
.select(CUSTOMER_SUMMARY)
.status.equalTo(Customer.Status.ACTIVE)
.findList();
```
### Agent rule
If the caller needs multiple to-many paths or a paged query, be suspicious of a
plain `fetch(...)` on those paths. `fetchQuery()` is often the safer default.
---
## Step 8 - Use DTO projection when the caller does not need entity beans
For list screens, API summaries, exports, or read-model views, the caller often
does **not** need managed entity beans. In those cases, project directly to a
DTO using `asDto(...)`.
### Example - DTO projection with query beans
```java
import static org.example.domain.query.QCustomer.Alias.id;
import static org.example.domain.query.QCustomer.Alias.name;
public record CustomerSummary(long id, String name) {}
List<CustomerSummary> summaries = new QCustomer()
.select(id, name)
.status.equalTo(Customer.Status.ACTIVE)
.orderBy().name.asc()
.asDto(CustomerSummary.class)
.findList();
```
### Prefer DTO projection when:
- the caller will serialize the result directly
- only a subset of fields is needed
- the result is not going to be updated and saved back as an entity
- the query contains formulas or aggregation intended for a read model
---
## Step 9 - Only fall back to raw SQL when the ORM query is not a good fit
Prefer the following order:
1. Query bean query
2. Query bean query + `asDto(...)`
3. `database.findDto(...)` or DTO query
4. Native SQL / `SqlQuery` / `RawSql`
### Typical reasons to use raw SQL
- vendor-specific SQL that query beans do not express well
- advanced aggregation or database functions
- hand-tuned reporting queries
- stored procedures or raw JDBC workflows
Do **not** jump to raw SQL just because the query joins multiple tables. Query
beans already handle ordinary relationship traversal well.
---
## Common anti-patterns
### Anti-pattern 1 - Using raw SQL first
**Avoid:**
```java
List<Customer> customers = database.findNative(Customer.class,
"select c.* from customer c join address a on a.id = c.billing_address_id where a.city = ?")
.setParameter(1, city)
.findList();
```
**Prefer:**
```java
List<Customer> customers = new QCustomer()
.billingAddress.city.equalTo(city)
.findList();
```
### Anti-pattern 2 - Using `findOne()` on a non-unique predicate
**Avoid:**
```java
Customer customer = new QCustomer()
.status.equalTo(Customer.Status.ACTIVE)
.findOne();
```
**Why:** Many rows can match; this is not a unique lookup.
### Anti-pattern 3 - Returning partially loaded entities as API models
If the caller only needs summary fields, return a DTO instead of partially
loaded entities that might later trigger more loading or confuse serializers.
### Anti-pattern 4 - Returning mutable entity graphs for read-only use
If the caller is only meant to read the result, prefer `setUnmodifiable(true)`
so accidental setter calls, collection mutation, and lazy loading fail fast.
### Anti-pattern 5 - Fetching every relationship "just in case"
Do not eagerly fetch large object graphs unless the immediate caller will use
them. Query tuning is part of the job.
---
## Troubleshooting
| Symptom | Likely cause | Fix |
|---------|--------------|-----|
| `Cannot resolve symbol QCustomer` | Query bean generation not configured or build not run | Check the annotation processor and run a build |
| Old `Q*` class still appears after entity rename | Stale generated source/class output | Run a clean rebuild |
| `findOne()` fails because multiple rows match | Predicate is not unique | Use `findList()` or tighten the predicate |
| Returned entities only have some fields loaded | `select()` or `FetchGroup` limited the query shape | Add the required fields or switch to DTO projection |
| Setter calls or collection mutation fail on query results | `setUnmodifiable(true)` returned a read-only graph | Remove `setUnmodifiable(true)` or treat the result as read-only |
| Accessing an unloaded property throws `LazyInitialisationException` | `setUnmodifiable(true)` disables lazy loading | Fetch the property up front or use DTO projection |
| Ebean executes secondary queries for a to-many path | ORM rules avoided cartesian product or honored `maxRows` | This is expected; use `fetchQuery()` explicitly when appropriate |
---
## Summary workflow for AI agents
When asked to add or modify an Ebean query:
1. Verify the relevant `Q*` type exists
2. Choose the terminal method first (`exists`, `findOne`, `findList`, `findPagedList`, `asDto`)
3. Add predicates with query bean properties and association traversal
4. Add explicit ordering and pagination if relevant
5. If the result is read-only entity data, consider `setUnmodifiable(true)`
6. Tune the fetch shape with `select()` / `fetch()` / `fetchQuery()` / `FetchGroup`
7. Prefer DTO projection for read models and serialized responses
8. Only use raw SQL if the ORM query is genuinely the wrong tool
---
## Related documentation
- [Add Ebean Postgres Maven POM](add-ebean-postgres-maven-pom.md)
- [Entity Bean Creation](entity-bean-creation.md)
- [Immutable bean cache for read-only references](immutable-bean-cache.md)
- [Ebean query docs](https://ebean.io/docs/query/)
+333
View File
@@ -0,0 +1,333 @@
# Immutable Bean Cache — notes on multi-level / remote caching
These notes capture design thoughts for a possible future multi-level immutable bean cache,
where immutable beans may be cached remotely (for example Redis or a Postgres cache table)
in addition to an in-JVM cache.
## Current important constraint
`AssocOneHelp.read()` now uses `ImmutableBeanCache.getIfPresent(id)` as a direct-hit fast path.
That means:
- `getIfPresent(id)` is on the **row read hot path**
- it must remain **cheap and local**
- it should **not** perform network I/O
- it should **not** deserialize remote payloads
- it should **not** trigger loading or record misses
## Strong recommendation
For any multi-level cache design:
- **L1 cache** = in-JVM cache of already materialized immutable beans
- **L2 cache** = remote/shared cache of serialized immutable snapshots
- **Loader** = Ebean query using the configured fetch group
With that split:
- `getIfPresent(id)` => **L1 only**
- `getAll(ids)` => batch through **L1 -> L2 -> loader**
This preserves the `AssocOneHelp` fast path.
---
## Snapshot mindset
Remote cache entries should be treated as **immutable snapshots**, not just arbitrary beans.
A cached value is specific to:
- bean type
- bean id
- tenant (if multi-tenant)
- fetch-group / cache identity
- serializer/schema version
This matters because a `Customer` cached with:
- `select("name,version")`
is not equivalent to a `Customer` cached with:
- `select("name,version").fetch("billingAddress", "line1,city")`
## Key design recommendation
Remote keys should include at least:
- bean type
- bean id
- tenant id (if applicable)
- cache/fetch-group identity
- optionally serializer/schema version
Example shape:
- `immutable:Customer:basic:42`
- `immutable:Customer:withAddresses:42`
---
## Recommended multi-level flow
### L1
Store actual read-only `EntityBean` instances.
Responsibilities:
- support `getIfPresent(id)`
- avoid repeated deserialize cost
- avoid network calls on row read path
### L2
Store serialized immutable snapshots.
Responsibilities:
- batch lookup only
- support cross-JVM sharing
- feed L1 with materialized immutable beans
### Loader
Use the existing query/fetch-group-based loader for misses.
### Suggested `getAll(ids)` flow
1. Check L1
2. Batch remaining ids to L2
3. Deserialize L2 hits into read-only beans
4. Put those beans into L1
5. Batch remaining misses to DB loader
6. Freeze / ensure read-only beans
7. Write through to L2
8. Put into L1
9. Negative-cache true misses if desired
---
## Invalidation is more important than serialization
Things to think about:
- update/delete invalidation across JVMs
- local L1 invalidation when L2 entry is removed
- ordering relative to DB commit
- multiple cache instances for the same bean type but different fetch groups
- tenant-scoped invalidation
Recommended direction:
- keep current immutable-cache invalidation semantics
- add a remote invalidation/event mechanism for L2-backed caches
- each JVM should evict affected L1 entries when notified
Examples:
- Redis: pub/sub or streams
- Postgres cache table: NOTIFY/listen, polling, or invalidation table/outbox pattern
---
## Serialization format considerations
## JSON
### Pros
- human readable / debuggable
- easier rolling upgrades
- field-name based, so generally more tolerant of schema evolution
- good fit for Redis strings or Postgres JSONB
- easier operational debugging
### Cons
- larger payloads
- more CPU to serialize/deserialize
- nested graphs / enums / dates / inheritance need disciplined handling
## Kryo / generic binary serialization
### Pros
- smaller payloads
- often faster than JSON
- can preserve object graphs efficiently
### Cons
- more fragile across versions and rolling deploys
- class registration / compatibility pain
- harder to inspect/debug
- tighter coupling to JVM/class layout
- riskier for long-lived shared cache entries
## Recommendation
For a first remote/shared implementation:
- prefer **JSON** or another self-describing structured format
- if a binary format is later needed, prefer a stable schema-based format over generic object-graph serialization
- **do not start with Kryo** unless short-lived entries and tight deployment coordination are acceptable
---
## What to serialize
Avoid thinking in terms of serializing arbitrary live entity bean graphs directly.
A cleaner model is:
- serialize a **snapshot representation**
- deserialize into a fresh entity bean
- mark loaded properties appropriately
- freeze / ensure read-only state
- store the resulting materialized bean in L1
This gives more control over:
- loaded-property semantics
- read-only state
- subtype handling
- schema/version evolution
## Practical recommendation
Remote cache entries should represent exactly the configured fetch-group snapshot.
That means:
- cache what the fetch group loaded
- include nested associations loaded by that fetch group
- treat it as a self-contained immutable snapshot
This is simpler than trying to normalize the graph into many remote cache fragments and re-link it later.
---
## Redis vs Postgres cache table
## Redis
### Good for
- low latency
- batch lookup via MGET / pipelining
- TTL/eviction support
- natural shared-cache use case
### Tradeoffs
- extra infrastructure
- memory cost
- invalidation/event coordination still required
## Postgres cache table (including unlogged-style approach)
### Good for
- simpler ops if Postgres is already present
- easy batch lookup with `IN (...)`
- fewer moving parts than introducing Redis
### Tradeoffs
- slower than Redis for hot shared-cache usage
- adds pressure to Postgres
- TTL/cleanup becomes application responsibility
- still network/database I/O, so should remain off the `getIfPresent()` hot path
## Recommendation
- if the goal is a serious shared L2 cache, Redis is the more natural fit
- if the goal is pragmatic shared caching with minimal extra infrastructure, Postgres can work but should still be treated as L2-only
---
## Versioning / evolution
Whatever serializer is used, include versioning information.
Useful dimensions:
- serializer/schema version
- cache implementation version
- fetch-group/cache identity version
This helps when:
- fields are added/removed
- graph shape changes
- fetch-group definitions evolve
---
## Compression
If remote snapshots become large:
- compress only above a size threshold
- avoid compressing tiny payloads
This is especially relevant for JSON in Redis or Postgres L2.
---
## Observability
A multi-level cache should expose at least:
- L1 hit rate
- L2 hit rate
- DB loader rate
- deserialize failures
- invalidation counts
- average payload size
- cold-start amplification
Without this, it will be hard to judge whether the remote cache is helping.
---
## Overall recommended architecture
### Recommended model
- **L1**: actual read-only `EntityBean` instances
- **L2**: serialized immutable snapshots
- **Loader**: fetch-group-based DB query
### Method responsibilities
- `getIfPresent(id)` => **L1 only**
- `getAll(ids)` => **L1 + L2 + DB loader** in batches
This aligns well with the current `AssocOneHelp` optimization and keeps the row-read path fast.
---
## Bottom line
If/when multi-level immutable caching is explored, the main points to preserve are:
1. keep `getIfPresent()` local-only
2. do remote work only in batched `getAll()`
3. key by type + id + tenant + fetch-group/cache identity
4. treat remote values as immutable snapshots
5. prefer JSON/self-describing format first
6. be cautious with generic binary serializers like Kryo
---
## Possible follow-up
If this becomes active design work later, consider promoting these notes into one of:
- a dedicated design note under `docs/notes/`
- a GitHub issue / discussion for design iteration
- a lightweight ADR if this becomes a committed architectural direction
+5 -33
View File
@@ -4,7 +4,7 @@
<parent>
<artifactId>ebean-parent</artifactId>
<groupId>io.ebean</groupId>
<version>13.23.0-jakarta</version>
<version>16.10.0</version>
</parent>
<name>ebean api</name>
@@ -26,20 +26,16 @@
<version>1.0</version>
</dependency>
<!--
Class retention Nonnull and Nullable annotations
to assist with IDE auto-completion with Ebean API
-->
<dependency>
<groupId>io.avaje</groupId>
<artifactId>avaje-lang</artifactId>
<version>1.1</version>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>io.avaje</groupId>
<artifactId>avaje-config</artifactId>
<version>3.8</version>
<version>4.2</version>
</dependency>
<dependency>
@@ -90,30 +86,6 @@
<optional>true</optional>
</dependency>
<!-- JAVAX-DEPENDENCY-START ___
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<optional>true</optional>
</dependency>
____ JAVAX-DEPENDENCY-END -->
<!-- JAKARTA-DEPENDENCY-START -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<optional>true</optional>
</dependency>
<!-- JAKARTA-DEPENDENCY-END -->
<dependency>
<groupId>io.avaje</groupId>
<artifactId>junit</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -1,10 +1,9 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import org.jspecify.annotations.NullMarked;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@@ -20,7 +19,7 @@ import java.util.concurrent.TimeUnit;
* This also propagates MDC context from the current thread to the
* background task if defined.
*/
@NonNullApi
@NullMarked
public interface BackgroundExecutor {
/**
@@ -0,0 +1,25 @@
package io.ebean;
/**
* Unsupported access of a property on an entity bean.
* <p>
* Attempted a lazy load operation on a bean that has disabled lazy loading
* or attempt to mutate an unmodifiable bean.
*/
public class BeanAccessException extends UnsupportedOperationException {
private static final long serialVersionUID = 1;
/**
* Create with no message.
*/
public BeanAccessException() {
super();
}
/**
* Create with message.
*/
public BeanAccessException(String message) {
super(message);
}
}
@@ -1,7 +1,7 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import io.avaje.lang.Nullable;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import java.util.List;
import java.util.Optional;
@@ -30,7 +30,7 @@ import java.util.Optional;
*
* @see BeanRepository
*/
@NonNullApi
@NullMarked
public abstract class BeanFinder<I,T> {
protected final Database database;
@@ -155,4 +155,10 @@ public abstract class BeanFinder<I,T> {
return db().findNative(type, nativeSql);
}
/**
* Creates a query using the ORM query language.
*/
protected Query<T> query(String ormQuery) {
return db().createQuery(type, ormQuery);
}
}
@@ -1,6 +1,6 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import org.jspecify.annotations.NullMarked;
import io.ebean.bean.EntityBean;
import java.util.Collection;
@@ -36,7 +36,7 @@ import java.util.Collection;
* @param <I> The ID type
* @param <T> The Bean type
*/
@NonNullApi
@NullMarked
public abstract class BeanRepository<I, T> extends BeanFinder<I, T> {
/**
@@ -89,12 +89,7 @@ public interface BeanState {
* <p>
* If a setter is called on a readOnly bean it will throw an exception.
*/
boolean isReadOnly();
/**
* Set the readOnly status for the bean.
*/
void setReadOnly(boolean readOnly);
boolean isUnmodifiable();
/**
* Advanced - Used to programmatically build a partially or fully loaded
+56 -53
View File
@@ -1,7 +1,7 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import io.avaje.lang.Nullable;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import io.ebean.annotation.TxIsolation;
import io.ebean.cache.ServerCacheManager;
import io.ebean.plugin.Property;
@@ -57,7 +57,7 @@ import java.util.concurrent.Callable;
*
* }</pre>
*/
@NonNullApi
@NullMarked
public final class DB {
private static final DbContext context = DbContext.getInstance();
@@ -266,55 +266,6 @@ public final class DB {
getDefault().register(transactionCallback);
}
/**
* Deprecated for removal migrate using try-with-resources and commit on the transaction itself.
* <p>
* Commit the current transaction.
*/
@Deprecated(forRemoval = true)
public static void commitTransaction() {
getDefault().commitTransaction();
}
/**
* Deprecated for removal migrate to using try-with-resources and rollback on the transaction itself.
* <p>
* Rollback the current transaction.
*/
@Deprecated(forRemoval = true)
public static void rollbackTransaction() {
getDefault().rollbackTransaction();
}
/**
* If the current transaction has already been committed do nothing otherwise
* rollback the transaction.
* <p>
* It is preferable to use <em>try with resources</em> rather than this.
* <p>
* Useful to put in a finally block to ensure the transaction is ended, rather
* than a rollbackTransaction() in each catch block.
* <p>
* Code example:
*
* <pre>{@code
* DB.beginTransaction();
* try {
* // do some fetching and or persisting
*
* // commit at the end
* DB.commitTransaction();
*
* } finally {
* // if commit didn't occur then rollback the transaction
* DB.endTransaction();
* }
* }</pre>
*/
public static void endTransaction() {
getDefault().endTransaction();
}
/**
* Mark the current transaction as rollback only.
*/
@@ -654,7 +605,7 @@ public final class DB {
* // find orders and their customers
* List<Order> list = DB.find(Order.class)
* .fetch("customer")
* .order("id")
* .orderBy("id")
* .findList();
*
* // sort by customer name ascending, then by order shipDate
@@ -790,6 +741,21 @@ public final class DB {
return getDefault().createUpdate(beanType, ormUpdate);
}
/**
* Create a named query.
* <p>
* For RawSql the named query is expected to be in ebean.xml.
*
* @param beanType The type of entity bean
* @param namedQuery The name of the query
* @param <T> The type of entity bean
* @return The query
*/
public static <T> Query<T> createNamedQuery(Class<T> beanType, String namedQuery) {
return getDefault().createNamedQuery(beanType, namedQuery);
}
/**
* Create a query for a type of entity bean.
* <p>
@@ -809,6 +775,43 @@ public final class DB {
return getDefault().createQuery(beanType);
}
/**
* Parse the Ebean query language statement returning the query which can then
* be modified (add expressions, change order by clause, change maxRows, change
* fetch and select paths etc).
* <p>
* <h3>Example</h3>
* <pre>{@code
*
* // Find order additionally fetching the customer, details and details.product name.
*
* String eql = "fetch customer fetch details fetch details.product (name) where id = :orderId ";
*
* Query<Order> query = DB.createQuery(Order.class, eql);
* query.setParameter("orderId", 2);
*
* Order order = query.findOne();
*
* // This is the same as:
*
* Order order = DB.find(Order.class)
* .fetch("customer")
* .fetch("details")
* .fetch("detail.product", "name")
* .setId(2)
* .findOne();
*
* }</pre>
*
* @param beanType The type of bean to fetch
* @param eql The Ebean query
* @param <T> The type of the entity bean
* @return The query with expressions defined as per the parsed query statement
*/
public static <T> Query<T> createQuery(Class<T> beanType, String eql) {
return getDefault().createQuery(beanType, eql);
}
/**
* Create a query for a type of entity bean.
* <p>
@@ -0,0 +1,104 @@
package io.ebean;
final class DInsertOptionsBuilder implements InsertOptions.Builder {
private Boolean getGeneratedKeys;
private boolean onConflictUpdate;
private boolean onConflictNothing;
private String constraint;
private String uniqueColumns;
private String updateSet;
@Override
public InsertOptions.Builder onConflictNothing() {
this.onConflictNothing = true;
return this;
}
@Override
public InsertOptions.Builder onConflictUpdate() {
this.onConflictUpdate = true;
return this;
}
@Override
public InsertOptions.Builder constraint(String constraint) {
this.constraint = constraint;
return this;
}
@Override
public InsertOptions.Builder uniqueColumns(String uniqueColumns) {
this.uniqueColumns = uniqueColumns;
return this;
}
@Override
public InsertOptions.Builder updateSet(String updateSet) {
this.updateSet = updateSet;
return this;
}
@Override
public InsertOptions.Builder getGeneratedKeys(boolean getGeneratedKeys) {
this.getGeneratedKeys = getGeneratedKeys;
return this;
}
@Override
public InsertOptions build() {
return new Options(constraint, uniqueColumns, updateSet, onConflictUpdate, onConflictNothing, getGeneratedKeys);
}
static final class Options implements InsertOptions {
private static final String UPDATE = "U";
private static final String NOTHING = "N";
private static final String NORMAL = "_";
private final String key;
private final Boolean getGeneratedKeys;
private final String constraint;
private final String uniqueColumns;
private final String updateSet;
Options(String constraint, String uniqueColumns, String updateSet, boolean onConflictUpdate, boolean onConflictNothing, Boolean getGeneratedKeys) {
this.constraint = constraint;
this.uniqueColumns = uniqueColumns;
this.updateSet = updateSet;
this.getGeneratedKeys = getGeneratedKeys;
this.key = (onConflictUpdate ? UPDATE : onConflictNothing ? NOTHING : NORMAL)
+ '+' + plus(constraint)
+ '+' + plus(uniqueColumns)
+ '+' + plus(updateSet);
}
private String plus(String val) {
return val == null ? "" : val;
}
@Override
public String key() {
return key;
}
@Override
public String constraint() {
return constraint;
}
@Override
public String uniqueColumns() {
return uniqueColumns;
}
@Override
public String updateSet() {
return updateSet;
}
@Override
public Boolean getGetGeneratedKeys() {
return getGeneratedKeys;
}
}
}
@@ -0,0 +1,50 @@
package io.ebean;
final class DPaging implements Paging {
static final Paging NONE = new DPaging(0, 0, null);
static Paging build(int pgIndex, int pgSize, OrderBy<?> orderBy) {
return new DPaging(pgIndex, pgSize, orderBy);
}
static Paging build(int pgIndex, int pgSize) {
return new DPaging(pgIndex, pgSize, null);
}
private final int pageNumber;
private final int pageSize;
private final OrderBy<?> orderBy;
DPaging(int pageNumber, int pageSize, OrderBy<?> orderBy) {
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.orderBy = orderBy;
}
@Override
public int pageIndex() {
return pageNumber;
}
@Override
public int pageSize() {
return pageSize;
}
@Override
public OrderBy<?> orderBy() {
return orderBy;
}
@Override
public Paging withPage(int pageNumber) {
return new DPaging(pageNumber, pageSize, orderBy);
}
@Override
public Paging withOrderBy(String orderByClause) {
return new DPaging(pageNumber, pageSize, OrderBy.of(orderByClause));
}
}
@@ -3,7 +3,7 @@ package io.ebean;
import jakarta.persistence.PersistenceException;
/**
* Thrown when a foreign key constraint is enforced.
* Thrown when a foreign key constraint is enforced or a field is too large.
*/
public class DataIntegrityException extends PersistenceException {
private static final long serialVersionUID = -6740171949170180970L;
@@ -14,4 +14,11 @@ public class DataIntegrityException extends PersistenceException {
public DataIntegrityException(String message, Throwable cause) {
super(message, cause);
}
/**
* Create with message only.
*/
public DataIntegrityException(String message) {
super(message);
}
}
+229 -69
View File
@@ -1,7 +1,7 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import io.avaje.lang.Nullable;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import io.ebean.annotation.Platform;
import io.ebean.annotation.TxIsolation;
import io.ebean.cache.ServerCacheManager;
@@ -23,11 +23,18 @@ import java.util.concurrent.Callable;
/**
* Provides the API for fetching and saving beans to a particular database.
*
* <h5>Constructing a Database</h5>
* <p>
* Databases are typically constructed via {@link #builder()} and {@link DatabaseBuilder#build()}.
* They can also be automatically constructed on demand using configuration information in
* the application.properties file. The underlying implementation is provided by
* {@link DatabaseFactory}.
*
* <h5>Registration with the DB singleton</h5>
* <p>
* When a Database instance is created it can be registered with the DB
* singleton (see {@link DatabaseConfig#setRegister(boolean)}). The DB
* singleton is essentially a map of Database's that have been registered
* When a Database instance is created it can be registered with the {@link DB}
* singleton (see {@link DatabaseBuilder#register(boolean)}). The {@link DB}
* singleton is essentially a map of {@link Database}'s that have been registered
* with it.
* <p>
* The Database can then be retrieved later via {@link DB#byName(String)}.
@@ -35,16 +42,10 @@ import java.util.concurrent.Callable;
* <h5>The 'default' Database</h5>
* <p>
* One Database can be designated as the 'default' or 'primary' Database
* (see {@link DatabaseConfig#setDefaultServer(boolean)}). Many methods on DB
* (see {@link DatabaseBuilder#defaultDatabase(boolean)}). Many methods on {@link DB}
* such as {@link DB#find(Class)} etc are actually just a convenient way to
* call methods on the 'default/primary' Database.
*
* <h5>Constructing a Database</h5>
* <p>
* Databases are constructed by the DatabaseFactory. They can be created
* programmatically via {@link DatabaseFactory#create(DatabaseConfig)} or they
* can be automatically constructed on demand using configuration information in
* the application.properties file.
*
* <h5>Example: Get a Database</h5>
* <pre>{@code
@@ -80,12 +81,32 @@ import java.util.concurrent.Callable;
* method. Example: a single thread requires more than one transaction.
*
* @see DB
* @see DatabaseBuilder
* @see DatabaseFactory
* @see DatabaseConfig
*/
@NonNullApi
@NullMarked
public interface Database {
/**
* Return a new database builder.
* <pre>{@code
*
* // build the 'default' database using configuration
* // from application.properties / application.yaml
*
* Database db = Database.builder()
* .name("db")
* .loadFromProperties()
* .build();
*
* }</pre>
*/
@SuppressWarnings("removal")
static DatabaseBuilder builder() {
return new DatabaseConfig();
}
/**
* Shutdown the Database instance.
*/
@@ -120,6 +141,7 @@ public interface Database {
/**
* Return the associated read only DataSource for this Database instance (can be null).
*/
@Nullable
DataSource readOnlyDataSource();
/**
@@ -225,6 +247,18 @@ public interface Database {
*/
<T> UpdateQuery<T> update(Class<T> beanType);
/**
* Create a named query.
* <p>
* For RawSql the named query is expected to be in ebean.xml.
*
* @param beanType The type of entity bean
* @param namedQuery The name of the query
* @param <T> The type of entity bean
* @return The query
*/
<T> Query<T> createNamedQuery(Class<T> beanType, String namedQuery);
/**
* Create a query for an entity bean and synonym for {@link #find(Class)}.
*
@@ -232,6 +266,41 @@ public interface Database {
*/
<T> Query<T> createQuery(Class<T> beanType);
/**
* Parse the Ebean query language statement returning the query which can then
* be modified (add expressions, change order by clause, change maxRows, change
* fetch and select paths etc).
* <p>
* <h3>Example</h3>
* <pre>{@code
*
* // Find order additionally fetching the customer, details and details.product name.
*
* String ormQuery = "fetch customer fetch details fetch details.product (name) where id = :orderId ";
*
* Query<Order> query = DB.createQuery(Order.class, ormQuery);
* query.setParameter("orderId", 2);
*
* Order order = query.findOne();
*
* // This is the same as:
*
* Order order = DB.find(Order.class)
* .fetch("customer")
* .fetch("details")
* .fetch("detail.product", "name")
* .setId(2)
* .findOne();
*
* }</pre>
*
* @param beanType The type of bean to fetch
* @param ormQuery The Ebean ORM query
* @param <T> The type of the entity bean
* @return The query with expressions defined as per the parsed query statement
*/
<T> Query<T> createQuery(Class<T> beanType, String ormQuery);
/**
* Create a query for a type of entity bean.
* <p>
@@ -336,7 +405,7 @@ public interface Database {
* // find orders and their customers
* List<Order> list = database.find(Order.class)
* .fetch("customer")
* .order("id")
* .orderBy("id")
* .findList();
*
* // sort by customer name ascending, then by order shipDate
@@ -395,6 +464,18 @@ public interface Database {
*/
<T> DtoQuery<T> findDto(Class<T> dtoType, String sql);
/**
* Create a named Query for DTO beans.
* <p>
* DTO beans are just normal bean like classes with public constructor(s) and setters.
* They do not need to be registered with DB before use.
*
* @param dtoType The type of the DTO bean the rows will be mapped into.
* @param namedQuery The name of the query
* @param <T> The type of the DTO bean.
*/
<T> DtoQuery<T> createNamedDtoQuery(Class<T> dtoType, String namedQuery);
/**
* Look to execute a native sql query that does not return beans but instead
* returns SqlRow or direct access to ResultSet.
@@ -590,49 +671,6 @@ public interface Database {
*/
void flush();
/**
* Deprecated for removal migrate using try-with-resources and commit on the transaction itself.
* <p>
* Commit the current transaction.
*/
@Deprecated(forRemoval = true)
void commitTransaction();
/**
* Deprecated for removal migrate to using try-with-resources and rollback on the transaction itself.
* <p>
* Rollback the current transaction.
*/
@Deprecated(forRemoval = true)
void rollbackTransaction();
/**
* If the current transaction has already been committed do nothing otherwise
* rollback the transaction.
* <p>
* Useful to put in a finally block to ensure the transaction is ended, rather
* than a rollbackTransaction() in each catch block.
* <p>
* Code example:
* <p>
* <pre>{@code
*
* database.beginTransaction();
* try {
* // do some fetching and or persisting ...
*
* // commit at the end
* database.commitTransaction();
*
* } finally {
* // if commit didn't occur then rollback the transaction
* database.endTransaction();
* }
*
* }</pre>
*/
void endTransaction();
/**
* Refresh the values of a bean.
* <p>
@@ -739,18 +777,6 @@ public interface Database {
*/
<T> T reference(Class<T> beanType, Object id);
/**
* Return the extended API for Database.
* <p>
* The extended API has the options for executing queries that take an explicit
* transaction as an argument.
* <p>
* Typically, we only need to use the extended API when we do NOT want to use the
* usual ThreadLocal based mechanism to obtain the current transaction but instead
* supply the transaction explicitly.
*/
ExtendedServer extended();
/**
* Either Insert or Update the bean depending on its state.
* <p>
@@ -1151,22 +1177,53 @@ public interface Database {
*/
void insert(Object bean);
/**
* Insert the bean with options (ON CONFLICT DO UPDATE | DO NOTHING).
* <p>
* Currently, this is limited to use with Postgres only,
* <p>
* When using this ebean will look to determine the unique columns by looking at
* the mapping like {@code @Column(unique=true} and {@code @Index(unique=true}.
*/
void insert(Object bean, InsertOptions insertOptions);
/**
* Insert the bean with a transaction.
*/
void insert(Object bean, Transaction transaction);
/**
* Insert the beans with options (ON CONFLICT DO UPDATE | DO NOTHING) and transaction.
* <p>
* Currently, this is limited to use with Postgres only,
*/
void insert(Object bean, InsertOptions insertOptions, Transaction transaction);
/**
* Insert a collection of beans. If there is no current transaction one is created and used to
* insert all the beans in the collection.
*/
void insertAll(Collection<?> beans);
/**
* Insert the beans with options - typically ON CONFLICT DO UPDATE | DO NOTHING.
* <p>
* Currently, this is limited to use with Postgres only,
*/
void insertAll(Collection<?> beans, InsertOptions options);
/**
* Insert a collection of beans with an explicit transaction.
*/
void insertAll(Collection<?> beans, Transaction transaction);
/**
* Insert the beans with options (ON CONFLICT DO UPDATE | DO NOTHING) and transaction.
* <p>
* Currently, this is limited to use with Postgres only,
*/
void insertAll(Collection<?> beans, InsertOptions options, Transaction transaction);
/**
* Execute explicitly passing a transaction.
*/
@@ -1321,6 +1378,109 @@ public interface Database {
*/
ScriptRunner script();
/**
* Return the Document store.
*/
DocumentStore docStore();
/**
* Publish a single bean given its type and id returning the resulting live bean.
* <p>
* The values are published from the draft to the live bean.
*
* @param <T> the type of the entity bean
* @param beanType the type of the entity bean
* @param id the id of the entity bean
* @param transaction the transaction the publish process should use (can be null)
*/
@Nullable
<T> T publish(Class<T> beanType, Object id, Transaction transaction);
/**
* Publish a single bean given its type and id returning the resulting live bean.
* This will use the current transaction or create one if required.
* <p>
* The values are published from the draft to the live bean.
*
* @param <T> the type of the entity bean
* @param beanType the type of the entity bean
* @param id the id of the entity bean
*/
@Nullable
<T> T publish(Class<T> beanType, Object id);
/**
* Publish the beans that match the query returning the resulting published beans.
* <p>
* The values are published from the draft beans to the live beans.
*
* @param <T> the type of the entity bean
* @param query the query used to select the draft beans to publish
* @param transaction the transaction the publish process should use (can be null)
*/
<T> List<T> publish(Query<T> query, Transaction transaction);
/**
* Publish the beans that match the query returning the resulting published beans.
* This will use the current transaction or create one if required.
* <p>
* The values are published from the draft beans to the live beans.
*
* @param <T> the type of the entity bean
* @param query the query used to select the draft beans to publish
*/
<T> List<T> publish(Query<T> query);
/**
* Restore the draft bean back to the live state.
* <p>
* The values from the live beans are set back to the draft bean and the
* <code>@DraftDirty</code> and <code>@DraftReset</code> properties are reset.
*
* @param <T> the type of the entity bean
* @param beanType the type of the entity bean
* @param id the id of the entity bean to restore
* @param transaction the transaction the restore process should use (can be null)
*/
@Nullable
<T> T draftRestore(Class<T> beanType, Object id, Transaction transaction);
/**
* Restore the draft bean back to the live state.
* <p>
* The values from the live beans are set back to the draft bean and the
* <code>@DraftDirty</code> and <code>@DraftReset</code> properties are reset.
*
* @param <T> the type of the entity bean
* @param beanType the type of the entity bean
* @param id the id of the entity bean to restore
*/
@Nullable
<T> T draftRestore(Class<T> beanType, Object id);
/**
* Restore the draft beans matching the query back to the live state.
* <p>
* The values from the live beans are set back to the draft bean and the
* <code>@DraftDirty</code> and <code>@DraftReset</code> properties are reset.
*
* @param <T> the type of the entity bean
* @param query the query used to select the draft beans to restore
* @param transaction the transaction the restore process should use (can be null)
*/
<T> List<T> draftRestore(Query<T> query, Transaction transaction);
/**
* Restore the draft beans matching the query back to the live state.
* <p>
* The values from the live beans are set back to the draft bean and the
* <code>@DraftDirty</code> and <code>@DraftReset</code> properties are reset.
*
* @param <T> the type of the entity bean
* @param query the query used to select the draft beans to restore
*/
<T> List<T> draftRestore(Query<T> query);
/**
* Returns the set of properties/paths that are unknown (do not map to known properties or paths).
* <p>
File diff suppressed because it is too large Load Diff
@@ -1,29 +1,25 @@
package io.ebean;
import io.ebean.config.ContainerConfig;
import io.ebean.config.DatabaseConfig;
import io.ebean.service.SpiContainer;
import io.ebean.service.SpiContainerFactory;
import jakarta.persistence.PersistenceException;
import java.util.Iterator;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.concurrent.locks.ReentrantLock;
/**
* Creates Database instances.
* Low-level factory for creating {@link Database} instances.
* <p>
* This uses either DatabaseConfig or properties in the application.properties file to
* configure and create a Database instance.
* Most applications should prefer {@link Database#builder()} together with {@link DatabaseBuilder#build()}.
* This factory remains for legacy creation entry points plus container lifecycle methods.
* <p>
* The Database instance can either be registered with the DB singleton or
* not. The DB singleton effectively holds a map of Database by a name.
* If the Database is registered with the DB singleton you can retrieve it
* The Database instance can either be registered with the {@link DB} singleton or
* not. The {@link DB} singleton effectively holds a map of {@link Database} by name.
* If the Database is registered with the {@link DB} singleton you can retrieve it
* later via {@link DB#byName(String)}.
* <p>
* One Database can be nominated as the 'default/primary' Database. Many
* methods on the DB singleton such as {@link DB#find(Class)} are just a
* methods on the {@link DB} singleton such as {@link DB#find(Class)} are just a
* convenient way of using the 'default/primary' Database.
*/
public final class DatabaseFactory {
@@ -40,7 +36,8 @@ public final class DatabaseFactory {
* Initialise the container with clustering configuration.
* <p>
* Call this prior to creating any Database instances or alternatively set the
* ContainerConfig on the DatabaseConfig when creating the first Database instance.
* {@link ContainerConfig} on the first {@link DatabaseBuilder} via
* {@link DatabaseBuilder#containerConfig(ContainerConfig)}.
*/
public static void initialiseContainer(ContainerConfig containerConfig) {
lock.lock();
@@ -52,8 +49,11 @@ public final class DatabaseFactory {
}
/**
* Create using properties to configure the database.
* Create using configuration loaded from properties for the given database name.
*
* @deprecated migrate to {@code Database.builder().name(name).loadFromProperties().build()}.
*/
@Deprecated
public static Database create(String name) {
lock.lock();
try {
@@ -64,21 +64,13 @@ public final class DatabaseFactory {
}
/**
* Create using the DatabaseConfig object to configure the database.
*
* <pre>{@code
*
* DatabaseConfig config = new DatabaseConfig();
* config.setName("db");
* config.loadProperties();
*
* Database database = DatabaseFactory.create(config);
*
* }</pre>
* @deprecated migrate to {@link DatabaseBuilder#build()}.
*/
public static Database create(DatabaseConfig config) {
@Deprecated(forRemoval = true)
public static Database create(DatabaseBuilder builder) {
lock.lock();
try {
var config = builder.settings();
if (config.getName() == null) {
throw new PersistenceException("The name is null (it is required)");
}
@@ -100,9 +92,10 @@ public final class DatabaseFactory {
}
/**
* Create using the DatabaseConfig additionally specifying a classLoader to use as the context class loader.
* Create using the {@link DatabaseBuilder}, additionally specifying a classLoader to use as the
* context class loader.
*/
public static Database createWithContextClassLoader(DatabaseConfig config, ClassLoader classLoader) {
public static Database createWithContextClassLoader(DatabaseBuilder config, ClassLoader classLoader) {
lock.lock();
try {
ClassLoader currentContextLoader = Thread.currentThread().getContextClassLoader();
@@ -132,7 +125,7 @@ public final class DatabaseFactory {
}
}
private static Database createInternal(DatabaseConfig config) {
private static Database createInternal(DatabaseBuilder.Settings config) {
return container(config.getContainerConfig()).createServer(config);
}
@@ -146,12 +139,9 @@ public final class DatabaseFactory {
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;
@@ -160,11 +150,11 @@ public final class DatabaseFactory {
/**
* Create the container instance using the configuration.
*/
protected static SpiContainer createContainer(ContainerConfig containerConfig) {
Iterator<SpiContainerFactory> factories = ServiceLoader.load(SpiContainerFactory.class).iterator();
if (factories.hasNext()) {
return factories.next().create(containerConfig);
private static SpiContainer createContainer(ContainerConfig containerConfig) {
SpiContainerFactory factory = XBootstrapService.containerFactory();
if (factory == null) {
throw new IllegalStateException("Service loader didn't find a SpiContainerFactory?");
}
throw new IllegalStateException("Service loader didn't find a SpiContainerFactory?");
return factory.create(containerConfig);
}
}
@@ -92,6 +92,7 @@ final class DbContext {
/**
* Read, create and put of Databases.
*/
@SuppressWarnings("deprecation")
private Database getWithCreate(String name) {
lock.lock();
try {
@@ -44,25 +44,12 @@ final class DbPrimary {
* Return the default database name.
*/
static String getDefaultServerName() {
lock.lock();
try {
getProperties();
return defaultServerName;
} finally {
lock.unlock();
}
}
/**
* Return the default configuration Properties.
*/
static Properties getProperties() {
lock.lock();
try {
if (defaultServerName == null) {
defaultServerName = determineDefaultServerName();
}
return Config.asProperties();
return defaultServerName;
} finally {
lock.unlock();
}
@@ -0,0 +1,94 @@
package io.ebean;
/**
* Bean holding the details to update the document store.
*/
public final class DocStoreQueueEntry {
/**
* Action to either update or delete a document from the index.
*/
public enum Action {
/**
* Action is to update a document in the doc store.
*/
INDEX(1),
/**
* Action is to delete a document from the doc store..
*/
DELETE(2),
/**
* An update is required based on a change to a nested/embedded object at a given path.
*/
NESTED(3);
int value;
Action(int value) {
this.value = value;
}
/**
* Return the value associated with this action type.
*/
public int getValue() {
return value;
}
}
private final Action type;
private final String queueId;
private final String path;
private final Object beanId;
/**
* Construct for an INDEX or DELETE action.
*/
public DocStoreQueueEntry(Action type, String queueId, Object beanId) {
this(type, queueId, null, beanId);
}
/**
* Construct for an NESTED/embedded path invalidation action.
*/
public DocStoreQueueEntry(Action type, String queueId, String path, Object beanId) {
this.type = type;
this.queueId = queueId;
this.path = path;
this.beanId = beanId;
}
/**
* Return the event type.
*/
public Action getType() {
return type;
}
/**
* Return the associate queueId.
*/
public String getQueueId() {
return queueId;
}
/**
* Return the path if this is a nested update.
*/
public String getPath() {
return path;
}
/**
* Return the bean id (which matches the document id).
*/
public Object getBeanId() {
return beanId;
}
}
@@ -0,0 +1,312 @@
package io.ebean;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import io.ebean.docstore.DocQueryContext;
import io.ebean.docstore.RawDoc;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* Document storage operations.
*/
@NullMarked
public interface DocumentStore {
/**
* Update the associated document store using the result of the query.
* <p>
* This will execute the query against the database creating a document for each
* bean graph and sending this to the document store.
* </p>
* <p>
* Note that the select and fetch paths of the query is set for you to match the
* document structure needed based on <code>@DocStore</code> and <code>@DocStoreEmbedded</code>
* so what this query requires is the predicates only.
* </p>
* <p>
* This query will be executed using findEach so it is safe to use a query
* that will fetch a lot of beans. The default bulkBatchSize is used.
* </p>
*
* @param query The query that selects object to send to the document store.
*/
<T> void indexByQuery(Query<T> query);
/**
* Update the associated document store index using the result of the query additionally specifying a
* bulkBatchSize to use for sending the messages to ElasticSearch.
*
* @param query The query that selects object to send to the document store.
* @param bulkBatchSize The batch size to use when bulk sending to the document store.
*/
<T> void indexByQuery(Query<T> query, int bulkBatchSize);
/**
* Update the document store for all beans of this type.
* <p>
* This is the same as indexByQuery where the query has no predicates and so fetches all rows.
* </p>
*/
void indexAll(Class<?> beanType);
/**
* Return the bean by fetching it's content from the document store.
* If the document is not found null is returned.
* <p>
* Typically this is called indirectly by findOne() on the query.
* </p>
* <pre>{@code
*
* Customer customer =
* database.find(Customer.class)
* .setUseDocStore(true)
* .setId(42)
* .findOne();
*
* }</pre>
*/
@Nullable
<T> T find(DocQueryContext<T> request);
/**
* Execute the find list query. This request is prepared to execute secondary queries.
* <p>
* Typically this is called indirectly by findList() on the query that has setUseDocStore(true).
* </p>
* <pre>{@code
*
* List<Customer> newCustomers =
* database.find(Customer.class)
* .setUseDocStore(true)
* .where().eq("status, Customer.Status.NEW)
* .findList();
*
* }</pre>
*/
<T> List<T> findList(DocQueryContext<T> request);
/**
* Execute the query against the document store returning the paged list.
* <p>
* The query should have <code>firstRow</code> or <code>maxRows</code> set prior to calling this method.
* </p>
* <p>
* Typically this is called indirectly by findPagedList() on the query that has setUseDocStore(true).
* </p>
* <pre>{@code
*
* PagedList<Customer> newCustomers =
* database.find(Customer.class)
* .setUseDocStore(true)
* .where().eq("status, Customer.Status.NEW)
* .setMaxRows(50)
* .findPagedList();
*
* }</pre>
*/
<T> PagedList<T> findPagedList(DocQueryContext<T> request);
/**
* Execute the query against the document store with the expectation of a large set of results
* that are processed in a scrolling resultSet fashion.
* <p>
* For example, with the ElasticSearch doc store this uses SCROLL.
* </p>
* <p>
* Typically this is called indirectly by findEach() on the query that has setUseDocStore(true).
* </p>
* <pre>{@code
*
* database.find(Order.class)
* .setUseDocStore(true)
* .where()... // perhaps add predicates
* .findEach((Order order) -> {
* // process the bean ...
* });
*
* }</pre>
*/
<T> void findEach(DocQueryContext<T> query, Consumer<T> consumer);
/**
* Execute the query against the document store with the expectation of a large set of results
* that are processed in a scrolling resultSet fashion.
* <p>
* Unlike findEach() this provides the opportunity to stop iterating through the large query.
* </p>
* <p>
* For example, with the ElasticSearch doc store this uses SCROLL.
* </p>
* <p>
* Typically this is called indirectly by findEachWhile() on the query that has setUseDocStore(true).
* </p>
* <pre>{@code
*
* database.find(Order.class)
* .setUseDocStore(true)
* .where()... // perhaps add predicates
* .findEachWhile(new Predicate<Order>() {
* @Override
* public void accept(Order bean) {
* // process the bean
*
* // return true to continue, false to stop
* // boolean shouldContinue = ...
* return shouldContinue;
* }
* });
*
* }</pre>
*/
<T> void findEachWhile(DocQueryContext<T> query, Predicate<T> consumer);
/**
* Find each processing raw documents.
*
* @param indexNameType The full index name and type
* @param rawQuery The query to execute
* @param consumer Consumer to process each document
*/
void findEach(String indexNameType, String rawQuery, Consumer<RawDoc> consumer);
/**
* Find each processing raw documents stopping when the predicate returns false.
*
* @param indexNameType The full index name and type
* @param rawQuery The query to execute
* @param consumer Consumer to process each document until false is returned
*/
void findEachWhile(String indexNameType, String rawQuery, Predicate<RawDoc> consumer);
/**
* Process the queue entries sending updates to the document store or queuing them for later processing.
*/
long process(List<DocStoreQueueEntry> queueEntries) throws IOException;
/**
* Drop the index from the document store (similar to DDL drop table).
* <pre>{@code
*
* DocumentStore documentStore = database.docStore();
*
* documentStore.dropIndex("product_copy");
*
* }</pre>
*/
void dropIndex(String indexName);
/**
* Create an index given a mapping file as a resource in the classPath (similar to DDL create table).
* <pre>{@code
*
* DocumentStore documentStore = database.docStore();
*
* // uses product_copy.mapping.json resource
* // ... to define mappings for the index
*
* documentStore.createIndex("product_copy", null);
*
* }</pre>
*
* @param indexName the name of the new index
* @param alias the alias of the index
*/
void createIndex(String indexName, String alias);
/**
* Modify the settings on an index.
* <p>
* For example, this can be used be used to set elasticSearch refresh_interval
* on an index before a bulk update.
* </p>
* <pre>{@code
*
* // refresh_interval -1 ... disable refresh while bulk loading
*
* Map<String,Object> settings = new LinkedHashMap<>();
* settings.put("refresh_interval", "-1");
*
* documentStore.indexSettings("product", settings);
*
* }</pre>
* <pre>{@code
*
* // refresh_interval 1s ... restore after bulk loading
*
* Map<String,Object> settings = new LinkedHashMap<>();
* settings.put("refresh_interval", "1s");
*
* documentStore.indexSettings("product", settings);
*
* }</pre>
*
* @param indexName the name of the index to update settings on
* @param settings the settings to set on the index
*/
void indexSettings(String indexName, Map<String, Object> settings);
/**
* Copy the index to a new index.
* <p>
* This copy process does not use the database but instead will copy from the source index to a destination index.
* </p>
* <pre>{@code
*
* long copyCount = documentStore.copyIndex(Product.class, "product_copy");
*
* }</pre>
*
* @param beanType The bean type of the source index
* @param newIndex The name of the index to copy to
* @return the number of documents copied to the new index
*/
long copyIndex(Class<?> beanType, String newIndex);
/**
* Copy entries from an index to a new index but limiting to documents that have been
* modified since the sinceEpochMillis time.
* <p>
* To support this the document needs to have a <code>@WhenModified</code> property.
* </p>
* <pre>{@code
*
* long copyCount = documentStore.copyIndex(Product.class, "product_copy", sinceMillis);
*
* }</pre>
*
* @param beanType The bean type of the source index
* @param newIndex The name of the index to copy to
* @return the number of documents copied to the new index
*/
long copyIndex(Class<?> beanType, String newIndex, long sinceEpochMillis);
/**
* Copy from a source index to a new index taking only the documents
* matching the given query.
* <pre>{@code
*
* // predicates to select the source documents to copy
* Query<Product> query = database.find(Product.class)
* .where()
* .ge("whenModified", new Timestamp(since))
* .ge("name", "A")
* .lt("name", "D")
* .query();
*
* // copy from the source index to "product_copy" index
* long copyCount = documentStore.copyIndex(query, "product_copy", 1000);
*
* }</pre>
*
* @param query The query to select the source documents to copy
* @param newIndex The target index to copy the documents to
* @param bulkBatchSize The ElasticSearch bulk batch size, if 0 uses the default.
* @return The number of documents copied to the new index.
*/
long copyIndex(Query<?> query, String newIndex, int bulkBatchSize);
}
+35 -6
View File
@@ -1,8 +1,10 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import io.avaje.lang.Nullable;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@@ -40,7 +42,7 @@ import java.util.stream.Stream;
*
* }</pre>
*/
@NonNullApi
@NullMarked
public interface DtoQuery<T> extends CancelableQuery {
/**
@@ -138,6 +140,17 @@ public interface DtoQuery<T> extends CancelableQuery {
* Bind the named multi-value array parameter which we would use with Postgres ANY.
* <p>
* For Postgres this binds an ARRAY rather than expands into multiple bind values.
* <pre>{@code
*
* String sql = "select id, name from o_customer where id = any(:idList)";
*
* var ids = List.of(1, 2, 3);
*
* List<CustomerDto> list2 = DB.findDto(CustomerDto.class, sql)
* .setArrayParameter("idList", ids)
* .findList();
*
* }</pre>
*/
DtoQuery<T> setArrayParameter(String name, Collection<?> values);
@@ -206,15 +219,31 @@ public interface DtoQuery<T> extends CancelableQuery {
*/
DtoQuery<T> usingTransaction(Transaction transaction);
/**
* Execute the query using the given connection.
*/
DtoQuery<T> usingConnection(Connection connection);
/**
* Ensure that the master DataSource is used if there is a read only data source
* being used (that is using a read replica database potentially with replication lag).
* <p>
* When the database is configured with a read-only DataSource via
* say {@link io.ebean.config.DatabaseConfig#setReadOnlyDataSource(DataSource)} then
* say {@link io.ebean.DatabaseBuilder#readOnlyDataSource(DataSource)} then
* by default when a query is run without an active transaction, it uses the read-only data
* source. We we use {@code usingMaster()} to instead ensure that the query is executed
* source. We use {@code usingMaster()} to instead ensure that the query is executed
* against the master data source.
*/
DtoQuery<T> usingMaster();
default DtoQuery<T> usingMaster() {
return usingMaster(true);
}
/**
* Ensure the master DataSource is used when useMaster is true. Otherwise, the read only
* data source can be used if defined.
*
* @see #usingMaster()
*/
DtoQuery<T> usingMaster(boolean useMaster);
}
@@ -5,6 +5,8 @@ import java.util.List;
import java.util.concurrent.Future;
/**
* @deprecated migrate to using {@link PagedList#emptyList()} only.
* <p>
* An empty PagedList.
* <p>
* For use in application code when we need to return a PagedList but don't want to
@@ -17,7 +19,8 @@ import java.util.concurrent.Future;
*
* }</pre>
*/
public class EmptyPagedList<T> implements PagedList<T> {
@Deprecated(forRemoval = true)
public final class EmptyPagedList<T> implements PagedList<T> {
@Override
public void loadCount() {
@@ -1,5 +1,7 @@
package io.ebean;
import io.ebean.search.*;
import java.util.Collection;
import java.util.Map;
@@ -623,6 +625,31 @@ public interface ExpressionFactory {
*/
Expression raw(String raw);
/**
* Create a Text Match expression (currently doc store/Elastic only).
*/
Expression textMatch(String propertyName, String search, Match options);
/**
* Create a Text Multi match expression (currently doc store/Elastic only).
*/
Expression textMultiMatch(String query, MultiMatch options);
/**
* Create a text simple query expression (currently doc store/Elastic only).
*/
Expression textSimple(String search, TextSimple options);
/**
* Create a text query string expression (currently doc store/Elastic only).
*/
Expression textQueryString(String search, TextQueryString options);
/**
* Create a text common terms expression (currently doc store/Elastic only).
*/
Expression textCommonTerms(String search, TextCommonTerms options);
/**
* And - join two expressions with a logical and.
*/
@@ -666,4 +693,12 @@ public interface ExpressionFactory {
*/
<T> Junction<T> junction(Junction.Type type, Query<T> query, ExpressionList<T> parent);
/**
* Add the expressions to the given expression list.
*
* @param where The expression list to add the expressions to
* @param expressions The expressions that are parsed
* @param params Bind parameters to match ? or ?1 bind positions.
*/
<T> void where(ExpressionList<T> where, String expressions, Object[] params);
}
@@ -1,7 +1,8 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import io.avaje.lang.Nullable;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import io.ebean.search.*;
import jakarta.persistence.NonUniqueResultException;
import java.sql.Connection;
@@ -30,7 +31,7 @@ import java.util.function.Predicate;
*
* @see Query#where()
*/
@NonNullApi
@NullMarked
public interface ExpressionList<T> {
/**
@@ -52,14 +53,6 @@ public interface ExpressionList<T> {
*/
Query<T> orderById(boolean orderById);
/**
* Deprecated migrate to {@link #orderBy(String)}
*/
@Deprecated(since = "13.19", forRemoval = true)
default ExpressionList<T> order(String orderByClause) {
return orderBy(orderByClause);
}
/**
* Set the order by clause replacing the existing order by clause if there is
* one.
@@ -70,14 +63,6 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> orderBy(String orderBy);
/**
* Deprecated migrate to orderBy().
*/
@Deprecated(forRemoval = true)
default OrderBy<T> order() {
return orderBy();
}
/**
* Return the OrderBy so that you can append an ascending or descending
* property to the order by clause.
@@ -105,6 +90,11 @@ public interface ExpressionList<T> {
*/
Query<T> asOf(Timestamp asOf);
/**
* Execute the query against the draft set of tables.
*/
Query<T> asDraft();
/**
* Convert the query to a DTO bean query.
* <p>
@@ -215,18 +205,6 @@ public interface ExpressionList<T> {
*/
int delete();
/**
* Execute as a delete query deleting the 'root level' beans that match the predicates
* in the query.
* <p>
* Note that if the query includes joins then the generated delete statement may not be
* optimal depending on the database platform.
* </p>
*
* @return the number of rows that were deleted.
*/
int delete(Transaction transaction);
/**
* Execute as a update query.
*
@@ -235,14 +213,6 @@ public interface ExpressionList<T> {
*/
int update();
/**
* Execute as a update query with the given transaction.
*
* @return the number of rows that were updated.
* @see UpdateQuery
*/
int update(Transaction transaction);
/**
* Execute the query returning true if a row is found.
* <p>
@@ -343,7 +313,7 @@ public interface ExpressionList<T> {
* List<String> names =
* DB.find(Customer.class)
* .select("name")
* .order().asc("name")
* .orderBy().asc("name")
* .findSingleAttributeList();
*
* }</pre>
@@ -356,7 +326,7 @@ public interface ExpressionList<T> {
* .setDistinct(true)
* .select("name")
* .where().eq("status", Customer.Status.NEW)
* .order().asc("name")
* .orderBy().asc("name")
* .setMaxRows(100)
* .findSingleAttributeList();
*
@@ -412,6 +382,42 @@ public interface ExpressionList<T> {
*/
Optional<T> findOneOrEmpty();
/**
* Execute find row count query in a background thread.
* <p>
* This returns a Future object which can be used to cancel, check the
* execution status (isDone etc) and get the value (with or without a
* timeout).
* </p>
*
* @return a Future object for the row count query
*/
FutureRowCount<T> findFutureCount();
/**
* Execute find Id's query in a background thread.
* <p>
* This returns a Future object which can be used to cancel, check the
* execution status (isDone etc) and get the value (with or without a
* timeout).
* </p>
*
* @return a Future object for the list of Id's
*/
FutureIds<T> findFutureIds();
/**
* Execute find list query in a background thread.
* <p>
* This returns a Future object which can be used to cancel, check the
* execution status (isDone etc) and get the value (with or without a
* timeout).
* </p>
*
* @return a Future object for the list result of the query
*/
FutureList<T> findFutureList();
/**
* Return a PagedList for this query using firstRow and maxRows.
* <p>
@@ -465,6 +471,28 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> filterMany(String manyProperty);
/**
* @deprecated for removal - migrate to {@link #filterManyRaw(String, String, Object...)}.
* <p>
* Add filter expressions to the many property.
*
* <pre>{@code
*
* DB.find(Customer.class)
* .where()
* .eq("name", "Rob")
* .filterMany("orders", "status = ?", Status.NEW)
* .findList();
*
* }</pre>
*
* @param manyProperty The many property
* @param expressions Filter expressions with and, or and ? or ?1 type bind parameters
* @param params Bind parameters used in the expressions
*/
@Deprecated(forRemoval = true)
ExpressionList<T> filterMany(String manyProperty, String expressions, Object... params);
/**
* Add filter expressions for the many path. The expressions can include SQL functions if
* desired and the property names are translated to column names.
@@ -516,6 +544,19 @@ public interface ExpressionList<T> {
*/
Query<T> setDistinct(boolean distinct);
/**
* Set the index(es) to search for a document store which uses partitions.
* <p>
* For example, when executing a query against ElasticSearch with daily indexes we can
* explicitly specify the indexes to search against.
* </p>
*
* @param indexName The index or indexes to search against
* @return This query
* @see Query#setDocIndexName(String)
*/
Query<T> setDocIndexName(String indexName);
/**
* Set the first row to fetch.
*
@@ -599,6 +640,14 @@ public interface ExpressionList<T> {
return setUseQueryCache(enabled ? CacheMode.ON : CacheMode.OFF);
}
/**
* Set to true if this query should execute against the doc store.
* <p>
* When setting this you may also consider disabling lazy loading.
* </p>
*/
Query<T> setUseDocStore(boolean useDocsStore);
/**
* Set true if you want to disable lazy loading.
* <p>
@@ -607,6 +656,16 @@ public interface ExpressionList<T> {
*/
Query<T> setDisableLazyLoading(boolean disableLazyLoading);
/**
* Disable read auditing for this query.
* <p>
* This is intended to be used when the query is not a user initiated query and instead
* part of the internal processing in an application to load a cache or document store etc.
* In these cases we don't want the query to be part of read auditing.
* </p>
*/
Query<T> setDisableReadAuditing();
/**
* Set a label on the query (to help identify query execution statistics).
*/
@@ -626,6 +685,14 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> where();
/**
* Add the expressions to this expression list.
*
* @param expressions The expressions that are parsed and added to this expression list
* @param params Bind parameters to match ? or ?1 bind positions.
*/
ExpressionList<T> where(String expressions, Object... params);
/**
* Path exists - for the given path in a JSON document.
* <pre>{@code
@@ -1006,6 +1073,14 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> like(String propertyName, String value);
/**
* Is LIKE if value is non-null and otherwise no expression is added to the query.
* <p>
* This is effectively a helper method that allows a query to be built in fluid style where some predicates are
* effectively optional. We can use <code>likeIfPresent()</code> rather than having a separate if block.
*/
ExpressionList<T> likeIfPresent(String propertyName, @Nullable String value);
/**
* Case insensitive Like - property like value where the value contains the
* SQL wild card characters % (percentage) and _ (underscore). Typically uses
@@ -1013,17 +1088,41 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> ilike(String propertyName, String value);
/**
* Is case insensitive LIKE if value is non-null and otherwise no expression is added to the query.
* <p>
* This is effectively a helper method that allows a query to be built in fluid style where some predicates are
* effectively optional. We can use <code>ilikeIfPresent()</code> rather than having a separate if block.
*/
ExpressionList<T> ilikeIfPresent(String propertyName, @Nullable String value);
/**
* Starts With - property like value%.
*/
ExpressionList<T> startsWith(String propertyName, String value);
/**
* Is STARTS WITH if value is non-null and otherwise no expression is added to the query.
* <p>
* This is effectively a helper method that allows a query to be built in fluid style where some predicates are
* effectively optional. We can use <code>startsWithIfPresent()</code> rather than having a separate if block.
*/
ExpressionList<T> startsWithIfPresent(String propertyName, @Nullable String value);
/**
* Case insensitive Starts With - property like value%. Typically uses a
* lower() function to make the expression case insensitive.
*/
ExpressionList<T> istartsWith(String propertyName, String value);
/**
* Is case insensitive STARTS WITH if value is non-null and otherwise no expression is added to the query.
* <p>
* This is effectively a helper method that allows a query to be built in fluid style where some predicates are
* effectively optional. We can use <code>istartsWithIfPresent()</code> rather than having a separate if block.
*/
ExpressionList<T> istartsWithIfPresent(String propertyName, @Nullable String value);
/**
* Ends With - property like %value.
*/
@@ -1040,12 +1139,28 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> contains(String propertyName, String value);
/**
* Is CONTAINS if value is non-null and otherwise no expression is added to the query.
* <p>
* This is effectively a helper method that allows a query to be built in fluid style where some predicates are
* effectively optional. We can use <code>containsIfPresent()</code> rather than having a separate if block.
*/
ExpressionList<T> containsIfPresent(String propertyName, @Nullable String value);
/**
* Case insensitive Contains - property like %value%. Typically uses a lower()
* function to make the expression case insensitive.
*/
ExpressionList<T> icontains(String propertyName, String value);
/**
* Is case insensitive CONTAINS if value is non-null and otherwise no expression is added to the query.
* <p>
* This is effectively a helper method that allows a query to be built in fluid style where some predicates are
* effectively optional. We can use <code>icontainsIfPresent()</code> rather than having a separate if block.
*/
ExpressionList<T> icontainsIfPresent(String propertyName, @Nullable String value);
/**
* In expression using pairs of value objects.
*/
@@ -1520,6 +1635,47 @@ public interface ExpressionList<T> {
*/
ExpressionList<T> rawOrEmpty(String raw, Collection<?> values);
/**
* Add a match expression.
*
* @param propertyName The property name for the match
* @param search The search value
*/
ExpressionList<T> match(String propertyName, String search);
/**
* Add a match expression with options.
*
* @param propertyName The property name for the match
* @param search The search value
*/
ExpressionList<T> match(String propertyName, String search, Match options);
/**
* Add a multi-match expression.
*/
ExpressionList<T> multiMatch(String search, String... properties);
/**
* Add a multi-match expression using options.
*/
ExpressionList<T> multiMatch(String search, MultiMatch options);
/**
* Add a simple query string expression.
*/
ExpressionList<T> textSimple(String search, TextSimple options);
/**
* Add a query string expression.
*/
ExpressionList<T> textQueryString(String search, TextQueryString options);
/**
* Add common terms expression.
*/
ExpressionList<T> textCommonTerms(String search, TextCommonTerms options);
/**
* And - join two expressions with a logical and.
*/
@@ -1563,7 +1719,7 @@ public interface ExpressionList<T> {
* .eq("status", Customer.Status.ACTIVE)
* .gt("id", 0)
* .endAnd()
* .order().asc("name")
* .orderBy().asc("name")
* .findList();
* }</pre>
*/
@@ -1584,7 +1740,7 @@ public interface ExpressionList<T> {
* .or()
* .eq("status", Customer.Status.ACTIVE)
* .isNull("anniversary")
* .order().asc("name")
* .orderBy().asc("name")
* .findList();
*
* }</pre>
@@ -1604,7 +1760,7 @@ public interface ExpressionList<T> {
* .eq("status", Customer.Status.ACTIVE)
* .gt("id", 0)
* .endAnd()
* .order().asc("name")
* .orderBy().asc("name")
* .findList();
*
* }</pre>
@@ -1638,7 +1794,7 @@ public interface ExpressionList<T> {
* .gt("id", 1)
* .eq("anniversary", onAfter)
* .endNot()
* .order()
* .orderBy()
* .asc("name")
* .findList();
*
@@ -1662,6 +1818,42 @@ public interface ExpressionList<T> {
*/
Junction<T> disjunction();
/**
* Start a list of expressions that will be joined by MUST.
* <p>
* This automatically makes the query a useDocStore(true) query that
* will execute against the document store (ElasticSearch etc).
* </p>
* <p>
* This is logically similar to and().
* </p>
*/
Junction<T> must();
/**
* Start a list of expressions that will be joined by SHOULD.
* <p>
* This automatically makes the query a useDocStore(true) query that
* will execute against the document store (ElasticSearch etc).
* </p>
* <p>
* This is logically similar to or().
* </p>
*/
Junction<T> should();
/**
* Start a list of expressions that will be joined by MUST NOT.
* <p>
* This automatically makes the query a useDocStore(true) query that
* will execute against the document store (ElasticSearch etc).
* </p>
* <p>
* This is logically similar to not().
* </p>
*/
Junction<T> mustNot();
/**
* End a junction returning the parent expression list.
* <p>
@@ -1,21 +0,0 @@
package io.ebean;
import java.time.Clock;
/**
* The extended API for Database.
*/
public interface ExtendedServer {
/**
* Deprecated but no yet determined suitable replacement (to support testing only change of clock).
* <p>
* Set the Clock to use for <code>@WhenCreated</code> and <code>@WhenModified</code>.
* <p>
* Note that we only expect to change the Clock for testing purposes.
* </p>
*/
@Deprecated
void setClock(Clock clock);
}
@@ -1,6 +1,6 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import org.jspecify.annotations.NullMarked;
import io.ebean.service.SpiFetchGroupQuery;
/**
@@ -61,7 +61,7 @@ import io.ebean.service.SpiFetchGroupQuery;
*
* @param <T> The bean type the Fetch group can be applied to
*/
@NonNullApi
@NullMarked
public interface FetchGroup<T> {
/**
@@ -84,7 +84,7 @@ public interface FetchGroup<T> {
* @return The FetchGroup with the given select clause
*/
static <T> FetchGroup<T> of(Class<T> cls, String select) {
return XServiceProvider.fetchGroupOf(cls, select);
return XBootstrapService.fetchGroupOf(cls, select);
}
/**
@@ -108,14 +108,14 @@ public interface FetchGroup<T> {
* @return The FetchGroupBuilder with the given select clause which we will add fetch clauses to
*/
static <T> FetchGroupBuilder<T> of(Class<T> cls) {
return XServiceProvider.fetchGroupOf(cls);
return XBootstrapService.fetchGroupOf(cls);
}
/**
* Return a query to be used by query beans for constructing FetchGroup.
*/
static <T> SpiFetchGroupQuery<T> queryFor(Class<T> beanType) {
return XServiceProvider.fetchGroupQueryFor(beanType);
return XBootstrapService.fetchGroupQueryFor(beanType);
}
}
@@ -1,6 +1,6 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import org.jspecify.annotations.NullMarked;
/**
* Builds a FetchGroup by adding fetch clauses.
@@ -23,7 +23,7 @@ import io.avaje.lang.NonNullApi;
*
* }</pre>
*/
@NonNullApi
@NullMarked
public interface FetchGroupBuilder<T> {
/**
+2 -2
View File
@@ -1,6 +1,6 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import org.jspecify.annotations.NullMarked;
import java.util.List;
import java.util.Set;
@@ -79,7 +79,7 @@ import java.util.Set;
*
* @param <T> the entity bean type
*/
@NonNullApi
@NullMarked
public interface Filter<T> {
/**
+11 -4
View File
@@ -1,7 +1,7 @@
package io.ebean;
import io.avaje.lang.NonNullApi;
import io.avaje.lang.Nullable;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import java.util.List;
/**
@@ -35,7 +35,7 @@ import java.util.List;
* public List<Customer> findNew() {
* return query().where()
* .eq("status", Customer.Status.NEW)
* .order("name")
* .orderBy("name")
* .findList()
* }
* }
@@ -60,7 +60,7 @@ import java.util.List;
* @see BeanRepository
* @see BeanFinder
*/
@NonNullApi
@NullMarked
public class Finder<I, T> {
/**
@@ -213,4 +213,11 @@ public class Finder<I, T> {
return db().findNative(type, nativeSql);
}
/**
* Creates a query using the ORM query language.
*/
public Query<T> query(String ormQuery) {
return db().createQuery(type, ormQuery);
}
}
@@ -0,0 +1,20 @@
package io.ebean;
import java.util.List;
import java.util.concurrent.Future;
/**
* FutureIds represents the result of a background query execution for the Id's.
* <p>
* It extends the java.util.concurrent.Future with the ability to get the Id's
* while the query is still executing in the background.
* </p>
*/
public interface FutureIds<T> extends Future<List<Object>> {
/**
* Returns the original query used to fetch the Id's.
*/
Query<T> getQuery();
}
@@ -0,0 +1,74 @@
package io.ebean;
import jakarta.persistence.PersistenceException;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* FutureMap represents the result of a background query execution that will
* return a map of entities.
* <p>
* It extends the java.util.concurrent.Future with the ability to cancel the
* query, check if it is finished and get the resulting list waiting for the
* query to finish (ie. the standard features of java.util.concurrent.Future).
* </p>
* <p>
* A simple example:
* </p>
* <pre>{@code
*
* // create a query to find all orders
* Query<Long,Order> query = DB.find(Order.class)
* .setMapKey("id");
*
* // execute the query in a background thread
* // immediately returning the futureMap
* FutureMap<Long,Order> futureMap = query.findFutureMap();
*
* // do something else ...
*
* if (!futureMap.isDone()){
* // we can cancel the query execution. This will cancel
* // the underlying query if that is supported by the JDBC
* // driver and database
* futureMap.cancel(true);
* }
*
* if (!futureMap.isCancelled()){
* // wait for the query to finish and return the map
* Map<Long,Order> map = futureMap.get();
* ...
* }
*
* }</pre>
*/
public interface FutureMap<K, T> extends Future<Map<K, T>> {
/**
* Return the query that is being executed by a background thread.
*/
Query<T> getQuery();
/**
* Same as {@link #get()} but wraps InterruptedException and ExecutionException in the
* unchecked PersistenceException.
*
* @return The query list result
* @throws PersistenceException when a InterruptedException or ExecutionException occurs.
*/
Map<K, T> getUnchecked();
/**
* Same as {@link #get(long, TimeUnit)} but wraps InterruptedException
* and ExecutionException in the unchecked PersistenceException.
*
* @return The query list result
* @throws TimeoutException if the wait timed out
* @throws PersistenceException if a InterruptedException or ExecutionException occurs.
*/
Map<K, T> getUnchecked(long timeout, TimeUnit unit) throws TimeoutException;
}
@@ -0,0 +1,58 @@
package io.ebean;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import java.util.Map;
import java.util.Set;
/**
* Query-scoped immutable bean cache.
*
* <p>Typical use is to attach an immutable cache to a query and let Ebean use it when
* resolving assoc-one references.
*
* <pre>{@code
* FetchGroup<Customer> customerGroup = FetchGroup.of(Customer.class)
* .select("name,version")
* .fetch("billingAddress", "line1,city")
* .fetch("shippingAddress", "line1,city")
* .build();
*
* ImmutableBeanCache<Customer> customerCache = ImmutableBeanCaches.builder(Customer.class)
* .loading(database, customerGroup)
* .build();
*
* Order order = database.find(Order.class)
* .setId(id)
* .setUnmodifiable(true)
* .using(customerCache)
* .findOne();
* }</pre>
*
* @param <T> The bean type.
*
* @see ImmutableBeanCaches#builder(Class)
*/
@NullMarked
public interface ImmutableBeanCache<T> {
/**
* Return the bean type this cache provides values for.
*/
Class<T> type();
/**
* Return immutable cached beans by id (loading and populating misses as needed).
*/
Map<Object, T> getAll(Set<Object> ids);
/**
* Return a cached bean for the given id if it is already present.
* <p>
* This does not trigger loading or record a miss.
*/
default @Nullable T getIfPresent(Object id) {
return null;
}
}
@@ -0,0 +1,246 @@
package io.ebean;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import io.ebean.service.SpiImmutableCacheFactory;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import static java.util.Objects.requireNonNull;
/**
* Utility factory methods for {@link ImmutableBeanCache}.
*
* <p>Use {@link #builder(Class)} when you want explicit cache policy controls (for example
* max size or TTL). Use {@link #loading(Class, Database, FetchGroup)} as a shorthand for
* query-loader-backed memoization.
*
* <pre>{@code
* FetchGroup<MyRef> fetchGroup = FetchGroup.of(MyRef.class)
* .select("version")
* .build();
*
* ImmutableBeanCache<MyRef> cache = ImmutableBeanCaches.builder(MyRef.class)
* .loading(database, fetchGroup)
* .maxSize(10_000)
* .maxIdleSeconds(300)
* .maxSecondsToLive(1_800)
* .build();
* }</pre>
*/
@NullMarked
public final class ImmutableBeanCaches {
private ImmutableBeanCaches() {
}
/**
* Return a builder for immutable bean caches.
*
* <pre>{@code
* ImmutableBeanCache<MyRef> cache = ImmutableBeanCaches.builder(MyRef.class)
* .loading(database, FetchGroup.of(MyRef.class, "version"))
* .build();
* }</pre>
*/
public static <T> ImmutableCacheBuilder<T> builder(Class<T> type) {
SpiImmutableCacheFactory factory = XBootstrapService.immutableCacheFactory();
if (factory != null) {
return factory.builder(type);
}
return new LoadingBuilder<>(type);
}
/**
* Return a loader-backed immutable bean cache that memoizes both hits and misses.
*
* <pre>{@code
* ImmutableBeanCache<MyRef> cache = ImmutableBeanCaches.loading(MyRef.class, ids ->
* database.find(MyRef.class)
* .setUnmodifiable(true)
* .where().idIn(ids)
* .findMap()
* );
* }</pre>
*
* @param type The bean type.
* @param loader Batch loader for unresolved ids.
*/
public static <T> ImmutableBeanCache<T> loading(Class<T> type, Function<Set<Object>, Map<Object, T>> loader) {
return builder(type).loader(loader).build();
}
/**
* Return a query-loader-backed immutable bean cache.
*
* <pre>{@code
* ImmutableBeanCache<MyRef> cache = ImmutableBeanCaches.loading(
* MyRef.class,
* database,
* FetchGroup.of(MyRef.class, "version")
* );
* }</pre>
*/
public static <T> ImmutableBeanCache<T> loading(Class<T> type, Database db, FetchGroup<T> fetchGroup) {
return builder(type).loading(db, fetchGroup).build();
}
/**
* Return a batch loader backed by an unmodifiable query using the given fetch group.
*/
public static <T> Function<Set<Object>, Map<Object, T>> queryLoader(Database db, Class<T> type, FetchGroup<T> fetchGroup) {
return new QueryLoader<>(type, db, fetchGroup);
}
private static final class QueryLoader<T> implements Function<Set<Object>, Map<Object, T>> {
private final Class<T> type;
private final Database db;
private final FetchGroup<T> fetchGroup;
QueryLoader(Class<T> type, Database db, FetchGroup<T> fetchGroup) {
this.type = requireNonNull(type);
this.db = requireNonNull(db);
this.fetchGroup = requireNonNull(fetchGroup);
}
@Override
public Map<Object, T> apply(Set<Object> ids) {
if (ids.isEmpty()) {
return Collections.emptyMap();
}
return db.find(type)
.select(fetchGroup)
.setUnmodifiable(true)
.where().idIn(ids)
.findMap();
}
}
private static final class LoadingBuilder<T> implements ImmutableCacheBuilder<T> {
private final Class<T> type;
private Function<Set<Object>, Map<Object, T>> loader;
private int maxSize;
private int maxIdleSeconds;
private int maxSecondsToLive;
private LoadingBuilder(Class<T> type) {
this.type = requireNonNull(type);
}
@Override
public ImmutableCacheBuilder<T> loader(Function<Set<Object>, Map<Object, T>> loader) {
this.loader = requireNonNull(loader);
return this;
}
@Override
public ImmutableCacheBuilder<T> loading(Database db, FetchGroup<T> fetchGroup) {
this.loader = new QueryLoader<>(type, db, fetchGroup);
return this;
}
@Override
public ImmutableCacheBuilder<T> maxSize(int maxSize) {
this.maxSize = maxSize;
return this;
}
@Override
public ImmutableCacheBuilder<T> maxIdleSeconds(int maxIdleSeconds) {
this.maxIdleSeconds = maxIdleSeconds;
return this;
}
@Override
public ImmutableCacheBuilder<T> maxSecondsToLive(int maxSecondsToLive) {
this.maxSecondsToLive = maxSecondsToLive;
return this;
}
@Override
public ImmutableBeanCache<T> build() {
if (loader == null) {
throw new IllegalStateException("No loader defined. Call loader(...) or loading(...) before build().");
}
if (maxSize > 0 || maxIdleSeconds > 0 || maxSecondsToLive > 0) {
throw new IllegalStateException("Cache policy options require SpiImmutableCacheFactory (ebean-core).");
}
return new LoadingCache<>(type, loader);
}
}
private static final class LoadingCache<T> implements ImmutableBeanCache<T> {
private final Class<T> type;
private final Function<Set<Object>, Map<Object, T>> loader;
private final ConcurrentHashMap<Object, T> cache = new ConcurrentHashMap<>();
private final Set<Object> misses = ConcurrentHashMap.newKeySet();
private LoadingCache(Class<T> type, Function<Set<Object>, Map<Object, T>> loader) {
this.type = requireNonNull(type);
this.loader = requireNonNull(loader);
}
@Override
public Class<T> type() {
return type;
}
@Override
public @Nullable T getIfPresent(Object id) {
return cache.get(id);
}
@Override
public Map<Object, T> getAll(Set<Object> ids) {
if (ids.isEmpty()) {
return Collections.emptyMap();
}
Set<Object> loadIds = null;
for (Object id : ids) {
if (!cache.containsKey(id) && !misses.contains(id)) {
if (loadIds == null) {
loadIds = new LinkedHashSet<>();
}
loadIds.add(id);
}
}
if (loadIds != null && !loadIds.isEmpty()) {
Map<Object, T> loaded = loader.apply(loadIds);
if (loaded == null) {
loaded = Collections.emptyMap();
}
for (Map.Entry<Object, T> entry : loaded.entrySet()) {
if (entry.getValue() != null) {
cache.put(entry.getKey(), entry.getValue());
}
}
for (Object id : loadIds) {
if (!cache.containsKey(id)) {
misses.add(id);
}
}
}
Map<Object, T> result = new LinkedHashMap<>();
for (Object id : ids) {
T bean = cache.get(id);
if (bean != null) {
result.put(id, bean);
}
}
return result;
}
}
}
@@ -0,0 +1,60 @@
package io.ebean;
import org.jspecify.annotations.NullMarked;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
/**
* Builder for creating {@link ImmutableBeanCache} instances.
*
* <pre>{@code
* FetchGroup<MyRef> fetchGroup = FetchGroup.of(MyRef.class)
* .select("version")
* .fetch("names", "locale,text")
* .build();
*
* ImmutableBeanCache<MyRef> cache = ImmutableBeanCaches.builder(MyRef.class)
* .loading(database, fetchGroup)
* .maxSize(10_000)
* .maxIdleSeconds(300)
* .maxSecondsToLive(1_800)
* .build();
* }</pre>
*
* @see ImmutableBeanCaches#builder(Class)
*/
@NullMarked
public interface ImmutableCacheBuilder<T> {
/**
* Set the batch loader used for unresolved ids.
*/
ImmutableCacheBuilder<T> loader(Function<Set<Object>, Map<Object, T>> loader);
/**
* Configure a query-based loader using the given database and fetch group.
*/
ImmutableCacheBuilder<T> loading(Database db, FetchGroup<T> fetchGroup);
/**
* Configure max cache size (0 means unbounded).
*/
ImmutableCacheBuilder<T> maxSize(int maxSize);
/**
* Configure max idle time in seconds (0 means disabled).
*/
ImmutableCacheBuilder<T> maxIdleSeconds(int maxIdleSeconds);
/**
* Configure max time-to-live in seconds (0 means disabled).
*/
ImmutableCacheBuilder<T> maxSecondsToLive(int maxSecondsToLive);
/**
* Build the immutable bean cache.
*/
ImmutableBeanCache<T> build();
}
@@ -0,0 +1,119 @@
package io.ebean;
import org.jspecify.annotations.Nullable;
/**
* Options to be used with insert such as ON CONFLICT DO UPDATE | NOTHING.
*/
public interface InsertOptions {
/**
* Use ON CONFLICT UPDATE with automatic determination of the unique columns to conflict on.
* <p>
* Uses mapping to determine the unique columns - {@code @Column(unique=true)} and {@code @Index(unique=true)} .
*/
InsertOptions ON_CONFLICT_UPDATE = InsertOptions.builder()
.onConflictUpdate()
.build();
/**
* Use ON CONFLICT DO NOTHING with automatic determination of the unique columns to conflict on.
* <p>
* Uses mapping to determine the unique columns - {@code @Column(unique=true)} and {@code @Index(unique=true)} .
*/
InsertOptions ON_CONFLICT_NOTHING = InsertOptions.builder()
.onConflictNothing()
.build();
/**
* Return a builder for InsertOptions.
*/
static Builder builder() {
return new DInsertOptionsBuilder();
}
/**
* Return the constraint name that is used for ON CONFLICT.
*/
@Nullable
String constraint();
/**
* Return the unique columns that is used for ON CONFLICT.
* <p>
* When not explicitly set will use mapping like {@code @Column(unique=true)} to determine the
* non-unique columns.
*/
@Nullable
String uniqueColumns();
/**
* Return the ON CONFLICT UPDATE SET clause.
* <p>
* When not set will use the non-unique columns.
*/
@Nullable
String updateSet();
/**
* Return if GetGeneratedKeys should be used to fetch the generated keys after insert.
*/
@Nullable
Boolean getGetGeneratedKeys();
/**
* Return the key for these build options.
*/
String key();
/**
* The builder for InsertOptions.
*/
interface Builder {
/**
* Use a ON CONFLICT UPDATE automatically determining the unique columns.
*/
Builder onConflictUpdate();
/**
* Use a ON CONFLICT DO NOTHING automatically determining the unique columns.
*/
Builder onConflictNothing();
/**
* Specify an explicit conflict constraint name.
* <p>
* When this is used then unique columns will not be used.
*/
Builder constraint(String constraint);
/**
* Specify the unique columns for the conflict target.
* <p>
* When not specified and constraint is also not specified then
* it will automatically determine the unique columns
* based on mapping like {@code @Column(unique=true)} and
* {@code @Index(unique=true)} .
*/
Builder uniqueColumns(String uniqueColumns);
/**
* Specify the ON CONFLICT DO UPDATE SET clause.
* <p>
* When not specified ebean will include all the non-unique columns.
*/
Builder updateSet(String updateSet);
/**
* Specify if GetGeneratedKeys should be used to return generated keys.
*/
Builder getGeneratedKeys(boolean getGeneratedKeys);
/**
* Build and return the insert options.
*/
InsertOptions build();
}
}
@@ -61,7 +61,7 @@ package io.ebean;
* .eq("status", Customer.Status.ACTIVE)
* .gt("id", 0)
* .endAnd()
* .order().asc("name");
* .orderBy().asc("name");
*
* q.findList();
* String s = q.getGeneratedSql();
@@ -0,0 +1,19 @@
package io.ebean;
/**
* Thrown when trying to access a property that isn't loaded on an entity
* that is unmodifiable or has disabled lazy loading.
* <p>
* On a normal mutable entity accessing the property would invoke lazy loading. On
* a unmodifiable entity with lazy loading disabled, accessing an unloaded property
* throws this LazyInitialisationException instead.
*/
public class LazyInitialisationException extends BeanAccessException {
/**
* Create specifying the property that was being accessed.
*/
public LazyInitialisationException(String message) {
super(message);
}
}
@@ -16,4 +16,7 @@ public interface ModifyAwareType {
*/
void setMarkedDirty(boolean markedDirty);
default Object freeze() {
return this; // throw new UnsupportedOperationException();
}
}
+90 -40
View File
@@ -8,13 +8,11 @@ import java.util.Objects;
/**
* Represents an Order By for a Query.
* <p>
* Is a ordered list of OrderBy.Property objects each specifying a property and
* Is an ordered list of OrderBy.Property objects each specifying a property and
* whether it is ascending or descending order.
* </p>
* <p>
* Typically you will not construct an OrderBy yourself but use one that exists
* Typically, you will not construct an OrderBy yourself but use one that exists
* on the Query object.
* </p>
*/
public class OrderBy<T> implements Serializable {
@@ -25,8 +23,22 @@ public class OrderBy<T> implements Serializable {
private final List<Property> list;
/**
* Create an OrderBy parsing the given order by clause.
* <p>
* The order by clause follows SQL order by clause with comma's between each
* property and optionally "asc" or "desc" to represent ascending or
* descending order respectively.
*/
public static <P> OrderBy<P> of(String orderByClause) {
return new OrderBy<>(orderByClause);
}
/**
* @deprecated This method will be removed from public API.
* <p>
* Create an empty OrderBy with no associated query.
*/
@Deprecated(forRemoval = true)
public OrderBy() {
this.list = new ArrayList<>(3);
}
@@ -36,20 +48,17 @@ public class OrderBy<T> implements Serializable {
}
/**
* Create an orderBy parsing the order by clause.
* <p>
* The order by clause follows SQL order by clause with comma's between each
* property and optionally "asc" or "desc" to represent ascending or
* descending order respectively.
* </p>
* @deprecated migrate to {@link OrderBy#of(String)}.
*/
@Deprecated(forRemoval = true)
public OrderBy(String orderByClause) {
this(null, orderByClause);
}
/**
* Construct with a given query and order by clause.
* @deprecated This method will be removed from public API.
*/
@Deprecated(forRemoval = true)
public OrderBy(Query<T> query, String orderByClause) {
this.query = query;
this.list = new ArrayList<>(3);
@@ -110,8 +119,11 @@ public class OrderBy<T> implements Serializable {
}
/**
* @deprecated This method will become internal only API.
* <p>
* Return a copy of this OrderBy with the path trimmed.
*/
@Deprecated(forRemoval = true)
public OrderBy<T> copyWithTrim(String path) {
List<Property> newList = new ArrayList<>(list.size());
for (Property aList : list) {
@@ -186,15 +198,15 @@ public class OrderBy<T> implements Serializable {
if (list.isEmpty()) {
return null;
}
StringBuilder sb = new StringBuilder();
var append = new StringAppend();
for (int i = 0; i < list.size(); i++) {
Property property = list.get(i);
if (i > 0) {
sb.append(", ");
append.append(", ");
}
sb.append(property.toStringFormat());
property.toStringFormat(append);
}
return sb.toString();
return append.toString();
}
@Override
@@ -231,6 +243,55 @@ public class OrderBy<T> implements Serializable {
return this;
}
/**
* Append the order by clause.
*/
public interface Append {
/**
* Append a property expression.
*/
Append property(String property);
/**
* Append a literal.
*/
Append append(String literal);
/**
* Parse and append an expression.
*/
Append parse(String expression);
}
private static final class StringAppend implements Append {
private final StringBuilder builder = new StringBuilder();
@Override
public String toString() {
return builder.toString();
}
@Override
public Append property(String property) {
builder.append(property);
return this;
}
@Override
public Append append(String literal) {
builder.append(literal);
return this;
}
@Override
public Append parse(String raw) {
builder.append(raw);
return this;
}
}
/**
* A property and its ascending descending order.
*/
@@ -309,36 +370,25 @@ public class OrderBy<T> implements Serializable {
@Override
public String toString() {
return toStringFormat();
return property;
}
public String toStringFormat() {
if (nulls == null && collation == null) {
if (ascending) {
return property;
public void toStringFormat(Append append) {
if (collation != null) {
if (collation.contains("${}")) {
// this is a complex collation, e.g. DB2 - we must replace the property
append.parse(collation.replace("${}", property));
} else {
return property + " desc";
append.property(property).append(" collate ").append(collation);
}
} else {
StringBuilder sb = new StringBuilder();
if (collation != null) {
if (collation.contains("${}")) {
// this is a complex collation, e.g. DB2 - we must replace the property
sb.append(collation.replace("${}", property));
} else {
sb.append(property);
sb.append(" collate ").append(collation);
}
} else {
sb.append(property);
}
if (!ascending) {
sb.append(' ').append("desc");
}
if (nulls != null) {
sb.append(' ').append(nulls).append(' ').append(highLow);
}
return sb.toString();
append.property(property);
}
if (!ascending) {
append.append(" desc");
}
if (nulls != null) {
append.append(" ").append(nulls).append(" ").append(highLow);
}
}
@@ -25,7 +25,7 @@ import java.util.concurrent.Future;
*
* PagedList<Order> pagedList = DB.find(Order.class)
* .where().eq("status", Order.Status.NEW)
* .order().asc("id")
* .orderBy().asc("id")
* .setFirstRow(0)
* .setMaxRows(50)
* .findPagedList();
@@ -0,0 +1,90 @@
package io.ebean;
import org.jspecify.annotations.Nullable;
/**
* Used to specify Paging on a Query as an alternative to setting each of the
* maxRows, firstRow and orderBy clause via:
* {@link Query#setMaxRows(int)} + {@link Query#setFirstRow(int)} + {@link Query#setOrderBy(OrderBy)}.
* <p>
* Example use:
*
* <pre>{@code
*
* var orderBy = OrderBy.of("lastName desc nulls first, firstName asc");
* var paging = Paging.of(0, 100, orderBy);
*
* new QCustomer()
* .name.isNotNull()
* .setPaging(paging)
* .findList();
*
* }</pre>
*/
public interface Paging {
/**
* Create a Paging with the given page index size and orderBy.
*
* @param pageIndex the page index starting from zero
* @param pageSize the page size (effectively max rows)
* @param orderBy order by for the query result
*/
static Paging of(int pageIndex, int pageSize, @Nullable OrderBy<?> orderBy) {
return DPaging.build(pageIndex, pageSize, orderBy);
}
/**
* Create a Paging with a raw order by clause.
*
* @param pageIndex the page index starting from zero
* @param pageSize the page size (effectively max rows)
* @param orderByClause raw order by clause for ordering the query result
*/
static Paging of(int pageIndex, int pageSize, @Nullable String orderByClause) {
return of(pageIndex, pageSize, OrderBy.of(orderByClause));
}
/**
* Create a Paging that will use the id property for ordering.
*
* @param pageIndex the page index starting from zero
* @param pageSize the page size (effectively max rows)
*/
static Paging of(int pageIndex, int pageSize) {
return DPaging.build(pageIndex, pageSize);
}
/**
* Return a Paging that will not apply any pagination to a query.
*/
static Paging ofNone() {
return DPaging.NONE;
}
/**
* Return the page index.
*/
int pageIndex();
/**
* Return the page size.
*/
int pageSize();
/**
* Return the order by.
*/
OrderBy<?> orderBy();
/**
* Return a Paging using the given page index.
*/
Paging withPage(int pageIndex);
/**
* Return a Paging using the given order by clause.
*/
Paging withOrderBy(String orderByClause);
}
+1 -1
View File
@@ -30,7 +30,7 @@ import java.util.Objects;
* .where()
* .eq("store", "def")
* .inPairs(pairs) // IN clause with 'pairs' of values
* .order("sku desc")
* .orderBy("sku desc")
*
* // query expressions cover the natural key properties
* // so we can choose to hit the L2 bean cache if we want
@@ -13,21 +13,21 @@ public interface ProfileLocation {
* Create and return a new ProfileLocation.
*/
static ProfileLocation create() {
return XServiceProvider.profileLocationFactory().create();
return XBootstrapService.profileLocationFactory().create();
}
/**
* Create and return a new ProfileLocation with line number.
*/
static ProfileLocation createWithLine() {
return XServiceProvider.profileLocationFactory().createWithLine();
return XBootstrapService.profileLocationFactory().createWithLine();
}
/**
* Create and return a new ProfileLocation with a given lineNumber and label.
*/
static ProfileLocation create(String label) {
return XServiceProvider.profileLocationFactory().create(label);
return XBootstrapService.profileLocationFactory().create(label);
}
/**
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,249 @@
package io.ebean;
/**
* Builder for ORM Query projection (the select and fetch part).
*
* @param <SELF> The builder type
* @param <T> The entity bean type
*/
public interface QueryBuilderProjection<SELF extends QueryBuilderProjection<SELF, T>, T> {
/**
* Apply the path properties replacing the select and fetch clauses.
* <p>
* This is typically used when the FetchPath is applied to both the query and the JSON output.
*/
SELF apply(FetchPath fetchPath);
/**
* Specify the properties to fetch on the root level entity bean in comma delimited format.
* <p>
* The Id property is automatically included in the properties to fetch unless setDistinct(true)
* is set on the query.
* </p>
* <p>
* Use {@link #fetch(String, String)} to specify specific properties to fetch
* on other non-root level paths of the object graph.
* </p>
* <pre>{@code
*
* List<Customer> customers = DB.find(Customer.class)
* // Only fetch the customer id, name and status.
* // This is described as a "Partial Object"
* .select("name, status")
* .where.ilike("name", "rob%")
* .findList();
*
* }</pre>
*
* @param fetchProperties the properties to fetch for this bean (* = all properties).
*/
SELF select(String fetchProperties);
/**
* Set DISTINCT ON clause. This is a Postgres only SQL feature.
*
* @param distinctOn The properties to include in the DISTINCT ON clause.
*/
SELF distinctOn(String distinctOn);
/**
* Apply the fetchGroup which defines what part of the object graph to load.
*/
SELF select(FetchGroup<T> fetchGroup);
/**
* Specify a path to fetch eagerly including specific properties.
* <p>
* Ebean will endeavour to fetch this path using a SQL join. If Ebean determines that it can
* not use a SQL join (due to maxRows or because it would result in a cartesian product) Ebean
* will automatically convert this fetch query into a "query join" - i.e. use fetchQuery().
* </p>
* <pre>{@code
*
* // query orders...
* List<Order> orders = DB.find(Order.class)
* // fetch the customer...
* // ... getting the customers name and phone number
* .fetch("customer", "name, phoneNumber")
*
* // ... also fetch the customers billing address (* = all properties)
* .fetch("customer.billingAddress", "*")
* .findList();
* }</pre>
* <p>
* If columns is null or "*" then all columns/properties for that path are fetched.
* </p>
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers = DB.find(Customer.class)
* .select("name, status")
* .fetch("contacts", "firstName,lastName,email")
* .findList();
*
* }</pre>
*
* @param path the property path we wish to fetch eagerly.
* @param fetchProperties properties of the associated bean that you want to include in the
* fetch (* means all properties, null also means all properties).
*/
SELF fetch(String path, String fetchProperties);
/**
* Fetch the path and properties using a "query join" (separate SQL query).
* <p>
* This is the same as:
* </p>
* <pre>{@code
*
* fetch(path, fetchProperties, FetchConfig.ofQuery())
*
* }</pre>
* <p>
* This would be used instead of a fetch() when we use a separate SQL query to fetch this
* part of the object graph rather than a SQL join.
* <p>
* We might typically get a performance benefit when the path to fetch is a OneToMany
* or ManyToMany, the 'width' of the 'root bean' is wide and the cardinality of the many
* is high.
*
* @param path the property path we wish to fetch eagerly.
* @param fetchProperties properties of the associated bean that you want to include in the
* fetch (* means all properties, null also means all properties).
*/
SELF fetchQuery(String path, String fetchProperties);
/**
* Fetch the path and properties using L2 bean cache.
*
* @param path The path of the beans we are fetching from L2 cache.
* @param fetchProperties The properties that should be loaded.
*/
SELF fetchCache(String path, String fetchProperties);
/**
* Fetch the path and properties lazily (via batch lazy loading).
* <p>
* This is the same as:
*
* <pre>{@code
*
* fetch(path, fetchProperties, FetchConfig.ofLazy())
*
* }</pre>
* <p>
* The reason for using fetchLazy() is to either:
* <ul>
* <li>Control/tune what is fetched as part of lazy loading</li>
* <li>Make use of the L2 cache, build this part of the graph from L2 cache</li>
* </ul>
*
* @param path the property path we wish to fetch lazily.
* @param fetchProperties properties of the associated bean that you want to include in the
* fetch (* means all properties, null also means all properties).
*/
SELF fetchLazy(String path, String fetchProperties);
/**
* Additionally specify a FetchConfig to use a separate query or lazy loading
* to load this path.
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers = DB.find(Customer.class)
* .select("name, status")
* .fetch("contacts", "firstName,lastName,email", FetchConfig.ofLazy(10))
* .findList();
*
* }</pre>
*
* @param path the property path we wish to fetch eagerly.
*/
SELF fetch(String path, String fetchProperties, FetchConfig fetchConfig);
/**
* Specify a path to fetch eagerly including all its properties.
* <p>
* Ebean will endeavour to fetch this path using a SQL join. If Ebean determines that it can
* not use a SQL join (due to maxRows or because it would result in a cartesian product) Ebean
* will automatically convert this fetch query into a "query join" - i.e. use fetchQuery().
* </p>
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers = DB.find(Customer.class)
* // eager fetch the contacts
* .fetch("contacts")
* .findList();
*
* }</pre>
*
* @param path the property path we wish to fetch eagerly.
*/
SELF fetch(String path);
/**
* Fetch the path eagerly using a "query join" (separate SQL query).
* <p>
* This is the same as:
* <pre>{@code
*
* fetch(path, FetchConfig.ofQuery())
*
* }</pre>
* <p>
* This would be used instead of a fetch() when we use a separate SQL query to fetch this
* part of the object graph rather than a SQL join.
* <p>
* We might typically get a performance benefit when the path to fetch is a OneToMany
* or ManyToMany, the 'width' of the 'root bean' is wide and the cardinality of the many
* is high.
*
* @param path the property path we wish to fetch eagerly
*/
SELF fetchQuery(String path);
/**
* Fetch the path eagerly using L2 cache.
*/
SELF fetchCache(String path);
/**
* Fetch the path lazily (via batch lazy loading).
* <p>
* This is the same as:
* </p>
* <pre>{@code
*
* fetch(path, FetchConfig.ofLazy())
*
* }</pre>
* <p>
* The reason for using fetchLazy() is to either:
* </p>
* <ul>
* <li>Control/tune what is fetched as part of lazy loading</li>
* <li>Make use of the L2 cache, build this part of the graph from L2 cache</li>
* </ul>
*
* @param path the property path we wish to fetch lazily.
*/
SELF fetchLazy(String path);
/**
* Additionally specify a JoinConfig to specify a "query join" and or define
* the lazy loading query.
* <pre>{@code
*
* // fetch customers (their id, name and status)
* List<Customer> customers = DB.find(Customer.class)
* // lazy fetch contacts with a batch size of 100
* .fetch("contacts", FetchConfig.ofLazy(100))
* .findList();
*
* }</pre>
*/
SELF fetch(String path, FetchConfig fetchConfig);
}
@@ -25,7 +25,7 @@ import java.util.Iterator;
*
* Query<Customer> query = database.find(Customer.class)
* .where().gt("id", 0)
* .order("id")
* .orderBy("id")
* .setMaxRows(2);
*
* QueryIterator<Customer> it = query.findIterate();
+1 -1
View File
@@ -111,7 +111,7 @@ package io.ebean;
* .fetch("order.customer", "name")
* .where().gt("order.id", 0)
* .having().gt("totalAmount", 20)
* .order().desc("totalAmount")
* .orderBy().desc("totalAmount")
* .setMaxRows(10)
* .findList();
*

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