> This is part 1 of 2 of the full documentation (pages 1–100 of 133).
> The content is paginated: fetch every part to see all of it.
> Next part: https://bxorm.ortusbooks.com/llms-full.txt/1
> Page index: https://bxorm.ortusbooks.com/llms.txt

> Agents can also search and read this documentation through its [MCP server](https://bxorm.ortusbooks.com/~gitbook/mcp).

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://bxorm.ortusbooks.com/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Introduction

The BoxLang ORM module allows your BoxLang application to integrate with the powerful Hibernate ORM

## BoxLang ORM

<figure><img src="https://146896706-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FpE0DivA4DpsOBQKEddvG%2Fuploads%2FcArI2SX7S5ko1idiZB6B%2Fbxorm-wide.jpg?alt=media&amp;token=d01db12c-a27c-430e-a9a0-3f1125782fa8" alt=""><figcaption></figcaption></figure>

The [BoxLang ORM module](https://github.com/ortus-boxlang/bx-orm) allows your BoxLang\
application to integrate with the powerful [Hibernate ORM](https://hibernate.org/orm/). With Hibernate, you can interact with your database records in an object oriented fashion, using a BoxLang class to denote each record and simple getters and setters for each field value:

```js
class entityName="Auto" persistent="true" {

	property name="id" type="string" fieldtype="id" ormtype="string";
	property name="make" type="string";
	property name="model" type="string";

    function onPreInsert(){
        log.info( "Inserting new Auto: #getMake()# #getModel()#" );
    }
}
```

BoxLang ORM also enables transactional persistence, where an error during a save will roll back the entire transaction to prevent leaving the database in a broken state:

```js
transaction{
    try{
        entitySave(
            entityNew( "Purchase", {
                productID : "123-expensive-watch",
                purchaseTime : now(),
                customerID : customer.getId()
            })
        );
        var cartProducts = entityLoad( "CartProduct", customer.getID() );
        entityDelete( cartProducts );
    } catch ( any e ){
        // don't clear the user's cart if the purchase failed
        transactionRollback();
        rethrow;
    }
}
```

### Hibernate Version Support

bx-orm bundles Hibernate `5.6.15.FINAL`.

### Open Source Product

bx-orm is an open source BoxLang module with no license purchase necessary. If you are looking to further the development of this extension, consider [sponsoring a feature or opening a support contract](#support).

### Features In A Nutshell

* Add Object Relational Mapping to any boxlang app with Hibernate ORM
* Use native built-in-functions (BIFs) to update and persist entities to the database (`entityNew()`, `entitySave()`, `ormFlush()`, etc.)
* Supports 80+ database dialects, from `SQLServer2005` to `MySQL8` and `PostgreSQL`
* Generate your mapping XML once and never again with the `autoGenMap=false` ORM configuration setting
* React to entity changes with pre and post event listeners such as `onPreInsert()`, `onPreUpdate()` and `onPreDelete()`
* Over 20 native BIFs:
  * `EntityDelete()`
  * `EntityLoad()`
  * `EntityLoadByExample()`
  * `EntityLoadByPK()`
  * `EntityMerge()`
  * `EntityNameArray()`
  * `EntityNameList()`
  * `EntityNew()`
  * `EntityReload()`
  * `EntitySave()`
  * `EntityToQuery()`
  * `ORMClearSession()`
  * `ORMCloseAllSessions()`
  * `ORMEvictCollection()`
  * `ORMEvictEntity()`
  * `ORMEvictQueries()`
  * `ORMExecuteQuery()`
  * `ORMFlush()`
  * `ORMGetSession()`
  * `ORMGetSessionFactory()`
  * `ORMReload()`

### Support

By launching [BoxLang](https://boxlang.io/) we are able to give back to the community, as well as offer premium support to enterprises looking for a level up in their Hibernate implementations. If you need performance optimization, session management or caching integrations, please [contact us for support](https://ortussolutions.atlassian.net/servicedesk/customer/portal/9).

* Source Code: [github.com/ortus-boxlang/bx-orm](https://github.com/ortus-boxlang/bx-orm)
* Support Plans: <https://www.ortussolutions.com/services/support>
* Bug Tracker: <https://ortussolutions.atlassian.net/browse/BLMODULES>


# About This Book

More info on this documentation gitbook for bx-orm

The source code for this book is hosted in GitHub:

{% @github-files/github-code-block url="<https://github.com/ortus-docs/bxorm>" %}

You can freely contribute to it and submit pull requests. The contents of this book is copyright by [Ortus Solutions, Corp](https://www.ortussolutions.com/) and cannot be altered or reproduced without author's consent. All content is provided *"As-Is"* and can be freely distributed.

* The majority of code examples in this book are done in `cfscript`.
* The majority of code generation and running of examples are done via **CommandBox**: The ColdFusion (CFML) CLI, Package Manager, REPL - <https://www.ortussolutions.com/products/commandbox>​

## Notice of Liability <a href="#notice-of-liability" id="notice-of-liability"></a>

The information in this book is distributed “as is”, without warranty. The author and Ortus Solutions, Corp shall not have any liability to any person or entity with respect to loss or damage caused or alleged to be caused directly or indirectly by the content of this training book, software and resources described in it.

## Contributing <a href="#contributing" id="contributing"></a>

We highly encourage contribution to this book and our open source software. The source code for this book can be found in our [GitHub repository](https://github.com/ortus-docs/bxorm) where you can submit pull requests.

## Charitable Proceeds <a href="#charitable-proceeds" id="charitable-proceeds"></a>

10% of the proceeds of this book will go to charity to support orphaned kids in El Salvador - [https://www.harvesting.org/](https://www.harvesting.org). So please donate and purchase the printed version of this book, every book sold can help a child for almost 2 months.

### Shalom Children's Home <a href="#shalom-childrens-home" id="shalom-childrens-home"></a>

{% embed url="<https://harvesting.org>" %}
[www.harvesting.org](http://www.harvesting.org)
{% endembed %}

**Shalom Children’s Home** is one of the ministries that is dear to our hearts located in El Salvador. During the 12 year civil war that ended in 1990, many children were left orphaned or abandoned by parents who fled El Salvador. The Benners saw the need to help these children and received 13 children in 1982. Little by little, more children came on their own, churches and the government brought children to them for care, and the Shalom Children’s Home was founded.

Shalom now cares for over 80 children in El Salvador, from newborns to 18 years old. They receive shelter, clothing, food, medical care, education and life skills training in a Christian environment. The home is supported by a child sponsorship program.

We have personally supported Shalom for over 6 years now; it is a place of blessing for many children in El Salvador that either have no families or have been abandoned. This is good earth to seed and plant.


# Release History

Release history for all bx-orm versions

In this section, you will find the release notes for each version we release under this major version. If you are looking for the release notes of previous major versions, use the version switcher at the top left of this documentation book. Here is a breakdown of our major version releases.

## v1.x

Check out our [1.x release notes](https://bxorm.ortusbooks.com/release-history/1x) for the latest updates and changes.

New in the latest release: [What's New in 1.7.3](https://bxorm.ortusbooks.com/release-history/whats-new-1.7.3).


# What's New in 1.7.3

What's new in bx-orm 1.7.3, HQL through the query component and typed values from forms and URLs

bx-orm 1.7.3 is a fix release for the 1.x line (Hibernate 5). It lets the query component and `queryExecute()` run HQL, and stops typed properties from failing when their value arrives as a string, such as an id from a form or a URL. There are no breaking changes. Update the module and your code keeps working.

```bash
box install bx-orm@1.7.3
```

## HQL in the Query Component and queryExecute()

[BLMODULES-306](https://ortussolutions.atlassian.net/browse/BLMODULES-306)

`<bx:query>` (`<cfquery>` in CFML templates) and `queryExecute()` now run HQL when you set `dbtype="hql"`. They return the same result as [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery): an array of entities, or an array of rows for a projection. Before 1.7.3 the `dbtype` was ignored, so the HQL ran as SQL against the default datasource and returned a query or a SQL error.

```html
<bx:query name="toyotas" dbtype="hql">
    FROM Auto WHERE make = <bx:queryparam value="#form.make#" sqltype="varchar">
</bx:query>
```

```js
var toyotas = queryExecute(
    "FROM Auto WHERE make = :make",
    { make: "Toyota" },
    { dbtype: "hql" }
);
```

* `<bx:queryparam>` (`<cfqueryparam>`) in the body binds a positional parameter. With a `sqltype` (`cfsqltype`) the value is cast first, and `list="true"` binds a list for `IN ( ... )`.
* `params` binds named (struct) or positional (array) parameters, as in `ORMExecuteQuery()`.
* `ormoptions` takes the `ORMExecuteQuery()` [options](https://bxorm.ortusbooks.com/usage/querying#options), such as `maxResults`, `offset`, `readOnly` and `unique`. `maxrows`, `timeout` and `datasource` apply too.
* `result` gets a struct with `sql` (the HQL), `recordCount`, `executionTime` and `cached`.

Without `dbtype="hql"`, both run SQL exactly as before. See [HQL in the Query Component](https://bxorm.ortusbooks.com/usage/querying#hql-in-the-query-component-and-queryexecute).

## Typed Values from Forms and URLs

[BLMODULES-307](https://ortussolutions.atlassian.net/browse/BLMODULES-307)

Form and URL values are always strings, and BoxLang arithmetic produces decimals. Before 1.7.3, binding one of them to a typed property failed, because Hibernate 5 binds values as they are:

```
class java.lang.String cannot be cast to class java.lang.Integer
```

bx-orm now converts each value to the property's mapped type before Hibernate binds it, so this code works:

```js
// A string id from the URL
var user = entityLoad( "User", { id: url.id }, true );

// Named, positional and list parameters
var users  = ormExecuteQuery( "FROM User WHERE id = :id", { id: url.id } );
var admins = ormExecuteQuery( "FROM User WHERE id IN (:ids)", { ids: listToArray( form.ids ) } );
```

```html
<!--- An untyped queryparam in an HQL query --->
<bx:query name="user" dbtype="hql">
    FROM User WHERE id = <bx:queryparam value="#url.id#">
</bx:query>
```

The conversion covers `entityLoad()` filters and every HQL parameter: `ORMExecuteQuery()`, `dbtype="hql"` queries, untyped `<bx:queryparam>` and list parameters.

| Property type                                            | Accepted values                                                                     |
| -------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| Whole numbers (`integer`, `long`, `short`, `biginteger`) | Numbers and numeric strings with no fractional part: `"1"`, `" 1 "`, `"1.0"`, `1.0` |
| Decimals (`double`, `float`, `bigdecimal`)               | Numbers and numeric strings: `"2.5"`                                                |
| `boolean`                                                | Booleans, numbers and boolean strings: `"true"`, `"yes"`, `0`                       |
| `string`                                                 | Numbers and booleans                                                                |

A value that does not fit the type is passed to Hibernate unchanged and fails as before. For example, `"1.5"` is never truncated to `1` for an integer property, and `"abc"` still fails. `entityLoadByPK()` and a `<bx:queryparam>` with a `sqltype` already converted their values and work as before.

## Also in 1.7

If you are coming from an earlier 1.x release, these arrived earlier in the 1.7 line:

* **1.7.2**:
  * value collections with `fieldtype="collection"` (arrays and structs of simple values in their own table);
  * ORM observability events (`onORMQuery`, `onORMFlush`, `onORMException`) and Hibernate statistics. See [Observability](https://bxorm.ortusbooks.com/usage/observability).
* **1.7.1**: `entityToQuery()` no longer adds always-`null` columns for relationship properties. See [Entities as Queries](https://bxorm.ortusbooks.com/usage/queries).
* **1.7.0**:
  * [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached);
  * raw Hibernate properties through `hibernateProperties` and `ormConfig`. See [Custom Hibernate Config](https://bxorm.ortusbooks.com/getting-started/configuration/custom-hibernate-config);
  * SQLite support;
  * the `uuid2` generator.

The full list is in the [1.x release notes](https://bxorm.ortusbooks.com/release-history/1x).


# 1.x

Version 1.x release notes for the BoxLang ORM Module

## 1.7.3 - 2026-11-04

See [What's New in 1.7.3](https://bxorm.ortusbooks.com/release-history/whats-new-1.7.3) for a tour of this release.

### 🐛 Fixed

* [BLMODULES-306](https://ortussolutions.atlassian.net/browse/BLMODULES-306) `<cfquery dbtype="hql">` / `<bx:query dbtype="hql">` and `queryExecute( hql, params, { dbtype : "hql" } )` run HQL and return the same array as `ormExecuteQuery()`. Before, `dbtype` was ignored and the HQL ran as SQL, returning a query. `<cfqueryparam>` binds positional parameters (cast to its `cfsqltype`), and `ormoptions`, `maxrows`, `timeout`, `datasource` and `result` apply. See [HQL in the Query Component](https://bxorm.ortusbooks.com/usage/querying#hql-in-the-query-component-and-queryexecute).
* [BLMODULES-307](https://ortussolutions.atlassian.net/browse/BLMODULES-307) A string or decimal value for a typed property no longer fails with `String cannot be cast to Integer`. `entityLoad()` filters and HQL parameters (`ormExecuteQuery()`, `dbtype="hql"` queries, untyped `<cfqueryparam>`, list parameters) convert the value to the property's type, so a form or URL id such as `"1"` works. Integer types only take whole numbers, and a value that cannot be converted is passed to Hibernate unchanged. See [Typed Values from Forms and URLs](https://bxorm.ortusbooks.com/release-history/whats-new-1.7.3#typed-values-from-forms-and-urls).

See [v1.7.3 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.7.2...v1.7.3)

## 1.7.2 - 2026-10-20

### ⭐ Added

* [BL-2751](https://ortussolutions.atlassian.net/browse/BL-2751) - `fieldtype="collection"` is now supported: a `type="array"` property becomes a Hibernate `<bag>` and a `type="struct"` property a `<map>` of simple values stored in their own table (`table`, `fkcolumn`, `elementcolumn`, `elementtype`, plus `structkeycolumn`/`structkeytype` for maps, `orderby`, `lazy`, `batchsize`). Previously the property was dropped from the mapping with only a warning in `orm.log`. A collection without `elementcolumn` or `fkcolumn` now fails at mapping time instead of being ignored. The generated `hasX( value )`, `addX( value )` and `removeX( value )` helpers accept the scalar values of such a collection, and `fieldtype` is matched case-insensitively. Writing a BoxLang struct to a map collection no longer fails with a `ClassCastException`.
* ORM observability events: `onORMQuery` is announced after each JDBC statement, `onORMFlush` reports insert, update and delete counts per flush, and `onORMException` reports failures. Nothing is built when there are no listeners. See [Observability](https://bxorm.ortusbooks.com/usage/observability).
* `announceQueryParams` ORM setting (default `false`) to include bound parameter values in `onORMQuery`.
* `generateStatistics` ORM setting (default `false`), plus `ORMService.getStatistics( appName )` and `ORMService.setStatisticsEnabled( appName, enabled )` for a plain-struct view of Hibernate statistics.

### ⚡ Changed

* `ORMPreConfigLoad` and `ORMPostConfigLoad` are now registered as interception points.

### 🐛 Fixed

* [BL-2739](https://ortussolutions.atlassian.net/browse/BL-2739) - `generator="identity"` no longer fails on PostgreSQL when `dialect` is set explicitly and the table name is a reserved word (`comment`, `collection`, `release`, `synonym`, `user`, ...). An explicit PostgreSQL dialect now tells Hibernate the driver returns generated keys, as auto-detection already did. Set `hibernate.jdbc.use_get_generated_keys` in `hibernateProperties` to override it.

See [v1.7.2 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.7.1...v1.7.2)

## 1.7.1 - 2026-10-07

### 🐛 Fixed

* `entityToQuery()` no longer adds columns for relationship properties (`one-to-one`, `one-to-many`, `many-to-one`, `many-to-many`). They were always `null`. The query now holds no relation data, matching Adobe ColdFusion and Lucee. Code reading those columns must be updated. See [Entities as Queries](https://bxorm.ortusbooks.com/usage/queries).

See [v1.7.1 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.7.0...v1.7.1)

## 1.7.0 - 2026-09-14

### ⭐ Added

* [BLMODULES-287](https://ortussolutions.atlassian.net/browse/BLMODULES-287) - Added `entityIsAttached()` to check whether an entity is attached to the ORM session for its datasource.
* New `ormSettings.hibernateProperties` setting: a flat struct of raw Hibernate property name/value pairs applied directly to the Hibernate `Configuration`, letting applications tune settings like `hibernate.connection.release_mode` without a custom Hibernate config file.
* Implemented the previously-unused `ormSettings.ormConfig` setting as a path to a `hibernate.properties`-formatted file, applied the same way as `hibernateProperties` (a conflicting key in `hibernateProperties` takes precedence). The `hibernate.cfg.xml` file format is not yet supported.
* Added SQLite dialect support. `ormSettings.dialect = "SQLite"` now resolves to `org.sqlite.hibernate.dialect.SQLiteDialect`, provided by the new `com.github.gwenn:sqlite-dialect` dependency (`org.hibernate:hibernate-community-dialects`, which houses the official SQLite dialect, is only published for Hibernate 6+ and is not available while this module is pinned to Hibernate 5).
* SQLite dialect resolution now uses JDBC metadata automatically when no explicit dialect is configured.

### 🐛 Fixed

* [BLMODULES-288](https://ortussolutions.atlassian.net/browse/BLMODULES-288) - Fixed support for Hibernate's built-in `uuid2` ORM generator.

See [v1.7.0 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.6.7...v1.7.0)

## 1.6.7 - 2026-08-13

### 🐛 Fixed

* [BL-2612](https://ortussolutions.atlassian.net/browse/BL-2612) - `entityToQuery()` now includes inherited persistent properties (e.g., from a persistent parent entity) in query columns. Property collections internally use `LinkedHashSet` to prevent duplicate properties across the inheritance chain.
* Updated CI `GRADLE_VERSION` to `9.6.1` to match the Gradle wrapper and fix `NoSuchMethodError` with Shadow plugin 9.6.1
* Normalized ORM field generator values to be case-insensitive for built-in generators (including `uuid`) so mixed-case declarations are handled correctly.
* Custom generator values (non-built-in) are now validated against the classpath at mapping time; an invalid generator name throws a descriptive `BoxRuntimeException` listing valid built-in generators.

See [v1.6.7 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.6.6...v1.6.7)

## 1.6.6 - 2026-07-22

### ⚡ Updates

* Toned down logging on the `ORMConnectionProvider` to avoid noisy logs on every connection acquisition.
* Dropped "No ORM application found" logs when ORM is disabled.

See [v1.6.6 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.6.5...v1.6.6)

## 1.6.5 - 2026-05-26

### ⭐ Added

* New AI skills under `.agents/skills` and custom skills under `.agents/skills-custom`
* New Custom Skills for AI agents under `.agents/skills-custom` for ORM configuration and troubleshooting.
* Consolidation of AI instruction files to `AGENTS.md` with a pointer from `CLAUDE.md`

### ⚡ Updates

* Updated readme with AI skills information and setup.
* Dependabot quarterly
* Updated BoxLang testing to v1.13.0

### 🐛 Fixed

* Fix `ClassCastException` when saving entities with `ormtype="float"` properties containing Integer values (e.g., `default="0"`). Added missing `FloatConverter` and registered it in `HibernateXMLWriter`.

See [v1.6.5 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.6.4...v1.6.5)

## 1.6.4 - 2026-05-13

### ⭐ Added

* Added debug logging for ORM startup metrics, including entity metadata parsing and Hibernate SessionFactory build times.

### 🐛 Fixed

* [BLMODULES-191](https://ortussolutions.atlassian.net/browse/BLMODULES-191) - Defensive code against disabled ORM logging causing boxlang cli startup failure.
* [BLMODULES-198](https://ortussolutions.atlassian.net/browse/BLMODULES-198) - Fix `missingRowIgnored` annotation not being applied to collection relationships.
* [BLMODULES-204](https://ortussolutions.atlassian.net/browse/BLMODULES-204) - Ensure transaction open only flushes session if `autoManageSession` is enabled.

See [v1.6.4 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.6.3...v1.6.4)

## 1.6.3 - 2026-04-29

### 🐛 Fixed

* [BLMODULES-190](https://ortussolutions.atlassian.net/browse/BLMODULES-190) - Fix error on `one-to-many` associations when `inversejoincolumn` attribute is specified

See [v1.6.3 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.6.2...v1.6.3)

## 1.6.2 - 2026-04-09

### 🐛 Fixed

* [BLMODULES-173](https://ortussolutions.atlassian.net/browse/BLMODULES-173) - Fixed issue with mutated entity metadata leaking across BoxLang applications.

See [v1.6.2 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.6.1...v1.6.2)

## 1.6.1 - 2026-04-09

### 🐛 Fixed

* Fixed issue with `scale` annotation not properly cast to a string in `ClassicPropertyMeta`.
*

See [v1.6.1 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.6.0...v1.6.1)

## 1.6.0 - 2026-04-02

### ⭐ Added

* Adds support for composite IDs.

### 🐛 Fixed

* Fixes an issue of lost mappings on entity discoveries, due to wrong parent context being sent.

See [v1.6.0 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.5.0...v1.6.0)

## 1.5.0 - 2026-03-27

### 🐛 Fixed

* **Memory leak on ORM reload** — all open Hibernate sessions are now closed before tearing down `SessionFactory` instances, preventing stale session/factory references from blocking garbage collection after every `ORMReload()`.
* **Memory leak on session factory build failure** — `SessionFactoryBuilder` now wipes the `BootstrapServiceRegistry` when `buildSessionFactory()` throws, so the registry is not orphaned on the failure path.
* **Stale ORM context after reload** — the old `ORMContext` is removed from the JDBC context before rebuilding, and a fresh one is eagerly installed after the new app is live, eliminating null-window races for concurrent callers.
* **Null context in threaded scenarios** — `EntityTuplizer` and related components now obtain the box context safely when executing in a non-request thread.
* **Null pointer when the method does not exist on a tuplizer call** — added an existence check before invoking optional methods.
* Improved exception logging to include full stack traces throughout the ORM lifecycle.
* Fixed issue with `dbdefault` annotation not properly cast to a string in `ClassicPropertyMeta`.

### ⭐ Added

* Use a deterministic directory name based on config content rather than a hashcode of the config file path for generated mapping files, ensuring consistent mapping file usage across different environments and absolute paths.

### ⚡ Changed

* **Hot-path interception performance** — all `interceptorService.announce()` calls on hot code paths (entity instantiation, config load) are now guarded with `hasState()` checks and use lazy `Struct` suppliers, avoiding unnecessary struct allocation when no listeners are registered.
* `ORMConfig` now receives and threads the `IBoxContext` through `process()` and `getAppDefaultDatasource()` so the correct application datasource is resolved in all execution contexts.
* `ORMService.reloadApp()` now performs an atomic put-and-swap of the new/old `ORMApp` in the registry to minimize the disruption window for requests running concurrently with a reload.

See [v1.5.0 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.4.1...v1.5.0)

## 1.4.1 - 2026-03-23

### ⛓️‍💥 Changed

* This version requires Boxlang Runtime `v1.11.x` and above

### 🗑 Deprecated

* The `autoGenMap` configuration setting is now deprecated in favor of `generateMappings`. Same function, different name. See [BLMODULES-119](https://ortussolutions.atlassian.net/browse/BLMODULES-119) for details.

### ⭐ Added

* [BLMODULES-119](https://ortussolutions.atlassian.net/browse/BLMODULES-119) - Add support for `generateMappings=false` (aliased as `autoGenMap` for backwards compatibility) to disable automatic mapping generation and require manual mapping files.

### 🐛 Fixed

* [BLMODULES-136](https://ortussolutions.atlassian.net/browse/BLMODULES-136) - Fix issue with naming strategy being double-applied on table and column identifiers.
* [BLMODULES-146](https://ortussolutions.atlassian.net/browse/BLMODULES-146) - Fix issue where rollbacks, commits, etc. inside a transaction block were not properly scoped to the transaction block and could affect the entire session.

See [v1.4.1 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.4.0...v1.4.1)

## 1.4.0 - 2026-02-06

### ⛓️‍💥 Changed

* This version requires Boxlang Runtime `v1.11.x` and above

### 🐛 Fixed

* [BLMODULES-120](https://ortussolutions.atlassian.net/browse/BLMODULES-120) - Add new settings for `lazy` and `defaultBatchSize` to provide compat implementations
* [BLMODULES-130](https://ortussolutions.atlassian.net/browse/BLMODULES-130) - Fix collection handling for java List objects - which hibernate returns
* Transaction management udpates to deal with complex nested transactions
* Ensure manual flush mode when `autoManageSession` is `false`
* Add savepoint interception for nested transactions and flush

See [v1.4.0 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.3.0...v1.4.0)

## 1.3.0 - 2026-01-07

### 🐛 Fixed

* [BLMODULES-110](https://ortussolutions.atlassian.net/browse/BLMODULES-110) - Implement `EntityTuplizer.getEntityMode()` for relationship getters
* [BLMODULES-113](https://ortussolutions.atlassian.net/browse/BLMODULES-113) - Drop unnecessary logging on request end for non-ORM requests
* [BLMODULES-117](https://ortussolutions.atlassian.net/browse/BLMODULES-117) - Resolve transaction interception error when no ORM App is present
* [BL-2039](https://ortussolutions.atlassian.net/browse/BL-2039) - Fix "Datasource with name ... not found" in empty transactions on subsequent requests

### ⭐ Added

* [BLMODULES-118](https://ortussolutions.atlassian.net/browse/BLMODULES-118) - Enable `table`, `schema`, and `catalog` annotations for joined subclasses.
* [BL-2052](https://ortussolutions.atlassian.net/browse/BL-2052) - Move ORM context removal to shutdown listener for improved datasource cleanup on request end.

See [v1.3.0 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.2.0...v1.3.0)

## 1.2.0 - 2025-12-05

### 🐛 Fixed

* [BLMODULES-102](https://ortussolutions.atlassian.net/browse/BLMODULES-102) - Fix ORM usage in threads causing ConcurrentModificationException
* [BLMODULES-109](https://ortussolutions.atlassian.net/browse/BLMODULES-109) - Fix queries on null relationships.

See [v1.2.0 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.1.3...v1.2.0)

## 1.1.3 - 2025-11-04

### 🐛 Fixed

* [BLMODULES-94](https://ortussolutions.atlassian.net/browse/BLMODULES-94) - Fix incorrect casting in Getter
* [BLMODULES-96](https://ortussolutions.atlassian.net/browse/BLMODULES-96) - Fix ORMExecute query handling of WHERE clauses with object params
* [BLMODULES-101](https://ortussolutions.atlassian.net/browse/BLMODULES-101) - Fix NPE due to null oldState in PreUpdate event listener

See [v1.1.3 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.1.2...v1.1.3)

## 1.1.2 - 2025-09-06

### 🐛Fixed

* [BLMODULES-84](https://ortussolutions.atlassian.net/browse/BLMODULES-84) - Resolved incorrect location of many-to-one on discriminated child
* [BLMODULES-85](https://ortussolutions.atlassian.net/browse/BLMODULES-85) - Resolved an issue where transaction interception points would throw an error on non-orm-enabled applications
* [BLMODULES-88](https://ortussolutions.atlassian.net/browse/BLMODULES-88) - Resolved an issue where entity modifications during orm events were not persisting correctly to the database
* [BLMODULES-90](https://ortussolutions.atlassian.net/browse/BLMODULES-90) - Resolved an issue where numerics were not being coerced correctly to strings on applicable properties when used in ORMExecuteQuery

See [v1.1.2 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.1.1...v1.1.2)

## 1.1.1 - 2025-08-27

### 🐛 Fixed

* Changed Array.fromString usage to use ListUtil as the method was removed from the Array class in v1.5.0 of the core
* [BLMODULES-83](https://ortussolutions.atlassian.net/browse/BLMODULES-83) - Resolved inheritiance and `mappedSuperClass` issues with 3+ levels
* [BLMODULES-80](https://ortussolutions.atlassian.net/browse/BLMODULES-80) - Fix for class relationships not being found due to core compiler casing changes

See [v1.1.1 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.1.0...v1.1.1).

## 1.1.0 - 2025-08-04

### ⛓️‍💥 Changed

* This new version only works with the fixes on [BoxLang v1.4.0](https://boxlang.ortusbooks.com/readme/release-history/1.4.0)

### 🐛 Fixed

* Updates to Request Context based on BoxLang v1.4.0 updates
* Lots of dependency updates

See [v1.1.0 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.11...v1.1.0).

## 1.0.11 - 2025-06-10

### 🐛 Fixed

* Fixed issue with default cache not being created when cache provider was empty - Resolves [BLMODULES-53](https://ortussolutions.atlassian.net/browse/BLMODULES-53)
* Fix error starting up on non-ORM apps - Resolves [BLMODULES-49](https://ortussolutions.atlassian.net/browse/BLMODULES-49)
* Add support for `tinyint` and `tinyinteger` ORM types - Resolves [BLMODULES-59](https://ortussolutions.atlassian.net/browse/BLMODULES-59)
* Skip type conversion on version properties - Resolves [BLMODULES-45](https://ortussolutions.atlassian.net/browse/BLMODULES-45)
* Drop ormApp instantiation in baseORMBIF - Fixes [BLMODULES-54](https://ortussolutions.atlassian.net/browse/BLMODULES-54)
* Improve default datasource look up and throw error if empty - See [BLMODULES-56](https://ortussolutions.atlassian.net/browse/BLMODULES-56)

See [v1.0.11 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.10...v1.0.11).

## 1.0.10 - 2025-05-03

### 🐛 Fixed

* Throw or log an error when class annotation on association is an empty string - Resolves [BLMODULES-50](https://ortussolutions.atlassian.net/browse/BLMODULES-50)
* Fix support for `dataType` annotation on version properties - Resolves [BLMODULES-51](https://ortussolutions.atlassian.net/browse/BLMODULES-51)

### ⭐ Added

* Implement 'index' annotation - Resolves [BLMODULES-47](https://ortussolutions.atlassian.net/browse/BLMODULES-47)
* Implement multi-column support in `column` and `fkcolumn` - Resolves [BLMODULES-48](https://ortussolutions.atlassian.net/browse/BLMODULES-48)
* Implement cache support at the property level - Resolves [BLMODULES-52](https://ortussolutions.atlassian.net/browse/BLMODULES-52)

See [v1.0.10 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.9...v1.0.10).

## 1.0.9 - 2025-04-29

### 🐛 Fixed

* Implement `elementType`,`elementColumn` annotations - Resolves [BLMODULES-46](https://ortussolutions.atlassian.net/browse/BLMODULES-46)
* Fixes for map collection when `structkeytype` or `structkeycolumn` are ignored - Resolves [BLMODULES-45](https://ortussolutions.atlassian.net/browse/BLMODULES-45)
* Skip usage of `AttributeConverter` on identifier properties - Resolves [BLMODULES-44](https://ortussolutions.atlassian.net/browse/BLMODULES-44)

See [v1.0.9 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.8...v1.0.9).

## 1.0.8 - 2025-04-25

### ⭐ Added

* Set hibernate version in build so `ORMGetHibernateVersion()` stays accurate - See [a8c7c16](https://github.com/ortus-boxlang/bx-orm/commit/a8c7c16d8b3ee766ab182aad490909a5509f10e4)

### 🐛 Fixed

* Foreign key must have same number of columns as the referenced primary key - Resolves [BLMODULES-41](https://ortussolutions.atlassian.net/browse/BLMODULES-41)
* Missing FKColumn on To-Many Relationship Should Check the Inverse Relationship for Column data - Resolves [BLMODULES-42](https://ortussolutions.atlassian.net/browse/BLMODULES-42)
* XMLWriter - Skip id,composite-id XML rendering on subclasses - Resolves [BLMODULES-38](https://ortussolutions.atlassian.net/browse/BLMODULES-38)
* XML Writer - Skip generator on composite keys - Resolves [BLMODULES-40](https://ortussolutions.atlassian.net/browse/BLMODULES-40)
* XMLWriter - Don't set insert or update on one-to-one elements - Resolves [BLMODULES-39](https://ortussolutions.atlassian.net/browse/BLMODULES-39)
* Fix support for 'params' attribute string notation - See [BLMODULES-40](https://ortussolutions.atlassian.net/browse/BLMODULES-40)

See [v1.0.8 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.7...v1.0.8).

## 1.0.7 - 2025-04-14

### 🐛 Fixed

* Fix string casting error on `lazy` property annotation

See [v1.0.7 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.6...v1.0.7).

## 1.0.6 - 2025-04-14

### 🐛 Fixed

* Fixed support for custom naming strategies - See [8e68206](https://github.com/ortus-boxlang/bx-orm/commit/8e68206e3d3f197a69fc12467c42c7c5de1c7eac)
* Fixed "smart" naming strategy when entity name begins with an uppercase character - See [b47b512](https://github.com/ortus-boxlang/bx-orm/commit/b47b51239a15530df245c5e12c36c48e10b09266)
* Move compat configuration to bx-compat-cfml - See [c8b7173](https://github.com/ortus-boxlang/bx-orm/commit/c8b7173f1c0fc01646d3b3d980d9d889ab8c7686)
* Fixed the two types of discriminator generation order - See [ea62a62](https://github.com/ortus-boxlang/bx-orm/commit/ea62a62fe1f4fe66bce58b4e27659b60faccb1aa)
* fix bag element being appended to wrong node on subclasses - See [f82b2ac](https://github.com/ortus-boxlang/bx-orm/commit/f82b2ac24e5d9cf1f43da5a8437c481be5e4f0c5)
* change to use caster so that lazy=true does not error - See [0096387](https://github.com/ortus-boxlang/bx-orm/commit/00963873c44480e6597ac0e3962d66244c42c865)

### ⭐ Added

* Add missing `date` property type - See [c6ec8a2](https://github.com/ortus-boxlang/bx-orm/commit/c6ec8a2e2dadfb344deb93edb7a1a2ccf8d0fb46)
* Add alternate spellings for big decimal and big integer - See [5e199f9](https://github.com/ortus-boxlang/bx-orm/commit/5e199f9e5674c3a3802a5e225d45f187b0724e23)
* Add flush after commit on transaction end - See [e2df378](https://github.com/ortus-boxlang/bx-orm/commit/e2df378c261a2c0aea99749d7bf04cd688d57658)

See [v1.0.6 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.5...v1.0.6).

## 1.0.5 - 2025-04-07

### 🐛 Fixed

* Removed debugging code

See [v1.0.5 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.4...v1.0.5).

## 1.0.4 - 2025-04-06

### 🐛 Fixed

* Metadata parsing throws error on empty class despite `skipCFCWithError` setting - Resolves [BLMODULES-37](https://ortussolutions.atlassian.net/browse/BLMODULES-37)

See [v1.0.4 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.3...v1.0.4).

## 1.0.3 - 2025-04-06

### 🐛 Fixed

* EntityLoad returning incorrect results with criteria struct filter on parent properties - Resolves [BLMODULES-36](https://ortussolutions.atlassian.net/browse/BLMODULES-36)
* Hibernate Criteria Querys using `get` are returning proxies instead of the entity - Resolves [BLMODULES-35](https://ortussolutions.atlassian.net/browse/BLMODULES-35)
* ensure proxies in session are expanded when a load is requested - See [5b07e2c](https://github.com/ortus-boxlang/bx-orm/commit/5b07e2c1f0bf2bb4f3cb3c5fd15f15cee9bfd01d)
* Error on first ORM request after Application Timeout - Resolves [BLMODULES-30](https://ortussolutions.atlassian.net/browse/BLMODULES-30)
* BoxProxy Struct Implementation causes validation exceptions - Resolves [BLMODULES-33](https://ortussolutions.atlassian.net/browse/BLMODULES-33)

See [v1.0.3 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.2...v1.0.3).

## 1.0.2 - 2025-04-04

No significant changes.

See [v1.0.2 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.1...v1.0.2).

## 1.0.1 - 2025-04-04

### ⭐ Added

* Allow options as third arg to ORMExecuteQuery - See [b5efc84](https://github.com/ortus-boxlang/bx-orm/commit/b5efc840df6ddc96e87dd2d18b1bd3acd4de6002)
* Add handling for not null on to-one relationship - See [6792fb0](https://github.com/ortus-boxlang/bx-orm/commit/6792fb0e81a11105ce056803f2b28b873546ec02)

### 🐛 Fixed

* Attempt casting `uniqueOrOrder` to string in EntityLoad BIF - See [98f6734](https://github.com/ortus-boxlang/bx-orm/commit/98f67344e0df0d808f6bb749b4ae20b2cc8c9734)
* Ignore null `uniqueOrOrder` argument in EntityLoad BIF - See [394d9ba](https://github.com/ortus-boxlang/bx-orm/commit/394d9ba907a016103949da5a5d157ffb14672d61)
* Fix chicken/egg issues with app startup by lazy-initializing the EventHandler - See [699f15b](https://github.com/ortus-boxlang/bx-orm/commit/699f15b8c82704f8e101d1d1ee38be541e5ae618)
* WrongClassException when re-querying for the same object in a session - Resolves [BLMODULES-12](https://ortussolutions.atlassian.net/browse/BLMODULES-12)
* Disable `not-null` annotation usage on one-to-one relationships - See [c512848](https://github.com/ortus-boxlang/bx-orm/commit/c512848bba331c6282a5a5c5c2b99271b3f28863)
* fix explicit nulls on setters - See [819fffb](https://github.com/ortus-boxlang/bx-orm/commit/819fffbe58fb576e630f29d001aec5a38d8bf1b4)
* Auto-generated `has` methods are overriding declared methods in ORM entities - Resolves [BLMODULES-31](https://ortussolutions.atlassian.net/browse/BLMODULES-31)
* `x-to-one` generated `hasX()` methods are not returning the correct values - Resolves [BLMODULES-32](https://ortussolutions.atlassian.net/browse/BLMODULES-32)

See [v1.0.1 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/v1.0.0...v1.0.1).

## 1.0.0 - 2025-03-26

* First iteration of this module

See [v1.0.0 commit history on github](https://github.com/ortus-boxlang/bx-orm/compare/2fe797c6330a5d110f3bfbc5ead058df9bdbe89e...v1.0.0)


# Installation

Get up and running in seconds!

### CommandBox

If you're using CommandBox to manage your BoxLang server, it's as easy as running `install bx-orm`:

```
box install bx-orm
```

You may need to install `bx-compat-cfml` as well for backwards-compatible ORM behaviors:

```
box install bx-orm bx-compat-cfml
```

### bx-module

For the BoxLang runtime or MiniServer outside of CommandBox, use the `bx-module` command from the BoxLang installer:

```
bx-module install bx-orm
```

Note that bx-orm currently only supports the web runtime.


# Configuration

Easily configure Hibernate with BL

## Application.bx

The ORM can be configured by a struct of settings set in `this.ormSettings` in your main `Application.bx`:

```js
class{
    this.ORMenabled = true;
    this.ormSettings = {
        // << Here Be ORM Configuration! 🤪 >>
    };
}
```

## ORM Settings

The full list of available properties you can use to configure the ORM are the following:

| Setting Name            | Default                  | Description                                                                                                                                                                                                                                                                                                       |
| ----------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `announceQueryParams`   | `false`                  | Includes bound parameter values in the `onORMQuery` event. Values can be sensitive, so they are never announced unless you ask. See [Observability](https://bxorm.ortusbooks.com/usage/observability).                                                                                                            |
| `generateMappings`      | `true`                   | Automatically generate entity mappings for persistent classes. When `false`, provide `{entityName}.hbm.xml` files beside the entity.                                                                                                                                                                              |
| `autoGenMap`            | `true`                   | Backwards-compatible alias for `generateMappings`. Deprecated.                                                                                                                                                                                                                                                    |
| `autoManageSession`     | `false`                  | Allows the engine to manage the Hibernate session. Use `transaction` blocks to demarcate transaction regions. See the [Hibernate transaction guide](https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#transactions).                                                       |
| `cacheConfig`           | *empty*                  | Location of the secondary cache provider configuration file. Used only when `secondaryCacheEnabled=true`. See [Secondary Cache](#secondary-cache).                                                                                                                                                                |
| `cacheConfigProperties` | *empty struct*           | Struct alternative to `cacheConfig` for defining secondary cache region settings. See [Secondary Cache](#secondary-cache).                                                                                                                                                                                        |
| `cacheProvider`         | `"BoxCacheProvider"`     | Secondary cache provider. This can be a BoxLang cache provider name, a legacy alias such as `ehcache`, `ConcurrentHashMap`, or `HashTable`, or a fully qualified JCache provider class. See [Secondary Cache](#secondary-cache).                                                                                  |
| `catalog`               |                          | Default database catalog.                                                                                                                                                                                                                                                                                         |
| `entityPaths`           | *empty*                  | Directory or array of directories searched for persistent classes. Specify this to avoid a startup performance cost.                                                                                                                                                                                              |
| `datasource`            | `application.datasource` | Datasource used by the ORM. Defaults to `this.datasource` in `Application.bx` when not specified.                                                                                                                                                                                                                 |
| `defaultBatchSize`      | `16`                     | Default batch size Hibernate uses when fetching lazy collections or proxies.                                                                                                                                                                                                                                      |
| `dbcreate`              | `none`                   | Schema strategy: `update` creates incremental updates, `dropcreate` recreates the database on reload, and `none` leaves the database unchanged.                                                                                                                                                                   |
| `dialect`               | `autodiscover`           | Database dialect. Hibernate introspects the datasource by default, or you can provide a fully qualified Java class name. See [Dialects](#dialects).                                                                                                                                                               |
| `eventHandling`         | `false`                  | Enables ORM event callbacks in entities and globally through `eventHandler`.                                                                                                                                                                                                                                      |
| `eventHandler`          |                          | Path to the `.bx` class that manages global ORM events.                                                                                                                                                                                                                                                           |
| `enableThreadedMapping` | `true`                   | Runs entity mapping generation across multiple threads at startup. Set to `false` to force single-threaded generation.                                                                                                                                                                                            |
| `flushAtRequestEnd`     | `false`                  | Automatically flushes the ORM at the end of a request. Persistence should generally be done through `transaction` blocks.                                                                                                                                                                                         |
| `generateStatistics`    | `false`                  | Collects Hibernate statistics at startup, for `ORMService.getStatistics()`. Collection has a small cost. See [Observability](https://bxorm.ortusbooks.com/usage/observability).                                                                                                                                   |
| `hibernateProperties`   | `empty`                  | Flat struct of raw Hibernate property name/value pairs applied directly to Hibernate configuration. Applied last, so it overrides ORM defaults and `ormconfig`. See [Custom Hibernate Config](https://bxorm.ortusbooks.com/getting-started/configuration/custom-hibernate-config).                                |
| `logSQL`                | `false`                  | Logs SQL queries to the console.                                                                                                                                                                                                                                                                                  |
| `namingstrategy`        | `default`                | Naming convention used for table and column names. See [Naming Strategies](https://bxorm.ortusbooks.com/getting-started/configuration/naming-strategies).                                                                                                                                                         |
| `ormconfig`             |                          | Path to a flat `hibernate.properties` file. Applied before `hibernateProperties`; matching keys in `hibernateProperties` take precedence. The XML `hibernate.cfg.xml` format is not supported. See [Custom Hibernate Config](https://bxorm.ortusbooks.com/getting-started/configuration/custom-hibernate-config). |
| `proxyLazyLoading`      | `false`                  | Wraps lazy-loaded relationship properties in a proxy instead of triggering an immediate load. See [Relationships](https://bxorm.ortusbooks.com/modeling/relationships).                                                                                                                                           |
| `quoteIdentifiers`      | `false`                  | Quotes generated table and column identifiers in the Hibernate mapping.                                                                                                                                                                                                                                           |
| `savemapping`           | `false`                  | Creates `*.hbmxml` mapping files beside the entities for debugging.                                                                                                                                                                                                                                               |
| `schema`                |                          | Default database schema.                                                                                                                                                                                                                                                                                          |
| `secondaryCacheEnabled` | `false`                  | Enables the secondary cache. See [Caching](https://bxorm.ortusbooks.com/usage/caching).                                                                                                                                                                                                                           |
| `ignoreParseErrors`     | `false`                  | Ignores classes with compile-time errors when `true`; otherwise throws exceptions.                                                                                                                                                                                                                                |
| `sqlScript`             |                          | Path to a SQL script executed after ORM initialization.                                                                                                                                                                                                                                                           |
| `useDBForMapping`       | `false`                  | Accepted but has no effect in 1.x: the database is never inspected. Untyped properties map as `string`, and an entity without an id uses its `id` property.                                                                                                                                                       |

## Dialects

By using the `ormsettings.dialect` you can tell Hibernate which specific database dialect to use for building queries. By default, Hibernate tries to inspect the datasource and define it for you. 95% of the time, this works. However, if you want a specific one, then you can use the following names or a fully qualified Java class name.

| Dialect (short name)   | Remarks                                                                                                                                        |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `Cache71`              | Support for the Caché database, version 2007.1.                                                                                                |
| `CockroachDB192`       | Support for CockroachDB version 19.2.                                                                                                          |
| `CockroachDB201`       | Support for CockroachDB version 20.1.                                                                                                          |
| `CUBRID`               | Support for CUBRID version 8.3. May work with later versions.                                                                                  |
| `DB2`                  | Support for DB2 version 8.2.                                                                                                                   |
| `DB297`                | Support for DB2 version 9.7.                                                                                                                   |
| `DB2390`               | Support for DB2 Universal Database for OS/390, also known as DB2/390.                                                                          |
| `DB2400`               | Support for DB2 Universal Database for iSeries, also known as DB2/400.                                                                         |
| `DB2400V7R3`           | Support for DB2 Universal Database for i, also known as DB2/400, version 7.3.                                                                  |
| `DerbyTenFive`         | Support for Derby version 10.5.                                                                                                                |
| `DerbyTenSix`          | Support for Derby version 10.6.                                                                                                                |
| `DerbyTenSeven`        | Support for Derby version 10.7.                                                                                                                |
| `Firebird`             | Support for Firebird.                                                                                                                          |
| `FrontBase`            | Support for Frontbase.                                                                                                                         |
| `H2`                   | Support for H2.                                                                                                                                |
| `HANACloudColumnStore` | Support for the SAP HANA Cloud column store.                                                                                                   |
| `HANAColumnStore`      | Support for the SAP HANA column store, version 2.x. May work with version 1.x.                                                                 |
| `HANARowStore`         | Support for the SAP HANA row store, version 2.x. May work with version 1.x.                                                                    |
| `HSQL`                 | Support for HSQL (HyperSQL).                                                                                                                   |
| `Informix`             | Support for Informix.                                                                                                                          |
| `Ingres`               | Support for Ingres, version 9.2.                                                                                                               |
| `Ingres9`              | Support for Ingres, version 9.3. May work with newer versions.                                                                                 |
| `Ingres10`             | Support for Ingres, version 10. May work with newer versions.                                                                                  |
| `Interbase`            | Support for Interbase.                                                                                                                         |
| `JDataStore`           | Support for JDataStore.                                                                                                                        |
| `McKoi`                | Support for McKoi.                                                                                                                             |
| `Mimer`                | Support for Mimer, version 9.2.1. May work with newer versions.                                                                                |
| `MySQL5`               | Support for MySQL, version 5.x.                                                                                                                |
| `MySQL5InnoDB`         | Support for MySQL, version 5.x, preferring the InnoDB storage engine.                                                                          |
| `MySQL57InnoDB`        | Support for MySQL, version 5.7, preferring the InnoDB storage engine. May work with newer versions.                                            |
| `MariaDB`              | Support for MariaDB. May work with newer versions.                                                                                             |
| `MariaDB53`            | Support for MariaDB, version 5.3 and newer.                                                                                                    |
| `Oracle8i`             | Support for Oracle, version 8i.                                                                                                                |
| `Oracle9i`             | Support for Oracle, version 9i.                                                                                                                |
| `Oracle10g`            | Support for Oracle, version 10g.                                                                                                               |
| `Pointbase`            | Support for Pointbase.                                                                                                                         |
| `PostgresPlus`         | Support for Postgres Plus.                                                                                                                     |
| `PostgreSQL81`         | Support for PostgreSQL, version 8.1.                                                                                                           |
| `PostgreSQL82`         | Support for PostgreSQL, version 8.2.                                                                                                           |
| `PostgreSQL9`          | Support for PostgreSQL, version 9. May work with later versions.                                                                               |
| `Progress`             | Support for Progress, version 9.1C. May work with newer versions.                                                                              |
| `SAPDB`                | Support for SAPDB/MAXDB.                                                                                                                       |
| `SQLite`               | Support for SQLite. It is not auto-discovered, so `dialect` must be set explicitly, and a SQLite JDBC driver must be added to the application. |
| `SQLServer`            | Support for SQL Server 2000.                                                                                                                   |
| `SQLServer2005`        | Support for SQL Server 2005.                                                                                                                   |
| `SQLServer2008`        | Support for SQL Server 2008.                                                                                                                   |
| `Sybase11`             | Support for Sybase up to version 11.9.2.                                                                                                       |
| `SybaseAnywhere`       | Support for Sybase Anywhere.                                                                                                                   |
| `SybaseASE15`          | Support for Sybase Adaptive Server Enterprise, version 15.                                                                                     |
| `SybaseASE157`         | Support for Sybase Adaptive Server Enterprise, version 15.7. May work with newer versions.                                                     |
| `Teradata`             | Support for Teradata.                                                                                                                          |
| `TimesTen`             | Support for TimesTen, version 5.1. May work with newer versions.                                                                               |

{% hint style="info" %}
See the Hibernate Dialect Section: [Hibernate\_User\_Guide.html#database-dialect](https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#database-dialect)
{% endhint %}

### SQLite

bx-orm automatically detects SQLite from the JDBC connection, so you do not need to configure `dialect: "SQLite"` explicitly.

```js
this.datasources = {
    "myDB" : {
        "connectionString" : "jdbc:sqlite:/path/to/my.db"
    }
};

this.ormSettings = {
	datasource : "myDB"
};
```

{% hint style="warning" %}
You'll need a SQLite JDBC driver (e.g. `org.xerial:sqlite-jdbc`) on your application's classpath, as bx-orm does not bundle one.
{% endhint %}

## Sample Config

Here is an example configuration from the popular ContentBox Modular CMS application

```js
// THE CONTENTBOX DATASOURCE NAME
this.datasource  = "contentbox";
// ORM SETTINGS
this.ormEnabled  = true;
this.ormSettings = {
	// An array of paths where your entity classes are located
	entityPaths           : [
		// If you create your own app entities
		"models",
		// The ContentBox Core Entities
		"modules/contentbox/models",
		// Custom Module Entities
		"modules_app",
		// Custom Module User Entities
		"modules/contentbox/modules_user"
	],
	// THE DIALECT OF YOUR DATABASE OR LET HIBERNATE FIGURE IT OUT, UP TO YOU TO CONFIGURE.
	dialect              : request.$systemHelper.getSystemSetting( "ORM_DIALECT", "" ),
    // The database creation strategy (e.g., "update", "create", "dropcreate")
	dbcreate             : "update",
    // Enable or disable the secondary cache
	secondarycacheenabled: request.$systemHelper.getSystemSetting( "ORM_SECONDARY_CACHE", false ),
    // The cache provider to use for the secondary cache
	cacheprovider        : request.$systemHelper.getSystemSetting( "ORM_SECONDARY_CACHE", "ehCache" ),
	// Whether to log SQL statements
    logSQL               : request.$systemHelper.getSystemSetting( "ORM_LOGSQL", false ),
    // The SQL script to execute during ORM initialization
	sqlScript            : request.$systemHelper.getSystemSetting( "ORM_SQL_SCRIPT", "" ),
    // Whether to flush the session at the end of each request
	flushAtRequestEnd    : false,
    // Whether to automatically manage the session
	autoManageSession    : false,
    // Whether to enable event handling
	eventHandling        : true,
    // The event handler class to use
	eventHandler         : "cborm.models.BxEventHandler",
    // Whether to ignore parse errors
	ignoreParseErrors     : true,
	// TURN ON FOR Debugging if ORM mappings are not working.
	savemapping          : false
}
```


# Custom Hibernate Config

Sometimes bx-orm doesn't have a dedicated setting for a Hibernate property you need. There are two ways to set arbitrary Hibernate properties directly: a `hibernate.properties` file via `ormconfig`, or an inline struct via `hibernateProperties`.

### ormConfig: A Properties File

Point `ormconfig` at a flat, standard Java `hibernate.properties`-formatted file:

```js
this.ormSettings = {
    // ...
    ormconfig : "./config/hibernate.properties"
};
```

The file is a simple list of `key=value` pairs, one Hibernate property per line:

```properties
# hibernate.properties
hibernate.connection.release_mode=on_close
hibernate.use_sql_comments=true
```

{% hint style="warning" %}
Only the flat `key=value` properties file format is supported. The XML `hibernate.cfg.xml` format is not yet implemented.
{% endhint %}

### hibernateProperties: An Inline Struct

For settings you'd rather keep alongside the rest of your ORM config instead of in a separate file, use the `hibernateProperties` struct:

```js
this.ormSettings = {
    // ...
    hibernateProperties = {
        "hibernate.connection.release_mode" = "on_close",
        "hibernate.use_sql_comments" = "true"
    }
};
```

Every entry is applied directly to the Hibernate configuration, giving you an escape hatch for tuning any Hibernate setting bx-orm doesn't expose a dedicated setting for.

### Precedence

Both settings are applied **after** bx-orm's own internal defaults, so either can override bx-orm's hardcoded Hibernate settings (e.g. flush and auto-close behavior). When using both together:

1. `ormconfig` (the file) is applied first.
2. `hibernateProperties` (the inline struct) is applied second, so it wins on a conflicting key.

{% hint style="info" %}
A handful of settings that are load-bearing for bx-orm's own correctness (JDBC connection provider wiring, classloaders, session context class, identifier quoting, and entity mode) are re-applied internally *after* `ormconfig` and `hibernateProperties` are processed, so neither can break those specific things no matter what you set.
{% endhint %}

### Example: Fixing Cross-Database "Statement Is Closed" Errors

If your app runs against multiple database engines (e.g. MySQL, MSSQL, PostgreSQL) you may see Hibernate `"statement is closed"` errors on MSSQL or Postgres, caused by stale JDBC statements after per-save transaction commits. Setting `hibernate.connection.release_mode` per-app resolves this:

```js
this.ormSettings = {
    // ...
    hibernateProperties = {
        "hibernate.connection.release_mode" = "on_close"
    }
};
```


# Secondary Caches

Hibernate's secondary cache is a powerful tool that can greatly improve the performance of your application. By storing frequently accessed data in memory, the secondary cache can reduce the number of database queries that need to be made, resulting in faster response times and more efficient use of system resources. Whether you're working on a small project or a large enterprise application, the secondary cache is an essential part of any Hibernate-based system. So if you want to get the most out of your Hibernate application, take advantage of this powerful caching feature!

<figure><img src="https://146896706-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FpE0DivA4DpsOBQKEddvG%2Fuploads%2Fgit-blob-0b6ed57765afba8b6e5510859b352e6349003098%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

Please see the [caching section](https://bxorm.ortusbooks.com/usage/caching) for all the wonderful caching strategies you can do with Hibernate.

### Configuration

A secondary cache provider is a class that manages a level of caching secondary to Hibernate's main caching context - the Hibernate session. A secondary cache enables longer-running cache contexts, more fine-grained control over cache busting, and other performance-related benefits.

The only setting necessary to enable secondary caching is the `secondaryCacheEnabled` setting:

```js
this.ormSettings = {
    secondaryCacheEnabled : true
};
```

To configure the caching, specify the path to an XML cache configuration file in `cacheConfig`:

```js
this.ormSettings = {
    secondaryCacheEnabled: true,
    cacheConfig          : "./config/ehcache.xml"
};
```

This `ehcache.xml` cache configuration then should look something like this:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" name="default">
    <diskStore path="java.io.tmpdir"/>
        <defaultCache
            maxElementsInMemory="10000" eternal="false"
            timeToIdleSeconds="120" timeToLiveSeconds="120"
            maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
            <persistence strategy="localTempSwap"/>
        </defaultCache>
        <cache
            name="Autos"
            maxElementsInMemory="20"
            overflowToDisk="false"
            eternal="true">
        </cache>
</ehcache>
```

### How the Cache Provider Setting Works

bx-orm bridges Hibernate's JCache (JSR-107) SPI to BoxLang's own `CacheService`, so `cacheProvider` selects a **BoxLang cache provider by name** rather than a specific Hibernate/EHCache implementation:

```js
this.ormSettings = {
    secondaryCacheEnabled : true,
    // use the "userCache" provider registered in your CacheBox/CacheService config
    cacheProvider : "userCache"
};
```

* The default, `"BoxCacheProvider"`, uses BoxLang's built-in in-memory cache.
* `"ConcurrentHashMap"` and `"HashTable"` are legacy aliases kept for CFML/Lucee compatibility; both simply resolve to the default BoxLang cache provider.
* Any other value must be the name of a cache provider already registered with BoxLang's `CacheService` (e.g. via CacheBox). If no provider with that name is found, ORM startup throws an error.
* `cacheConfigProperties` lets you pass secondary-cache settings as a BoxLang struct instead of (or alongside) an XML `cacheConfig` file.

See the [Caching](https://bxorm.ortusbooks.com/usage/caching) page for entity-level cache strategies (`cacheUse`).


# Logging

How do Hibernate logs work in bx-orm?

There are several categories of logs generated during normal use of a bx-orm application:

1. `bx-orm` logs
2. SQL logs
3. Hibernate logs
4. Startup Metrics

## bx-orm logs

Logging statements generated from bx-orm itself will be output to the `orm.log` file located in the boxlang runtime `logs/` directory.

This log file may look something like the below when DEBUG mode is enabled:

```
[2025-04-25T09:50:34,965] [Test worker] [DEBUG] [ORM] beforeApplicationListenerLoad fired; checking for ORM configuration 
[2025-04-25T09:50:34,972] [Test worker] [DEBUG] [ORM] ORMEnabled, starting up ORM app for [myApp] 
[2025-04-25T09:50:34,979] [Test worker] [DEBUG] [ORM] ORMApp created for application: [myapp_1428735748] 
[2025-04-25T09:50:35,001] [Test worker] [DEBUG] [ORM] Found more than 20 entities; parallelizing metadata introspection 
[2025-04-25T09:50:35,006] [Test worker] [DEBUG] [ORM] Loading metadata for class /app/models/cms/Author.bx 
[2025-04-25T09:50:35,007] [Test worker] [DEBUG] [ORM] Parsing class file: [/app/models/cms/Author.bx] 
...
```

For more information on configuring loggers, see the [Boxlang Logging](https://boxlang.ortusbooks.com/getting-started/configuration/logging) documentation.

## SQL Logs

bx-orm has the ability to log every SQL statement generated from ORM code. For example, firing `entityDelete( myEntity )` will generate a `DELETE` SQL statement for deleting the entity (table row) in question from the entity table.

A quick example might be this log, generated after firing `entityNew( "Manufacturer", properties )`:

```
[2025-04-25T09:50:46,264] [Test worker] [DEBUG] [org.hibernate.SQL] 
    /* insert Manufacturer
        */ insert 
        into
            manufacturers
            (name, address, id) 
        values
            (?, ?, ?) 
```

To enable this behavior, set `this.ormSettings.logSQL` to `true` in your `Application.bx`:

```js
this.ormSettings={
	"logSQL" : "true"
	// ...
}
```

These SQL statements will also log to the `orm.log` file located in `${boxlang-home}/logs`.

## Hibernate-native logs

Hibernate-native logging statements will also be captured in the `orm.log` file located in `${boxlang-home}/logs`.

## Startup Metrics

In debug mode, bx-orm will log the time taken for each step of the startup process, including entity discovery, metadata parsing, XML mapping generation, and SessionFactory building. Here are some example log entries:

```bash
ORM startup metric - entity file discovery: 42ms (187 candidate files found)
ORM startup metric - entity metadata parsing: 310ms (23 persistent entities found, sequential mode)
ORM startup metric - XML mapping generation: 88ms (23 mapping files written)
ORM startup metric - Hibernate SessionFactory build time [myDatasource]: 1243ms
ORM startup metric - Hibernate SessionFactory build time [defaultDatasource]: 987ms
```

{% hint style="info" %}
Only available in bx-orm\@1.6.4 and later.
{% endhint %}


# Naming Strategies

Boxlang ORM provides flexible naming strategies to control how entity and property names are mapped to database tables and columns. This allows you to easily customize schema, table, column and other physical names to match your database conventions without having to change your source code.

## Predefined Naming Strategies

You have several choices of naming strategies to choose from:

* **default**: No conversion is performed. Entity and property names are mapped to table and column names exactly as defined in your code.
* **smart**: Applies a smart conversion:
  * All names are forced to uppercase.
  * camelCase names are automatically separated with underscores. For example, `userProfile` becomes `USER_PROFILE`.
* **custom**: Specify a custom naming strategy class that implements the `INamingStrategy` interface. This allows you to implement your own logic for converting names. See [Custom Naming Strategy](#custom-naming-strategy).

## Custom Naming Strategy

Need something else? Try a custom naming strategy. This allows you to implement your own logic for converting entity and property names to table and column names.

```js
this.ormSettings = {
	// ...
	namingStrategy : "models.orm.UnderscoreNamingStrategy"
}
```

The naming strategy may implement [the `INamingStrategy` interface](https://github.com/ortus-boxlang/bx-orm/blob/development/src/main/bx/models/INamingStrategy.bx#L23), or you may omit the declaration and simply provide a class with the appropriate methods. The following methods are supported:

* `public string function getTableName( string tableName )`
* `public string function getColumnName( string columnName )`
* `public string function getCatalogName( string catalogName )`
* `public string function getSchemaName( string schemaName )`
* `public string function getSequenceName( string sequenceName )`


# ACF/Lucee Migration Guide

Migrating to BoxLang ORM from Adobe ColdFusion and Lucee

BoxLang ORM is designed to be compatible with existing CFML ORM code, but there are some differences and considerations when migrating from Adobe ColdFusion (ACF) or Lucee.

## Configuration Differences

There are several ORM settings which have been renamed OR the default value changed in `bx-orm`. You will need to either rename these in your configuration, or install `bx-compat-cfml` to provide compatibility with the old settings names.

### Renamed Settings

| Setting name (ACF/Lucee) | Setting name (BoxLang) |
| ------------------------ | ---------------------- |
| `skipCFCWithError`       | `ignoreParseErrors`    |
| `cfcLocation`            | `entityPaths`          |

Both of these settings are supported in `bx-compat-cfml` for compatibility with existing code, but you should update your configuration to use the new names to avoid confusion and ensure future compatibility.

### Changed Defaults

| Setting                                           | Lucee Default | ACF Default | BoxLang Default |
| ------------------------------------------------- | ------------- | ----------- | --------------- |
| `ignoreParseErrors` (formerly `skipCFCWithError`) | `true`        | `true`      | `false`         |
| `autoManageSession`                               | `true`        | `true`      | `false`         |
| `flushAtRequestEnd`                               | `true`        | `true`      | `false`         |
| `proxyLazyLoading`                                | `true`        | `true`      | `false`         |

Again, each of these settings are reverted to the ACF/Lucee defaults in `bx-compat-cfml`.

## Built-in Function Differences

Most of the built-in functions (BIFs) from other CFML engines are functionally identical in BoxLang. A few notable exceptions:

### `EntityLoadByPK()`

In ACF/Lucee, this BIF returns an array of entities by default, and you must pass a `unique=true` argument to return a single entity. In BoxLang, a single entity is returned by default, and the `unique` argument is not supported. To return an array of entities in BoxLang, use the `entityLoad` BIF instead.

```js
// Lucee/ACF returns an array
var myAuto = entityLoadByPK( "Automobile", "1HGCM82633A123456" ).first();
// BoxLang returns a single item
var myAuto = entityLoadByPK( "Automobile", "1HGCM82633A123456" );
```

### `EntityNew()`

In ACF, a third argument `ignoreExtras` is implemented which allows you to ignore struct keys that do not match properties on the entity. In Lucee, this argument is called `ignoreNotExisting` but is not properly implemented and is always `true`. In BoxLang, this argument is not supported and any extra keys will cause an error. To achieve similar functionality in BoxLang, you can filter the struct of values before passing it to `EntityNew` to remove any keys that do not match properties on the entity.

ACF, Lucee, and BoxLang will all error if you attempt to set a property that does not exist on the entity:

```js
var entityProps = { nonExistentKey: "Blue" };
var myNewEntity = entityNew( "Automobile", entityProps );
```

ACF does allow ignoring keys that do not match an entity property:

```js
var entityProps = { nonExistentKey: "Blue" };
var myNewEntity = entityNew( "Automobile", entityProps, true );
```


# Performance

bx-orm is designed to be as fast as possible, but there are some factors that can affect performance. Let's look at a few key areas where you can optimize performance in your application.

## ORM Startup

You want the short answer?

* Commit your XML mapping files to disk and set `this.ormSettings.generateMappings = false` to eliminate the XML mapping generation time on startup.
* Fine-tune `this.ormSettings.entityPaths` to minimize the number of candidate files that need to be parsed for entity discovery.

See also [Startup Metrics Logs](https://bxorm.ortusbooks.com/getting-started/configuration/logging#startup-metrics) for consolidated examples of the debug log output for ORM startup performance metrics.

### Entity Discovery

The initial step in ORM startup is to discover ORM entities and parse the entity metadata into internal structures. The time will be proportional to the number of entities found and the number of candidate files that need to be parsed to find those entities. By default, bx-orm will scan all CFC files in the specified entity paths, which can lead to a large number of candidate files and increased startup time.

This can be minimized by fine-tuning `this.ormSettings.entityPaths` [in your orm configuration](https://github.com/ortus-docs/bxorm/tree/master/intro/configuration/README.md).

Enable debug logging to see the time taken for entity discovery and metadata parsing in the logs:

```bash
ORM startup metric - entity file discovery: 42ms (187 candidate files found)
ORM startup metric - entity metadata parsing: 310ms (23 persistent entities found, sequential mode)
```

### XML Mapping Generation

Once persistent entities are located and metadata is collected, bx-orm generates XML mapping files for each entity. This process can be time-consuming, especially if you have a large number of entities.

This startup penalty can be mostly eliminated by committing your hbm.xml mappings to disk and setting `this.ormSettings.generateMappings = false`.

Note that for any ORM entity changes, you will need to regenerate the XML mapping files by setting `this.ormSettings.generateMappings = true` and running `ormReload()` or restarting your application. This will regenerate the XML mappings to pick up any changes.

You can also pre-generate `.hbm.xml` files from the command line, without booting a full application, using the [GenerateMappings CLI tool](https://bxorm.ortusbooks.com/reference/cli-tools).

Enable debug mode to see the time taken for XML mapping generation in the logs:

```bash
ORM startup metric - XML mapping generation: 88ms (23 mapping files written)
```

### SessionFactory Build

The bulk of this time is spent in hibernate startup itself. You can minimize this by investigating and applying standard Hibernate performance optimizations.

Enable debug mode to see the time taken for SessionFactory building in the logs:

```bash
ORM startup metric - Hibernate SessionFactory build time [myDatasource]: 1243ms
```

## Runtime Performance

Most ORM performance problems happen after startup. Measure the SQL generated by Hibernate and the time spent in the database before changing fetch strategies or caching. A faster application usually comes from loading fewer rows, issuing fewer queries, and keeping transactions short.

### Use Lazy Loading Deliberately

Keep large to-many relationships lazy so loading a parent entity does not also load its entire object graph. This is usually the right default for `one-to-many` and `many-to-many` relationships. See [Modeling Relationships](https://bxorm.ortusbooks.com/modeling/relationships#lazy-loading) for the available `lazy` values.

Lazy loading is not a request to load data for free. Accessing a lazy relationship triggers another SQL query while the entity is attached to an ORM session. Access lazy properties inside the transaction or session boundary, and avoid returning entities to code that will access unloaded relationships after the session has closed.

Do not make every relationship eager to avoid lazy-loading errors. Eager to-many relationships can load a large amount of data and can multiply rows when several collections are joined. Choose the fetch plan for each use case instead.

### Prevent N+1 Queries

An N+1 query occurs when one query loads a list of parent entities and then one additional query runs for each parent's relationship. It is easy to create accidentally:

```js
var users = entityLoad( "User", {}, "name asc", { maxResults: 50 } );

for ( var user in users ) {
	// Accessing posts here can issue one query per user.
	println( user.getPosts().size() );
}
```

When a screen or operation needs a relationship for every result, fetch it intentionally with an HQL join:

```js
var users = ORMExecuteQuery(
	hql    : "SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.posts WHERE u.active = true",
	params : {},
	options: { maxResults: 50 }
);
```

Use fetch joins for the specific use case that needs the related data. Do not fetch-join multiple to-many collections in one query, and be cautious with pagination over a collection fetch join because the database paginates joined rows rather than distinct parent entities. For larger result sets, prefer batch fetching or separate queries.

### Batch Fetching

Batch fetching lets Hibernate initialize several lazy associations with fewer `SELECT` statements. Configure a moderate default batch size through `hibernateProperties`, then tune it using query logs and database metrics:

```js
this.ormSettings.hibernateProperties = {
	"hibernate.default_batch_fetch_size": 25
};
```

Batch fetching is useful when a request loads many entities and then accesses the same lazy relationship on several of them. It does not replace a good fetch plan: a fetch join is often better when the relationship is always required, while batching is useful when access is conditional.

### Batch Writes

For large insert or update jobs, use one transaction and enable JDBC batching. Hibernate can group compatible statements into fewer database round trips:

```js
this.ormSettings.hibernateProperties = {
	"hibernate.jdbc.batch_size": 25,
	"hibernate.order_inserts": true,
	"hibernate.order_updates": true
};
```

Use a batch size appropriate for the database and driver, and commit in bounded chunks for very large jobs. Keep an eye on memory because the session retains managed entities until they are flushed and cleared. Bulk HQL `UPDATE` and `DELETE` statements can be more efficient than loading and changing thousands of entities, but they bypass entity lifecycle events and require careful cache handling.

### Select Only What You Need

For reports, exports, and list screens, avoid loading a complete entity graph when a few columns are sufficient. Use an HQL projection or a purpose-built query, apply `maxResults` and `offset` for pagination, and return read-only results when the data will not be changed:

```js
var rows = ORMExecuteQuery(
	hql    : "SELECT u.id, u.name, u.email FROM User u WHERE u.active = true ORDER BY u.name",
	params : {},
	options: {
		maxResults: 100,
		offset    : 0,
		readOnly  : true
	}
);
```

For deep pagination, large offsets can become expensive because the database still has to find and discard preceding rows. Prefer keyset pagination, such as `WHERE u.id > :lastId ORDER BY u.id`, when the workflow supports it.

### Keep Transactions and Sessions Focused

Open the transaction as late as practical, perform the required work, and commit promptly. Do not hold a transaction open while rendering a response, calling a remote service, or waiting for user input. Long sessions also increase dirty-checking work and memory usage.

For read-heavy code, use `readOnly: true` on queries where supported so Hibernate does not need to track changes for those results. Do not use read-only mode for entities that the operation intends to modify.

### Index the Queries You Actually Run

Hibernate cannot compensate for missing database indexes. Add indexes for columns used frequently in `WHERE`, `JOIN`, and `ORDER BY` clauses, especially foreign keys used by relationships. Validate index choices with the database's execution plan; an index that helps one query can hurt write performance or be ignored when selectivity is poor.

### Inspect Before Optimizing

Enable SQL logging temporarily and inspect:

* the number of SQL statements for one request;
* repeated queries that differ only by an identifier, which often indicates N+1 loading;
* large result sets caused by eager relationships or fetch joins;
* slow statements in the database execution plan;
* flushes or unexpected updates before a query.

See [Querying](https://bxorm.ortusbooks.com/usage/querying), [Session Management](https://bxorm.ortusbooks.com/usage/session-management), and [Caching](https://bxorm.ortusbooks.com/usage/caching) for bx-orm-specific behavior. For the underlying fetch and batching rules, see Hibernate's [Fetching](https://docs.hibernate.org/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#fetching), [Batching](https://docs.hibernate.org/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#batch), and [Querying](https://docs.hibernate.org/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#hql) chapters.


# Entities

Learn the basics of modeling ORM entities

A persistent entity is a boxlang class that is marked as a database entity via the `persistent` annotation upon the class definition:

```js
class persistent="true"{

}
```

By default, the entity name will be the boxlang class file name - minus the file extension, of course. We can modify the entity name via the `entityname` annotation:

```js
class persistent="true" entityname="Author" {

}
```

And the table name via the `table` annotation:

```js
class persistent="true" entityname="Author" table="authors" {

}
```

Here's the full list of available annotations for a persistent class:

| Attribute             | Type      | Default | Description                                                                                                                 |
| --------------------- | --------- | ------- | --------------------------------------------------------------------------------------------------------------------------- |
| `persistent`          | `boolean` | `false` | Mark this class as an ORM entity                                                                                            |
| `entityname`          | `string`  |         | Set a custom entity name which is different than the boxlang class name                                                     |
| `table`               | `string`  |         | Specify the database table name                                                                                             |
| `schema`              | `string`  |         | Specify the database schema name.                                                                                           |
| `catalog`             | `string`  |         | Specify the database catalog name.                                                                                          |
| `dynamicinsert`       |           |         | Specifies whether INSERT SQL is generated at runtime. Only columns whose values are not null are included in the SQL.       |
| `dynamicinsert`       | `boolean` | `false` | Specifies whether INSERT SQL is generated at runtime. Only columns whose values are not null are included in the SQL.       |
| `dynamicupdate`       | `boolean` | `false` | Specifies whether UPDATE SQL is generated at runtime. Only columns whose values are not null are included in the SQL.       |
| `readonly`            | `boolean` | `false` | Specify whether the table is read-only.                                                                                     |
| `selectbeforeupdate`  | `boolean` |         | Specify whether Hibernate should perform an SQL `UPDATE` only when an object is actually modified.                          |
| `optimisticlock`      | `string`  |         | Determines the locking strategy: `all`, `dirty`, `version`, or `none`.                                                      |
| `batchsize`           | `integer` |         | Number of records to retrieve at a single instance.                                                                         |
| `lazy`                | `boolean` | `true`  | Whether loading is done lazily.                                                                                             |
| `rowid`               | `string`  |         | Specify the row ID.                                                                                                         |
| `discriminatorColumn` | `string`  |         | Define the discriminator column used in inheritance mapping.                                                                |
| `discriminatorValue`  | `string`  |         | Define the discriminator value used in inheritance mapping.                                                                 |
| `joinColumn`          | `string`  |         | Define a join column for inheritance mapping.                                                                               |
| `mappedSuperClass`    | `boolean` | `false` | Mark a non-persistent parent class as a mapped superclass. Its properties are folded into each persistent subclass's table. |
| `embedded`            | `boolean` |         | Mark the class as embedded so its properties are persisted with the parent's data.                                          |
| `cacheUse`            | `string`  |         | Caching strategy: `read-only`, `nonstrict-read-write`, `read-write`, or `transactional`.                                    |
| `cacheName`           | `string`  |         | Specify the name of the secondary cache.                                                                                    |
| `cacheInclude`        | `string`  | `all`   | Set to `non-lazy` to exclude lazy-loaded properties from the secondary cache entry.                                         |
| `saveMapping`         | `boolean` | `false` | Save the generated Hibernate mapping file as `{class name}.hbm.xml` beside the BoxLang class.                               |
| `datasource`          | `string`  |         | Name a specific datasource to persist this entity to.                                                                       |

### Sharing Properties with `mappedSuperClass`

Use `mappedSuperClass` when you want several entities to share a set of properties (like audit columns) without those properties living in their own database table:

```js
// BaseEntity.bx - not persistent itself
class mappedSuperClass="true" {
    property name="createdDate" ormType="timestamp";
    property name="modifiedDate" ormType="timestamp";
}

// Author.bx
class persistent="true" extends="BaseEntity" {
    property name="authorID" fieldtype="id";
    property name="name" ormType="string";
    // createdDate and modifiedDate columns are added to the "Author" table
}
```

This differs from `joinColumn`/`discriminatorValue` inheritance, where subclasses share rows through a join or a discriminator column in a single parent table. With `mappedSuperClass`, there is no parent table at all: every property is copied into each subclass's own table.


# Properties

Entity properties are how we map table columns to boxlang object values. You can specify an entity property by setting `persistent="true"` on any `property` inside a persistent boxlang class:

```js
class persistent="true"{
    property name="name" type="string" persistent="true";
}
```

By default, all properties inside a `persistent=true` class are assumed to be persistent as well. Thus, we can skip the `persistent=true` annotation for brevity:

```js
class persistent="true"{
    property name="name" type="string";
}
```

## Common Property Annotations

| Attribute    | Type      | Description                                                                                                                 |
| ------------ | --------- | --------------------------------------------------------------------------------------------------------------------------- |
| `persistent` | `boolean` | Define this property as a persistent property. If `false`, this property will be completely ignored from an orm standpoint. |
| `name`       | `string`  | Property name                                                                                                               |
| `default`    | `string`  | Default value for the property. This only reaches the boxlang engine, and *does not affect creation of the entity table.*   |
| `column`     | `string`  | Table column where the property value is stored.                                                                            |
| `dbDefault`  | `string`  | Set the default value for the property.                                                                                     |

Make sure you quote datetime `dbdefault` values to avoid invalid date errors in MySQL:

```js
property
    name     ="createdOn"
    ormtype  ="datetime"
    dbdefault="'2016-10-10'";
```

## Property Types

There are several "type" concepts and annotations you may need to use to keep the proper format when persisting or retrieving table data. While these may look similar, they are not equivalent.

| Attribute   | Examples                     | Description                                                                            |
| ----------- | ---------------------------- | -------------------------------------------------------------------------------------- |
| `type`      | `date`,`numeric`             | Boxlang data type                                                                      |
| `fieldtype` | `column`,`id`, `one-to-many` | Denote a special type of field, like an identifier or relationship field.              |
| `ormType`   | `big_decimal`,`timestamp`    | Data type for the database value.                                                      |
| `sqlType`   | `nvarchar`                   | A vendor-specific SQL type used for table creation only. This can normally be ignored. |

## Field Type

The `fieldtype` attribute allows you to define the behavior and purpose of this property:

```js
property
    name="userID"
    fieldtype="id"
    type="string";
```

There are several options for the `fieldtype` value:

* `column` - By far the most common, this is the default behavior of every field.
* `id` - Notes this field as the primary key or part of the a composite key.
* `collection` - Denote a collection of items - this could represent a struct, an array
* `version` - Denote a version field, useful for [optimistic locking](https://en.wikipedia.org/wiki/Optimistic_concurrency_control) on an entity
* `timestamp` - Denote a timestamp field
* `one-to-one` - Denote a [one-to-one relationship](https://bxorm.ortusbooks.com/modeling/relationships#one-to-one)
* `one-to-many` - Denote a [one-to-many relationship](https://bxorm.ortusbooks.com/modeling/relationships#one-to-many)
* `many-to-one` - Denote a [many-to-one relationship](https://bxorm.ortusbooks.com/modeling/relationships#many-to-one)
* `many-to-many` - Denote a [many-to-many relationship](https://bxorm.ortusbooks.com/modeling/relationships#many-to-many)
* `primary` - Not currently used.

## ORM Type

The `ormType` attribute allows you to define the database type of the property. This is important for ensuring that data is properly converted when being persisted or retrieved from the database. The `ormType` values are based on Hibernate types, and are documented in the [Hibernate 3.3 Mapping Documentation](https://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-types).

While not an exhaustive list, here are some of the more common `ormType` values:

* blob
* bit
* tinyint
* yesno
* truefalse
* bigdecimal
* biginteger
* integer
* numeric
* date
* datetime
* char
* nchar
* text

See [Type Conversion](https://bxorm.ortusbooks.com/modeling/type-conversion) for exactly how each `ormType` value is bridged to a JDBC column type.

## Generator Annotations

| Attribute   | Type               | Description                                                                                                                                                                                                                                           |
| ----------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `generator` | `string`           | One of the built-in generators: `assigned`, `foreign`, `guid`, `identity`, `increment`, `native`, `select`, `sequence`, `sequence-identity`, `uuid`, `uuid2`. Any other value is treated as a fully-qualified Java class name for a custom generator. |
| `params`    | `struct`, `string` | `{ "table: "uuid_table", column: "uuid_value_column" }`                                                                                                                                                                                               |
| `sequence`  | `string`           | Specify the database sequence key name to use for value generation. Use with `generator="sequence"`                                                                                                                                                   |
| `selectkey` | `string`           | Only used with `generator=select`. Specify the select key to use when selecting sequence values from the database.                                                                                                                                    |
| `generated` | `string`           | Specify whether this property should generate values upon entity save. One of `always`, `insert`, `never`.                                                                                                                                            |

```js
property name      = "userID"
         fieldtype = "id"
         generator = "sequence"
         sequence  = "userIDGenerator";
```

{% hint style="warning" %}
The legacy CFML/Lucee generator name `seqhilo` is **not** a recognized built-in generator in bx-orm. Use `generator="sequence"` instead. See [Identifiers](https://bxorm.ortusbooks.com/modeling/identifiers) for the full list of built-in generators.
{% endhint %}

{% hint style="info" %}
See [Identifiers and Generators](https://bxorm.ortusbooks.com/modeling/identifiers#common-generator-types) for more information on generated value properties.
{% endhint %}

## Validation

| Attribute        | Type      | Description                                                                                                  |
| ---------------- | --------- | ------------------------------------------------------------------------------------------------------------ |
| `notnull`        | `boolean` | Specify a not-null constraint.                                                                               |
| `insert`         | `boolean` | Allow inserting values to new rows.                                                                          |
| `update`         | `boolean` | Allow value updates on existing rows.                                                                        |
| `uniquekey`      | `string`  | Specify a key name for a unique constraint. Useful for defining a unique constraint across multiple columns. |
| `unique`         | `boolean` | Specify a unique constraint. Default `false`.                                                                |
| `validateParams` | `string`  | *Not currently supported*                                                                                    |
| `validate`       | `string`  | *Not currently supported*                                                                                    |

## Collection Modifiers

These property annotations are used when setting `fieldtype="collection"` and `collectiontype` is either `struct` or `map`.

| Attribute         | Type     | Description                                                           |
| ----------------- | -------- | --------------------------------------------------------------------- |
| `structkeycolumn` | `string` | Specify the column name to use as the key in the collection struct.   |
| `structkeytype`   | `string` | Specify the ORM type of the key column.                               |
| `elementcolumn`   | `string` | Specify the column name to use as the value in the collection struct. |
| `elementtype`     | `string` | Specify the value type of the collection values.                      |

```js
property name            = "yearlyEarnings"
         class           = "Earnings"
         fieldtype       = "collection"
         collectiontype  = "struct"
         structkeycolumn = "year"
         structkeytype   = "integer"
         elementcolumn   = "totalEarnings"
         elementtype     = "bigdecimal";
```

## Relationship Modifiers

| Attribute           | Type                | Description                                                                                                                                                                                                                    |
| ------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `table`             | `string`            | Define the table where the foreign items are stored.                                                                                                                                                                           |
| `lazy`              | `boolean`, `string` | Define a lazy association retrieval type. One of `true`, `false`, `extra`.                                                                                                                                                     |
| `inverse`           | `boolean`           | Specify that the association "owner" is referenced and managed on the opposite entity - not this current entity.                                                                                                               |
| `inversejoincolumn` | `string`            | Specify the join column on the associated entity. For `inverse` associations only.                                                                                                                                             |
| `linkschema`        | `string`            | Specify the schema name of the link table                                                                                                                                                                                      |
| `linkcatalog`       | `string`            | Specify the catalog name of the link table                                                                                                                                                                                     |
| `linktable`         | `string`            | Specify the name of the link table                                                                                                                                                                                             |
| `missingRowIgnored` | `boolean`           | Do not throw an error if a foreign key has no match in the foreign entity                                                                                                                                                      |
| `fkcolumn`          | `string`            | Specify the foreign key column in the link table referencing this entity's primary key                                                                                                                                         |
| `orderby`           | `string`            | Specify the order by clause for the association                                                                                                                                                                                |
| `fetch`             | `string`            | Specify the fetch strategy for the association. One of `join`, `select`.                                                                                                                                                       |
| `cascade`           | `string`            | Specify the cascade operation(s) to use upon manipulation of this entity or association. One of `all`,`none`,`save-update`,`delete`,`all-delete-orphan`,`delete-orphan`,`create`,`merge`,`lock`,`refresh`,`evict`,`replicate`. |
| `constrained`       | `boolean`           | Only valid for `one-to-one` relationships. [See Hibernate 3.3 Mapping Documentation](https://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-onetoone)                                    |
| `optimisticLock`    | `boolean`           | Enable optimistic locking on this association. One of `all`, `dirty`, `version`, `none`.                                                                                                                                       |
| `mappedby`          | `string`            | Specify the property on the association that maps to this entity.                                                                                                                                                              |
| `class`             | `string`            | Specify the location of the foreign entity.                                                                                                                                                                                    |
| `joinColumn`        | `string`            | Join the foreign entity on this column in this entity.                                                                                                                                                                         |
| `where`             | `string`            | Arbitrary SQL where clause for the relation.                                                                                                                                                                                   |
| `singularname`      | `string`            | Singular name to use when generating accessor methods for the relationship: `addPost()`, `removePost()`                                                                                                                        |

```js
property name         = "posts"
         singularName = "post"
         fieldtype    = "one-to-many"
         class        = "Post"
         lazy         = "true"
         fkcolumn     = "author_id";
```

{% hint style="info" %}
See [Modeling Relationships](https://bxorm.ortusbooks.com/modeling/relationships) for more details on modeling an ORM entity relationship.
{% endhint %}

## Other

| Attribute      | Type      | Description                                                                                                                              |
| -------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `scale`        | `integer` | Decimal scale                                                                                                                            |
| `precision`    | `integer` | Decimal precision                                                                                                                        |
| `length`       | `integer` | String length                                                                                                                            |
| `formula`      | `string`  | Define this property as a computed property by using a SQL query to determine the property value. Formula properties cannot be modified. |
| `index`        | `string`  | Key name for a property value index.                                                                                                     |
| `cacheUse`     | `string`  | Define a cache type to use for this property. One of `read-only`, `nonstrict-read-write`, `read-write`, or `transactional`.              |
| `cacheName`    | `string`  | Set the name of the cache to use for this property.                                                                                      |
| `cacheInclude` | `string`  | Set to `non-lazy` to exclude this property from the secondary cache entry when lazy-loaded. Defaults to `all`.                           |
| `unSavedValue` | `string`  | Set a value to populate into this column on newly instantiated entities.                                                                 |

## Formula Property

```js
property name="totalPosts"
    ormType="integer"
    formula="(
        SELECT COUNT(*)
        FROM posts
        WHERE posts.FK_user = id
    )";
```

## Unsupported Attributes

{% hint style="info" %}
Looking for better support of a specific persistent attribute? [Contact our Support team to consider sponsoring this feature](https://boxlang.io/plans).
{% endhint %}


# Identifiers

All about entity identifiers, from primary keys, and generators to composite keys and field types.

Identifier properties are denoted via `fieldtype="id"`.

We highly recommend disabling updates on identifier properties via `update="false"`:

```js
property name      = "id"
         fieldtype = "id"
         ormtype   = "string"
         generator = "assigned"
         update    = "false";
```

## Common Generator Types

### Assigned Generator

The Assigned generator is the default identifier generator type, and simply allows the application (your boxlang code) to assign identifier values prior to insertion. You can think of this as `generator=none`.

> lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified. - [*Hibernate 3.3 mapping reference docs*](https://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-id-generator)

```js
property name      = "id"
         fieldtype = "id"
         generator = "assigned"
         update    = "false";
```

Assigned generators will commonly use [a `preInsert()` event listener](https://bxorm.ortusbooks.com/usage/events#entity-event-handler) to assign the identifer value:

```js
function preInsert( entity ){
    setId( createUUID() );
}
```

### Select Generator

A select generator will attempt to select the next identifier value from the specified `selectKey` column:

> retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value. - [*Hibernate 3.3 mapping reference docs*](https://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-id-generator)

```js
property name      = "userID"
         fieldtype = "id"
         generator = "select"
         selectKey = "ssn"
         update    = "false";
```

### UUID Generator

The UUID generator uses Hibernate's uuid generator under the hood:

> uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length. - [*Hibernate 3.3 mapping reference docs*](https://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-id-generator)

```js
property name      = "userID"
         fieldtype = "id"
         generator = "uuid"
         update    = "false";
```

### Increment Generator

The Increment generator uses a simple incrementing value to create identifiers. Do not use in concurrent applications, as the values may no longer be unique.

> Generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster. - [*Hibernate 3.3 mapping reference docs*](https://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-id-generator)

```js
property name      = "userID"
         fieldtype = "id"
         generator = "increment"
         update    = "false";
```

#### Other Valid Generator Types

There are several lesser-known identifier generator types, including:

* `foreign` - use a specific property from a foreign entity
* `sequence` - use a database sequence (name it with the `sequence` attribute); replaces the legacy `seqhilo` generator name
* `sequence-identity` - use a database sequence, then retrieve the generated value via `INSERT ... RETURNING` (supported databases only)
* `identity` - use an identity column from the database (auto-increment)
* `native` - use identity, sequence, or an optimized algorithm depending on the underlying database capabilities
* `select` - select the next value from the column denoted in `selectKey`
* `uuid` / `uuid2` - use Hibernate's UUID generation
* `guid` - use the database's native GUID generation

The full list of built-in generator names is: `assigned`, `foreign`, `guid`, `identity`, `increment`, `native`, `select`, `sequence`, `sequence-identity`, `uuid`, `uuid2`. Any other value is treated as the fully-qualified Java class name of a custom generator on the classpath; an unrecognized value throws a `BoxRuntimeException` at mapping time.

{% hint style="warning" %}
The legacy CFML/Lucee generator name `seqhilo` is **not** a recognized built-in generator in bx-orm. Use `generator="sequence"` with a `sequence` attribute naming your database sequence instead.
{% endhint %}

{% hint style="info" %}
See the [Hibernate 3.3 Mapping Reference Documentation](https://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-id-generator) for more information on these and other generator types.
{% endhint %}


# Relationships

Entity relationships let you define an association between two entity types.

Every relationship property must define the state of the relationship. In each case, the relationship property is defined in an entity which represents the "left" side of the relationship. If you bring a `Posts` relationship into the `User` entity, then from the `User` entity, the `User` is the left side of the relationship, and `Posts` is the right.

## One To One

A one to one relationship couples a single row on the left side to a single row on the right side:

```js
property name      = "Address"
         fieldtype = "one-to-one"
         class     = "Address";
```

One to one relationships can be seen as simply extending the entity with additional information. Since there is no possibility of multiple records per entity instance, it may be worthwhile to set `lazy=false` to fetch the related entity along with any entity load:

```js
property name      = "Address"
         fieldtype = "one-to-one"
         class     = "Address"
         lazy      = "false";
```

This one-to-one relationship can be visualized as follows:

![One User has one Address, an entity relationship diagram](https://146896706-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FpE0DivA4DpsOBQKEddvG%2Fuploads%2Fgit-blob-d40df3bbf35479495ffb5e1c155f4caad22acb83%2Fentity-relationship-one-to-one.png?alt=media)

### Constrained (`constrained`)

The `constrained` attribute is specific to `one-to-one` relationships. When set to `true`, it declares that the owning entity's primary key has a foreign-key constraint pointing to the associated entity's primary key — in other words, the associated record must exist:

```js
property name        = "userProfile"
         fieldtype   = "one-to-one"
         class       = "UserProfile"
         constrained = "true";
```

Use `constrained=true` when the `UserProfile` table's primary key is also a foreign key back to the `User` table (a shared-primary-key one-to-one). Without it, Hibernate treats the association as a simple reference with no FK constraint generated in the schema.

## One To Many

A one to many relationship couples a single row on the left side (the "one") to multiple rows on the right side (the "many"):

```js
class entityName="User" persistent="true"{
    property name      = "posts"
             fieldtype = "one-to-many"
             class     = "Post"
             fkcolumn  = "author_id";
}
```

You'll normally want to set `lazy="true"` to (for example) avoid fetching every Post on a User:

```js
property name      = "posts"
         fieldtype = "one-to-many"
         class     = "Post"
         lazy      = "true"
         fkcolumn  = "author_id";
```

![One user writes many Posts, an entity relationship diagram](https://146896706-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FpE0DivA4DpsOBQKEddvG%2Fuploads%2Fgit-blob-bd7db89d351739099a9f665c3b1de46af4e120bd%2Fentity-relationship-one-to-many.png?alt=media)

## Many To One

A many to one relationship couples multiple rows on the left side (the "many") to a single row on the right side( the "one"):

```js
property name      = "Authors"
         fieldtype = "many-to-one"
         class     = "User"
         fkcolumn  = "author_id";
```

Thus, a single Post can have only one Author... but an Author (or a User, really) can have many Posts.

![Many Posts are written by one User, an entity relationship diagram](https://146896706-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FpE0DivA4DpsOBQKEddvG%2Fuploads%2Fgit-blob-f2fc398fcff16871ff96b77dc974ad8d763a5620%2Fentity-relationship-many-to-one.png?alt=media)

## Many To Many

A many to many relationship allows each entity to relate to multiple rows on the opposite side. A good example might be the author/book relationship. Each book can have multiple authors, and each author may write multiple books:

```js
// Author.bx
property name      = "books"
         fieldtype = "many-to-many"
         class     = "Book"
         linktable = "author_books_link";
```

The `linktable` attribute is required on a `many-to-many` property to set the location for storing join records. You can further alter the storage location via `linkschema` and `linkcatalog`:

```js
property name        = "authors"
         fieldtype   = "many-to-many"
         class       = "Author";
         linkschema  = "blog"
         linkcatalog = "dbo";
```

![Many Authors write Many Books, an entity relationship diagram](https://146896706-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FpE0DivA4DpsOBQKEddvG%2Fuploads%2Fgit-blob-43671360b57e12f60b92d0223dc970669d222081%2Fentity-relationship-many-to-many.png?alt=media)

### Singular Name

On many\* relationships like `one-to-many`, `many-to-one`, etc., you'll be manipulating the full set of items via the property name: `hasAuthors()`, `setAuthors()`, etc. However, this plural terminology becomes weird when used on a single item addition or removal, such as `addAuthors( Author )`. For this reason, you can define a `singularName=STRING` attribute to clean up your entity manipulation:

```js
property name         = "Authors"
         singularName = "Author"
         fieldtype    = "many-to-one"
         class        = "User";
```

### Lazy Loading

The `lazy` attribute controls **when** Hibernate fetches the related data — immediately when the owning entity is loaded, or deferred until the data is actually accessed. Choosing the right strategy can have a significant impact on performance.

| Value   | Applies to                              | Behaviour                                                                                                                                               |
| ------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `false` | all                                     | Related data is fetched immediately in the same SQL query (eager loading).                                                                              |
| `true`  | all                                     | Related data is fetched lazily; Hibernate issues a separate SQL query only when the association is first accessed.                                      |
| `proxy` | to-one (`many-to-one`, `one-to-one`)    | Like `true`, but the related entity is replaced with a lightweight proxy object. The real entity is loaded only when a non-identifier getter is called. |
| `extra` | to-many (`one-to-many`, `many-to-many`) | Like `true`, but even more granular — aggregate operations (`size()`, `contains()`, etc.) are resolved without loading the full collection.             |

#### `lazy=false` — Eager Loading

Eager loading fetches the association in the same query as the parent entity. This is most useful for to-one relationships where the related data is almost always needed:

```js
property name      = "Address"
         fieldtype = "one-to-one"
         class     = "Address"
         lazy      = "false";
```

Avoid using `lazy=false` on to-many collections — fetching large collections eagerly can significantly inflate query result sets.

#### `lazy=true` — Lazy Loading

Related data is not fetched until you first access it. A separate SQL query is issued at that point:

```js
property name      = "posts"
         fieldtype = "one-to-many"
         class     = "Post"
         lazy      = "true"
         fkcolumn  = "author_id";
```

For to-one relationships, `lazy=true` behaves identically to `lazy=proxy` when the application-level `proxyLazyLoading` setting is enabled (see below).

#### `lazy=proxy` — Proxy-Based Lazy Loading

Only valid on to-one relationships (`many-to-one`, `one-to-one`). Hibernate returns a proxy object in place of the real entity. The proxy holds the primary key so that identity checks work without hitting the database; the real entity is loaded only when you call a non-identifier getter:

```js
property name      = "manufacturer"
         fieldtype = "many-to-one"
         class     = "Manufacturer"
         fkcolumn  = "FK_manufacturer"
         lazy      = "proxy";
```

This is the most efficient lazy strategy for to-one associations. When the `proxyLazyLoading` application setting is `true`, BoxLang ORM automatically upgrades `lazy=true` to `lazy=proxy` for all to-one properties (see below).

#### `lazy=extra` — Extra Lazy Collection Loading

A more granular form of lazy loading for to-many collections. Aggregate operations on the collection (checking `size()`, calling `contains()`, etc.) are resolved with targeted SQL without loading the full collection into memory:

```js
property name      = "posts"
         fieldtype = "one-to-many"
         class     = "Post"
         lazy      = "extra"
         fkcolumn  = "author_id";
```

Use `lazy=extra` when you frequently need collection metadata (e.g. counts) but rarely iterate over the full set.

#### `proxyLazyLoading` Application Setting

The `proxyLazyLoading` boolean in your `Application.bx` ORM settings controls whether `lazy=true` is automatically promoted to `lazy=proxy` for **to-one** relationships at mapping time.

| Setting                    | Default                                                                       |
| -------------------------- | ----------------------------------------------------------------------------- |
| `proxyLazyLoading = false` | `lazy=true` on a to-one stays as Hibernate `lazy=true` (standard lazy fetch)  |
| `proxyLazyLoading = true`  | `lazy=true` on a to-one is rewritten to `lazy=proxy` (proxy-based lazy fetch) |

```js
// Application.bx
this.ormSettings = {
    proxyLazyLoading : true
};
```

> **Note:** `proxyLazyLoading` defaults to `false` in BoxLang ORM to match Adobe ColdFusion and Lucee behaviors. If you are migrating from ACF or Lucee and rely on proxy-based lazy loading, you must explicitly set `proxyLazyLoading = true`, or install `bx-compat-cfml` which restores the legacy default.

### Cascade

The `cascade` attribute controls which persistence operations performed on the owning entity are automatically propagated to the associated entity or collection. Without a cascade setting, you must explicitly save, delete, or update each related entity yourself.

| Value         | Behaviour                                                                          |
| ------------- | ---------------------------------------------------------------------------------- |
| `none`        | No operations are cascaded. Each entity must be persisted independently. (Default) |
| `all`         | All operations below are cascaded.                                                 |
| `save-update` | `EntitySave()` on the owner also saves or updates the related entity.              |
| `persist`     | JPA-style alias for `save-update`.                                                 |
| `merge`       | Merging the owner into the session also merges the related entity.                 |
| `delete`      | Deleting the owner also deletes the related entity.                                |
| `remove`      | JPA-style alias for `delete`.                                                      |
| `refresh`     | Refreshing the owner from the database also refreshes the related entity.          |
| `evict`       | Evicting the owner from the session cache also evicts the related entity.          |
| `lock`        | Locking the owner into the session also locks the related entity.                  |
| `replicate`   | Replicating the owner also replicates the related entity.                          |

You can combine multiple values as a comma-separated string:

```js
property name      = "posts"
         fieldtype = "one-to-many"
         class     = "Post"
         fkcolumn  = "author_id"
         cascade   = "save-update,delete";
```

With `cascade="save-update,delete"`, calling `EntitySave( user )` will automatically persist any new or modified `Post` objects in the collection, and calling `EntityDelete( user )` will delete all of the user's posts first.

> **Warning:** Use `cascade="all"` or `cascade="delete"` carefully on large collections. Deleting a `User` with thousands of posts will issue a DELETE for each one individually unless you configure bulk operations at the database level.

### Fetch Strategy

The `fetch` attribute controls *how* Hibernate retrieves the association when it does load — as a SQL JOIN in the same query, or as a separate SELECT:

| Value    | Behaviour                                                                          |
| -------- | ---------------------------------------------------------------------------------- |
| `select` | Hibernate issues a separate SELECT query to load the association. (Default)        |
| `join`   | Hibernate uses a SQL JOIN to load the association in the same query as the parent. |

```js
property name      = "manufacturer"
         fieldtype = "many-to-one"
         class     = "Manufacturer"
         fkcolumn  = "FK_manufacturer"
         fetch     = "join";
```

`fetch=join` forces eager loading regardless of the `lazy` setting and is most useful on to-one associations where the related data is almost always needed. Avoid it on to-many collections, as it can multiply the result-set rows.

### Ordering Collections (`orderBy`)

The `orderBy` attribute applies a SQL `ORDER BY` clause whenever Hibernate loads a to-many collection. The value is a raw SQL fragment:

```js
property name      = "posts"
         fieldtype = "one-to-many"
         class     = "Post"
         fkcolumn  = "author_id"
         orderBy   = "created_at DESC";
```

The collection returned from `getPosts()` will always be sorted by `created_at` descending. This is applied at the database level, not in memory.

### Filtering Collections (`where`)

The `where` attribute applies a fixed SQL `WHERE` condition to a collection, restricting which rows are ever included. The value is a raw SQL fragment (not HQL):

```js
property name      = "publishedPosts"
         fieldtype = "one-to-many"
         class     = "Post"
         fkcolumn  = "author_id"
         where     = "status = 'published'";
```

`getPosts()` will only ever return rows where `status = 'published'`. This is useful for modelling a filtered view of a collection without a separate entity query.

### Inverse and Bidirectional Relationships

When you model a relationship from both sides (e.g. `User` has `posts` and `Post` has `author`), only one side should "own" the foreign key and be responsible for writing it to the database. The other side is the **inverse** side and should be marked accordingly to avoid Hibernate attempting to update the join column twice.

Use `inverse=true` to mark a collection as the non-owning side:

```js
// User.bx — inverse side
property name      = "posts"
         fieldtype = "one-to-many"
         class     = "Post"
         fkcolumn  = "author_id"
         inverse   = "true";

// Post.bx — owning side (holds the FK column)
property name      = "author"
         fieldtype = "many-to-one"
         class     = "User"
         fkcolumn  = "author_id";
```

Alternatively, use `mappedBy` on the collection to name the property on the child entity that owns the join:

```js
// User.bx
property name      = "posts"
         fieldtype = "one-to-many"
         class     = "Post"
         mappedBy  = "author";
```

Both `inverse=true` and `mappedBy` tell Hibernate the same thing: this collection side does not manage the foreign key. For `one-to-many` / `many-to-one` pairs, always mark the collection side as inverse (or use `mappedBy`). For `many-to-many`, pick one side.

### Batch Size (`batchsize`)

The `batchsize` attribute overrides the global `defaultBatchSize` ORM setting for this specific collection, controlling how many collections Hibernate fetches in a single round-trip when multiple parent entities are loaded:

```js
property name      = "posts"
         fieldtype = "one-to-many"
         class     = "Post"
         fkcolumn  = "author_id"
         lazy      = "true"
         batchsize = "50";
```

If you load 100 `User` entities and then access each one's `posts`, Hibernate will fetch them in batches of 50 rather than issuing 100 individual SELECT queries.

When no per-property `batchsize` is set, Hibernate falls back to the application-wide `defaultBatchSize` ORM setting (see [Configuration](https://bxorm.ortusbooks.com/getting-started/configuration)). BoxLang ORM defaults `defaultBatchSize` to `25`, while Adobe ColdFusion and Lucee both historically default to `16`. If you are migrating from ACF/Lucee and want matching batch-fetch behavior, set `defaultBatchSize=16` in your `this.ormSettings`, or install `bx-compat-cfml` which restores the legacy default.

## Relationship Methods

When you define a relationship property, a number of methods are automatically generated in each relationship entity instance which allow you to access and manipulate the relationship data.

| Method                            | Description                                          | Relationship types            |
| --------------------------------- | ---------------------------------------------------- | ----------------------------- |
| `has<PropertyName>()`             | Returns true if the relationship contains any items. | All                           |
| `add<PropertyName>( entity1 )`    | Add an entity instance to the relationship.          | `one-to-many`, `many-to-many` |
| `remove<PropertyName>( entity1 )` | Removes one or more entities from the relationship.  | `one-to-many`, `many-to-many` |

These method signatures are as follows:

```java
public boolean function hasPosts();
// returns `this` for method chaining
public component function addPosts( required any postItem );
// returns `this` for method chaining
public component function removePosts( required any postItem );
```

### One-To-One Example

The following relationship definition defines a `Contact` property on a `User` entity:

```java
property name="Contact"
    fieldtype="one-to-one"
    class="Contact";
```

Since this is a one-to-one relationship, *only the `hasContact()` method is generated*:

* `hasContact()`

Use the property accessor methods `getContact()` and `setContact()` to access and modify the relationship.

### One-To-Many Example

The following relationship definition defines a `posts` property on a `User` entity:

```java
property name="posts"
    fieldtype="one-to-many"
    class="Post"
    lazy="true";
```

Since this is a one-to-many relationship, the following methods are generated:

* `hasPosts()`
* `addPosts()`
* `removePosts()`

### Singular Name

We can set a `singularName` attribute to change the `addPosts()` and `removePosts()` methods to `addPost()` and `removePost()`:

```java
property name="posts"
    singularName="post"
    fieldtype="one-to-many"
    class="Post"
    lazy="true";
```

This will generate the following methods:

* `hasPosts()`
* `addPost()`
* `removePost()`

Note that the `hasPosts()` method remains plural since it checks for the existence of any posts in the relationship.


# Type Conversion

How BoxLang's dynamic types are bridged to JDBC column types

BoxLang is dynamically typed, but JDBC and Hibernate expect a specific Java type for every column. bx-orm bridges the two using a set of built-in JPA `AttributeConverter` classes, applied automatically based on each property's `ormType`.

## How It Works

When bx-orm generates the Hibernate mapping XML for a property, it normalizes the property's `ormType` value (folding aliases like `big_decimal`/`bigdecimal`, or `date`/`datetime`, down to a canonical name) and, for most properties, wires up a matching converter:

| `ormType` values (aliases folded)                    | Canonical type | Converter used                          |
| ---------------------------------------------------- | -------------- | --------------------------------------- |
| `string`, `varchar`, `nvarchar`                      | `string`       | `StringConverter`                       |
| `bigdecimal`, `big_decimal`, `big-decimal`           | `bigdecimal`   | `BigDecimalConverter`                   |
| `biginteger`, `big_integer`, `big-integer`, `bigint` | `biginteger`   | `BigIntegerConverter`                   |
| `integer`, `int`                                     | `integer`      | `IntegerConverter`                      |
| `long`                                               | `long`         | `LongConverter`                         |
| `tinyint`, `tinyinteger`                             | `short`        | `ShortConverter`                        |
| `numeric`, `number`, `decimal`                       | `double`       | `DoubleConverter`                       |
| `float`                                              | `float`        | `FloatConverter`                        |
| `bit`, `bool`                                        | `boolean`      | `BooleanConverter`                      |
| `yes-no`, `yesno`, `yes_no`                          | `yes_no`       | `BooleanConverter`                      |
| `true-false`, `truefalse`, `true_false`              | `true_false`   | `BooleanConverter`                      |
| `eurodate`, `usdate`, `date`, `datetime`             | `timestamp`    | `DateTimeConverter`                     |
| `time`                                               | `time`         | `TimeConverter`                         |
| `blob`, `byte[]`                                     | `binary`       | *(none - stored as raw binary)*         |
| `char`, `nchar`                                      | `character`    | *(none - stored as a single character)* |
| `clob`                                               | `text`         | *(none - stored as text)*               |

Each converter's job is to translate a BoxLang dynamic value into the JDBC type Hibernate expects on the way into the database, and back into a BoxLang-friendly value on the way out - using BoxLang's own type casters (e.g. `DateTimeCaster`, so a `DateTime` object round-trips correctly regardless of what dynamic type was assigned to the property in memory).

{% hint style="info" %}
**Identifier and version properties skip converters.** A property with `fieldtype="id"` or `fieldtype="version"` is written using its plain Hibernate basic type, not one of the converters above. This keeps primary key and optimistic-locking columns on Hibernate's native type handling.
{% endhint %}

## Custom Converters

There is currently no supported mechanism for registering your own `AttributeConverter` for a property - the converters above are applied automatically based on `ormType` and cover the standard Hibernate basic types. If you need a database column type not covered here, use `sqlType` to control the generated DDL, or reach for a [custom Hibernate config](https://bxorm.ortusbooks.com/getting-started/configuration/custom-hibernate-config) / `hibernateProperties` for engine-level tuning.

See [Properties](https://bxorm.ortusbooks.com/modeling/properties#orm-type) for the full list of `ormType` values you can set on a property.


# Queries and HQL

Query your entities with HQL or simple filter-based lookups

bx-orm gives you two ways to query entities: **HQL** (Hibernate Query Language) for anything beyond a simple lookup, and **filter-based queries** for quick equality lookups without writing a query string at all.

## HQL Queries

HQL looks like SQL, but it queries **entity names and properties**, not table and column names. Use [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery) to run one:

```js
var toyotas = ORMExecuteQuery(
    hql: "FROM Auto WHERE make = :make",
    params: { make: "Toyota" }
);
```

### Parameters

Bind parameters using either named parameters (`:name`, with a struct of params) or positional parameters (`?`, with an array of params) - don't mix the two styles in the same query:

```js
// Named
ORMExecuteQuery( hql: "FROM Auto WHERE make = :make", params: { make: "Toyota" } );

// Positional
ORMExecuteQuery( hql: "FROM Auto WHERE make = ?", params: [ "Toyota" ] );
```

An array-valued parameter is expanded into a comma-separated list of placeholders automatically, so `IN` clauses work as expected:

```js
ORMExecuteQuery(
    hql: "FROM Auto WHERE make IN (:makes)",
    params: { makes: [ "Toyota", "Honda", "Ford" ] }
);
```

From 1.7.3, each value is converted to the type of the property it is compared with, so a string from a form or URL (`"1"`) or a decimal binds to an integer property. Whole-number types only take whole numbers, and a value that cannot be converted (`"abc"` for an integer) still fails. See [Typed Values from Forms and URLs](https://bxorm.ortusbooks.com/release-history/whats-new-1.7.3#typed-values-from-forms-and-urls).

### Options

Pass a struct of options to control pagination, caching, and result shape:

| Option       | Description                                                                  |
| ------------ | ---------------------------------------------------------------------------- |
| `unique`     | Return a single object (or `null`) instead of an array                       |
| `offset`     | Skip this many results                                                       |
| `maxResults` | Limit the number of results returned                                         |
| `readOnly`   | Load results as read-only (not tracked for dirty-checking)                   |
| `datasource` | Run the query against a specific datasource, instead of the entity's default |

### Update and Delete Queries

HQL `UPDATE` and `DELETE` statements are executed directly against the database (bypassing the second-level cache and entity lifecycle events), and return the number of affected rows instead of a result list:

```js
var rowsUpdated = ORMExecuteQuery( hql: "UPDATE Auto SET discontinued = true WHERE make = :make", params: { make: "Yugo" } );
```

## HQL in the Query Component and queryExecute()

{% hint style="info" %}
Available from bx-orm 1.7.3.
{% endhint %}

`<bx:query>` (`<cfquery>` in CFML templates) and `queryExecute()` run HQL when you set `dbtype="hql"`. They return the same result as [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery): an array of entities, or an array of rows for a projection. They do not return a query object.

```html
<bx:query name="toyotas" dbtype="hql">
    FROM Auto WHERE make = <bx:queryparam value="#form.make#" sqltype="varchar">
</bx:query>
```

```js
var toyotas = queryExecute(
    "FROM Auto WHERE make = :make",
    { make: "Toyota" },
    { dbtype: "hql" }
);
```

* `<bx:queryparam>` (`<cfqueryparam>`) in the body binds a positional parameter. With a `sqltype` (`cfsqltype`) the value is cast first, so an id that arrives as a string from a form matches an integer property. `list="true"` binds a list for `IN ( ... )`.
* `params` binds named (struct) or positional (array) parameters, as in `ORMExecuteQuery()`.
* `ormoptions` takes the [query options](#options), such as `maxResults`, `offset`, `readOnly` and `unique`. `maxrows`, `timeout` and `datasource` apply too.
* `result` gets a struct with `sql` (the HQL), `recordCount`, `executionTime` and `cached`.

Without `dbtype="hql"`, the query component and `queryExecute()` run SQL as usual.

## Filter-Based Queries

For simple equality lookups, skip HQL entirely and use [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload) with a struct of filter criteria:

```js
// All Toyotas
var toyotas = entityLoad( "Auto", { make: "Toyota" } );

// A single, unique Toyota
var toyota = entityLoad( "Auto", { make: "Toyota" }, true );

// With pagination and ordering
var page = entityLoad( "Auto", { make: "Toyota" }, "model asc", { offset: 0, maxResults: 25 } );
```

Every key in the filter struct must be a valid persistent property name on the entity; each key/value pair is combined with the others using `AND` equality. From 1.7.3, filter values are converted to each property's type, so `{ id: url.id }` works when `url.id` is a string. This only supports equality checks - reach for HQL as soon as you need `LIKE`, ranges, joins, or `OR` logic.

[EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample) works the same way, but takes a sample entity instance instead of a struct:

```js
var sample = entityNew( "Auto", { make: "Toyota" } );
var toyotas = entityLoadByExample( sample );
```

## Converting Results to a Query Object

If you need to hand entity results to code that expects a BoxLang `Query` object (e.g. for a report or grid), use [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery):

```js
var toyotas = entityLoad( "Auto", { make: "Toyota" } );
var qryToyotas = entityToQuery( toyotas );
```

The query holds the entity's plain properties only, never relationship data. See [Entities as Queries](https://bxorm.ortusbooks.com/usage/queries).

## Where Queries Run

Both HQL and filter-based queries execute against the current request's Hibernate session - see [Session Management](https://bxorm.ortusbooks.com/usage/session-management) for how that session is opened and when it flushes. If `secondaryCacheEnabled` is on for an entity, HQL queries respect the query cache automatically; see [Caching](https://bxorm.ortusbooks.com/usage/caching).


# Entities as Queries

Turn entities into a BoxLang query for reports, grids and exports

When code expects a BoxLang `Query` object (a report, a data grid, a CSV export), convert your entities with [entityToQuery()](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery):

```js
vehicles    = entityLoad( "Vehicle", { make : "Ford" } );
qryVehicles = entityToQuery( vehicles );

// one entity gives a one-row query
qryVehicle = entityToQuery( entityLoadByPK( "Vehicle", "1HGCM82633A123456" ) );
```

## What goes in the query

One row per entity, one column per **plain persistent property**:

| Included                                                                  | Not included                                                              |
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| The id property                                                           | Relationships: `one-to-one`, `one-to-many`, `many-to-one`, `many-to-many` |
| Column properties                                                         | Non-persistent properties (`persistent="false"`)                          |
| Version and timestamp properties                                          |                                                                           |
| Properties inherited from a persistent parent entity or mapped superclass |                                                                           |

{% hint style="warning" %}
**The result query will not contain any relation data.** Relationship properties do not appear as columns at all, not even as empty ones, and no association is loaded. This matches Adobe ColdFusion and Lucee. Before 1.7.1, bx-orm added relationship columns that were always `null`.
{% endhint %}

Given this entity:

```js
class persistent="true" entityName="Vehicle" {
    property name="vin" fieldtype="id" generator="assigned";
    property name="make";
    property name="model";
    property name="manufacturer" fieldtype="many-to-one" cfc="Manufacturer" fkcolumn="FK_manufacturer";
    property name="features" fieldtype="many-to-many" cfc="Feature" linktable="vehicle_features";
}
```

`entityToQuery( vehicles )` returns the columns `vin`, `make` and `model`. There is no `manufacturer` or `features` column.

## Arrays and the entity name

* An array becomes one row per entity. All entities in the array must be of the same type.
* The entity name is read from the first entity. Pass it as the second argument to skip that lookup, or to pick the entity whose columns you want with inheritance mappings.
* An empty array with an entity name gives an empty query with that entity's columns. Without a name it gives an empty query with a single `id` column.

```js
qry = entityToQuery( entityLoad( "Vehicle", { make : "Honda" } ), "Vehicle" );
qry = entityToQuery( [], "Vehicle" ); // 0 rows, columns vin, make, model
```

## Need related data?

Read it from the entity's relationship getters (for example `vehicle.getManufacturer().getName()`) and add it to the query yourself, or select the related values with an HQL `select` through [ormExecuteQuery()](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery). See [Queries and HQL](https://bxorm.ortusbooks.com/usage/querying).

## Related

* [entityToQuery()](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [Queries and HQL](https://bxorm.ortusbooks.com/usage/querying)


# Events

Easily run actions on entity insertion, update, and more with event listeners

Hibernate ORM allows reacting to various events in the session lifecycle such as `onPreInsert`, `onPostUpdate`, `onFlush`, etc. You can enable event handling in bx-orm by setting `eventHandling` to `true` in your `this.ormSettings` struct:

```js
this.ormSettings = {
    eventHandling: true
};
```

This will enable two different event listener types for listening to Hibernate events:

* Listen to all events across all entities via the [global event handler](#global-event-handler)
* Listen to specific events on a specific entity via [entity event handler](#entity-event-handler) methods

## Global Event Handler

To use a global event handler, you must set a path to the global event handler using the `eventHandler` setting:

```js
this.ormSettings = {
    eventHandling: true,
    eventHandler : "path/to/global/EventHandler.bx"
};
```

The `EventHandler.bx` must then contain function definitions matching the ORM events you wish to listen for.

Currently, the available event names are:

* `onFlush`
* `preLoad`
* `postLoad`
* `preInsert`
* `postInsert`
* `preUpdate`
* `postUpdate`
* `preDelete`
* `onDelete`
* `postDelete`
* `onEvict`
* `onClear`
* `onDirtyCheck`
* `onAutoFlush`

Here's an example of an EventHandler configured for all events:

```js
class {

	public class function init(){
		return this;
	}

	function onFlush( entity ) {
		// Do something upon function call
	}

	function preLoad( entity ){
		// Do something upon function call
	}
	function postLoad( entity ){
		// Do something upon function call
	}

	function preInsert( entity ){
		// Do something upon function call
	}
	function postInsert( entity ){
		// Do something upon function call
	}

	function preUpdate( entity, Struct oldData  ){
		// Do something upon function call
	}
	function postUpdate( entity ){
		// Do something upon function call
	}

	function preDelete( entity ){
		// Do something upon function call
	}	
	function onDelete( entity ) {
		// Do something upon function call
	}
	function postDelete( entity ) {
		// Do something upon function call
	}

	function onEvict() {
		// Do something upon function call
	}
	function onClear( entity ) {
		// Do something upon function call
	}
	function onDirtyCheck( entity ) {
		// Do something upon function call
	}
	function onAutoFlush( entity ) {
		// Do something upon function call
	}
}
```

## Entity Event Handler

You can also listen to events on a specific entity at the entity level by adding methods to the entity (class) itself:

```js
class persistent="true"{
	function preInsert( entity ){
		setDateCreated( now() );
	}
	function preUpdate( entity ){
		setDateModified( now() );
	}
}
```

{% hint style="info" %}
Note that only events related to a specific entity will fire upon that entity. For example, you cannot listen to `onFlush` in an entity event handler because a flush is not tied to any one entity.
{% endhint %}

Here is the full list of event types which can be listened to in entity event listeners:

* `preLoad`
* `postLoad`
* `preInsert`
* `postInsert`
* `preUpdate`
* `postUpdate`
* `preDelete`
* `postDelete`

{% hint style="info" %}
`onDelete` is only available in the [global event handler](#global-event-handler), not as an entity-level method - it fires once per delete operation, before Hibernate has resolved which entity persister to use.
{% endhint %}

{% hint style="info" %}
Changes you make to the entity inside `preInsert` or `preUpdate` (either globally or at the entity level) are written back into the values Hibernate persists - these are the two events where mutating the entity actually affects what gets saved.
{% endhint %}


# Observability

Listen to ORM queries, flushes and failures from interceptors, and read Hibernate statistics

bx-orm announces events for SQL, flushes and failures so tools (debuggers, monitors, profilers) can listen instead of reaching into Hibernate. Register a normal BoxLang interceptor for the event names below.

There is no cost when nothing is listening. JDBC objects are only wrapped when a listener exists at the moment a connection is acquired, and payloads are built lazily.

## Events

| Event            | Fires                                                                                               | Payload                                                                  |
| ---------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `onORMQuery`     | After each JDBC statement. Selects fire when the result set is closed, once the row count is known. | See below                                                                |
| `onORMFlush`     | After each Hibernate session flush.                                                                 | `inserts`, `updates`, `deletes`, `elapsedNanos`, `datasource`, `appName` |
| `onORMException` | When a statement fails.                                                                             | `error`, `sql`, `datasource`, `appName`                                  |

### `onORMQuery` payload

| Key            | Description                                                                                                   |
| -------------- | ------------------------------------------------------------------------------------------------------------- |
| `sql`          | The SQL text sent to the driver.                                                                              |
| `kind`         | `select`, `insert`, `update`, `delete`, `ddl` or `other`.                                                     |
| `elapsedNanos` | Execution time in nanoseconds. Excludes time spent reading rows.                                              |
| `rows`         | Rows returned for selects, rows affected for DML, `-1` when unknown (for example DDL).                        |
| `datasource`   | The datasource name.                                                                                          |
| `appName`      | The unique ORM application name, as used by `ORMService.getORMApp()`.                                         |
| `hql`          | The HQL being run, when the statement came from `ormExecuteQuery()`. Otherwise `null`.                        |
| `entityName`   | The entity being loaded, when the statement came from `entityLoad()` or `entityLoadByPK()`. Otherwise `null`. |
| `error`        | The `Throwable` when the statement failed, otherwise `null`.                                                  |
| `params`       | Ordered array of bound parameter values. Only present when `announceQueryParams` is `true`.                   |

A failed statement announces `onORMQuery` with `error` set, and `onORMException`. This includes SQL the database rejects while the statement is being prepared.

Startup DDL (for example `dbcreate="dropcreate"`) is announced too, as long as the listener is registered before the application starts.

### `onORMFlush` counts

`inserts`, `updates` and `deletes` count the statements run during the flush, not entities. JDBC batching can make them differ from the number of entities changed.

### Example

```javascript
// OrmWatcher.bx
class {

    function onORMQuery( data ) {
        // 100 ms
        if ( data.elapsedNanos > 100000000 ) {
            writeLog( text="Slow ORM #data.kind#: #data.sql#", type="warning" );
        }
    }

    function onORMException( data ) {
        writeLog( text="ORM failure on #data.datasource#: #data.error.getMessage()#", type="error" );
    }

}
```

Register it with `boxRegisterInterceptor()`, naming the events it listens to:

```javascript
boxRegisterInterceptor(
    interceptor : new OrmWatcher(),
    points      : [ "onORMQuery", "onORMException" ]
);
```

## Settings

Set these in `this.ormSettings`. Both default to `false`.

| Setting               | Description                                                                                                          |
| --------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `announceQueryParams` | Include bound parameter values in `onORMQuery`. Values can be sensitive, so they are never announced unless you ask. |
| `generateStatistics`  | Collect Hibernate statistics at startup, for `ORMService.getStatistics()`. Collection has a small cost.              |

## Statistics

`ORMService.getStatistics( appName )` returns a struct of `appName` and a `datasources` struct with one entry per datasource. When statistics are not collected, each entry is just `{ enabled: false }`.

Statistics can also be switched on and off at runtime with `ORMService.setStatisticsEnabled( appName, enabled )`. Counters start from zero when switched on.

Enabled entries contain: `enabled`, `startTime`, `sessionOpenCount`, `sessionCloseCount`, `flushCount`, `connectCount`, `prepareStatementCount`, `transactionCount`, `successfulTransactionCount`, `queryExecutionCount`, `queryExecutionMaxTime`, `queryExecutionMaxTimeQueryString`, `entityLoadCount`, `entityFetchCount`, `entityInsertCount`, `entityUpdateCount`, `entityDeleteCount`, `collectionLoadCount`, `collectionFetchCount`, `secondLevelCacheHitCount`, `secondLevelCacheMissCount`, `secondLevelCachePutCount`, `queryCacheHitCount` and `queryCacheMissCount`.

## Other ORM events

`ORMPreConfigLoad` and `ORMPostConfigLoad` are now registered as interception points as well. `post_new` is announced when an entity is created.


# Session Management

How bx-orm manages Hibernate Sessions and SessionFactories behind the scenes

bx-orm manages Hibernate state across four layers. Understanding them helps explain behavior you'll run into in practice: why entities loaded in one request aren't visible in another, why a background thread needs its own session, and what actually happens when you call `ormReload()`.

```mermaid
flowchart TD
    subgraph runtime["Lives for the BoxRuntime"]
        Service["ORMService<br/>(one singleton)"]
    end

    subgraph app["Lives for the BoxLang Application"]
        App["ORMApp<br/>(one per Application name)"]
        SF1["Hibernate SessionFactory<br/>(datasource A)"]
        SF2["Hibernate SessionFactory<br/>(datasource B)"]
        App --> SF1
        App --> SF2
    end

    subgraph req["Lives for one request or thread"]
        Ctx["ORMContext"]
        S1["Hibernate Session<br/>(datasource A)"]
        S2["Hibernate Session<br/>(datasource B)"]
        Ctx -->|opened lazily| S1
        Ctx -->|opened lazily| S2
    end

    Service -->|tracks| App
    Ctx -->|looks up| App
    S1 -.built from.-> SF1
    S2 -.built from.-> SF2
```

## ORMService

`ORMService` is a single BoxRuntime-wide service. It keeps a map of every running `ORMApp`, keyed by the BoxLang Application's name, and is responsible for:

* Starting up an `ORMApp` the first time an ORM-enabled application runs (`startupApp()`)
* Looking up the running `ORMApp` for a given context (`getORMAppByContext()`)
* Reloading an application's ORM state (`reloadApp()`, backing the `ormReload()` BIF)
* Shutting down one application (`shutdownApp()`) or all of them when the runtime itself shuts down

## ORMApp

An `ORMApp` represents one BoxLang Application's ORM state, and is built once and reused for the life of that application (until reload or shutdown). On startup it:

1. Discovers entities via `MappingGenerator`, grouped by the datasource each entity belongs to
2. Builds one Hibernate `SessionFactory` per datasource, via `SessionFactoryBuilder`
3. Tracks which datasource is the default (from `this.ormSettings.datasource`)

Everything expensive - entity discovery, XML mapping generation, and Hibernate bootstrapping - happens here, once per application, not per request. This is why `ormSettings.entityPaths` and `generateMappings=false` matter so much for startup performance; see [Performance](https://bxorm.ortusbooks.com/getting-started/performance).

## ORMContext and Hibernate Sessions

Where `ORMApp` is application-scoped, `ORMContext` is scoped to a single request or thread context. It holds the actual Hibernate `Session` objects your code reads and writes through, one per datasource, opened lazily the first time that datasource is touched.

{% hint style="warning" %}
Because a Hibernate `Session` is tied to a single request or thread context, spawning parallel threads (e.g. `array.each(..., true)`) gives each thread its **own** `ORMContext` and its own Hibernate sessions. An entity created with `entityNew()` inside a parallel thread is attached to that thread's session, not the request's - loading, saving, or querying it from the parent request won't see it until it's been persisted and reloaded through the request's own session.
{% endhint %}

When a session is opened, its flush mode depends on `autoManageSession`:

* `autoManageSession = false` (the default): the session is opened in `FlushMode.MANUAL`. Nothing is written to the database until you explicitly call `ormFlush()` or commit a `transaction` block. See [Transactions](https://bxorm.ortusbooks.com/usage/transactions).
* `autoManageSession = true`: Hibernate manages flushing automatically (e.g. before query execution), which is generally discouraged - see the `autoManageSession` setting in [Configuration](https://bxorm.ortusbooks.com/getting-started/configuration).

At the end of the request or thread (or explicitly via `ormCloseSession()`/`ormCloseAllSessions()`), the `ORMContext` is torn down: any active transaction on each open session is committed, then the session is closed. If `flushAtRequestEnd` and `autoManageSession` are both enabled, sessions are flushed first.

## Reloading the ORM (`ormReload()`)

Calling `ormReload()` rebuilds the current application's `ORMApp` - re-discovering entities and re-building every `SessionFactory` - without restarting the BoxLang application itself. The rebuild is ordered carefully to stay safe under concurrent requests:

1. Any open Hibernate sessions for the reloading request are closed first, so they can't hold a reference to a `SessionFactory` that's about to be replaced.
2. The new `ORMApp` (with fresh session factories) is fully built *before* it replaces the old one in the running application map.
3. The old `ORMApp` is swapped out and only then shut down, closing its old `SessionFactory` instances.

This ordering means other requests keep using a valid `ORMApp` throughout the reload, with only a small window where both the old and new session factories briefly coexist.

## Relevant Built-in Functions

| Function                                                                                                                                                                                            | Purpose                                                                |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)                                                                                                            | Get the raw Hibernate `Session` for the current context and datasource |
| [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)                                                                                              | Get the Hibernate `SessionFactory` for a datasource                    |
| [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush) / [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)                               | Flush one or all open sessions                                         |
| [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)                                                                                                        | Detach all entities from the session without flushing                  |
| [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession) / [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions) | Close one or all open sessions for the current context                 |
| [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)                                                                                                                    | Rebuild the ORM application's session factories                        |


# Transactions

Learn transaction management with bx-orm

A transaction is any discrete unit of work used to pool database queries and statements to execute at once. This helps us to prevent a failed update from leaving the database in a broken state.

To denote a transaction, we wrap it in the `transaction{}` tag:

```js
transaction{
    // queries go here
}
```

The transaction will automatically commit (persist) at the end of the transaction block.

{% hint style="warning" %}
**Transaction Scope:** Transaction events are persisted across **ALL** ORM datasources. This means that:

* **Transaction begin** - begins a transaction on every ORM datasource referenced by an ORM entity
* **Transaction commit** - commits changes on every ORM datasource
* **Transaction rollback** - rolls back changes on every ORM datasource
* **Transaction end** - ends the transaction on every ORM datasource

When you initiate a transaction, it affects **all** datasources that have been referenced by ORM entities, not just a single datasource as in normal Boxlang transaction management.
{% endhint %}

## Transaction Rollback

A transaction rollback undoes all changes made within the transaction block and prevents them from being persisted to the database. This is useful when an error occurs or business rules are violated.

### Automatic Rollback on Error

If an exception occurs within a transaction block, the transaction is automatically rolled back:

```js
try {
    transaction {
        var user = entityNew( "User" );
        user.setUsername( "johndoe" );
        entitySave( user );
        
        // This will throw an exception and trigger automatic rollback
        var invalid = entityLoadByPK( "NonExistentEntity", 1 );
    }
} catch ( any e ) {
    // Transaction has been rolled back, user was not saved
    writeOutput( "Error: #e.message#" );
}
```

### Manual Rollback

You can manually trigger a rollback using `transactionRollback()`:

```js
transaction {
    var account = entityLoadByPK( "Account", 1 );
    var newBalance = account.getBalance() - 100;
    
    // Business rule: account balance cannot go negative
    if ( newBalance < 0 ) {
        transactionRollback();
        writeOutput( "Insufficient funds - transaction rolled back" );
    } else {
        account.setBalance( newBalance );
        entitySave( account );
        // Transaction commits automatically at end of block
    }
}
```

The alternative syntax `action="rollback"` is also supported.

## Transaction Commit

A transaction commit persists all changes made within the transaction block to the database. By default, transactions automatically commit when the transaction block completes successfully.

### Automatic Commit

When a transaction block completes without errors or explicit rollback, it will be automatically committed:

```js
transaction {
    // Create a new user
    var user = entityNew( "User" );
    user.setUsername( "janedoe" );
    user.setEmail( "jane@example.com" );
    entitySave( user );
    
    // Create a profile for the user
    var profile = entityNew( "Profile" );
    profile.setUser( user );
    profile.setBio( "Software developer" );
    entitySave( profile );
    
    // Both saves commit together at the end of this block
}
```

### Manual Commit

You can manually commit a transaction using `transactionCommit()` when you need to persist changes before the end of the block:

```js
transaction {
    // First batch of operations
    var batch1 = entityNew( "Batch" );
    batch1.setName( "Batch 1" );
    entitySave( batch1 );
    transactionCommit();
    writeOutput( "Batch 1 committed successfully" );
    
    // Second batch of operations
    var batch2 = entityNew( "Batch" );
    batch2.setName( "Batch 2" );
    entitySave( batch2 );
    transactionCommit();
    writeOutput( "Batch 2 committed successfully" );
}
```

The alternative syntax `action="commit"` is also supported.

{% hint style="warning" %}
**Important:** When you manually commit a transaction using `transactionCommit()`, it effectively closes the current transaction and immediately begins a new one. This means that any subsequent operations within the transaction block will be part of a new transaction context.
{% endhint %}

### Named Transactions

Named transactions allow you to commit or rollback specific transactions when dealing with nested transactions:

```js
transaction name="outer" {
    var customer = entityNew( "Customer" );
    customer.setName( "Acme Corp" );
    entitySave( customer );
    
    transaction name="inner" {
        var invoice = entityNew( "Invoice" );
        invoice.setCustomer( customer );
        invoice.setAmount( 1000.00 );
        entitySave( invoice );
        
        // Commit only the inner transaction
        transactionCommit( "inner" );
    }
    
    // Outer transaction commits automatically
}
```

## Transaction Savepoint

True database savepoints (`SAVEPOINT` / `ROLLBACK TO SAVEPOINT`) are not *currently* supported on ORM transactions - you cannot partially roll back a transaction to an intermediate point.

Nested `transaction` blocks are still tracked internally: when an inner (child) `transaction` block ends, bx-orm flushes the Hibernate session for each active datasource so that its changes are pushed to the database before the outer transaction continues. This keeps nested transaction blocks well-behaved, but it is not a substitute for real savepoint/rollback support.

{% hint style="info" %}
Looking for full ORM savepoint support? [Contact our Support team to consider sponsoring this feature](https://boxlang.io/plans).
{% endhint %}


# Caching

Improve your database performance with secondary caching in Hibernate ORM.

## Secondary Cache

A secondary cache provider is a class which manages a level of caching that is secondary to Hibernate's main caching context - the Hibernate session. A secondary cache enables longer-running cache contexts, more fine-grained control over cache busting, and other performance-related benefits.

The only setting necessary to enable secondary caching is the `secondaryCacheEnabled` setting:

```js
this.ormSettings = {
    secondaryCacheEnabled : true
};
```

To configure the caching, specify the path to an XML cache configuration file in `cacheConfig`:

```js
this.ormSettings = {
    secondaryCacheEnabled: true,
    cacheConfig          : "./config/ehcache.xml"
};
```

This `ehcache.xml` cache configuration then should look something like this:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" name="default">
    <diskStore path="java.io.tmpdir"/>
        <defaultCache
            maxElementsInMemory="10000" eternal="false"
            timeToIdleSeconds="120" timeToLiveSeconds="120"
            maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
            <persistence strategy="localTempSwap"/>
        </defaultCache>
        <cache
            name="Autos"
            maxElementsInMemory="20"
            overflowToDisk="false"
            eternal="true">
        </cache>
</ehcache>
```

## Configure Each Entity Cache

Notice how our `ehcache.xml` defines a default cache configuration?

```xml
<defaultCache
    maxElementsInMemory="10000" eternal="false"
    timeToIdleSeconds="120" timeToLiveSeconds="120"
    maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120"
    memoryStoreEvictionPolicy="LRU">
    <persistence strategy="localTempSwap"/>
</defaultCache>
```

We highly recommend adding a cache configuration for each cacheable entity. This will help you optimize caching, and will silence error logs like the below:

```
WARN: HHH90001006: Missing cache[default-update-timestamps-region] was created on-the-fly. The created cache will use a provider-specific default configuration: make sure you defined one. You can disable this warning by setting 'hibernate.cache.ehcache.missing_cache_strategy' to 'create'
```

Here's a quick example. Say we have an `Autos.bx` persistent class with caching enabled:

```js
class persistent="true" cacheUse="read-write"{
    // persistent properties...
}
```

For this entity, we'll want to create a `<cache></cache>` entry with a `name` attribute that matches the entity name OR our `cacheName` class annotation:

```xml
<cache
    name="Autos"
    maxElementsInMemory="20"
    overflowToDisk="false"
    eternal="true">
</cache>
```

### How the Cache Provider Setting Works

bx-orm bridges Hibernate's JCache (JSR-107) SPI to BoxLang's own `CacheService`, rather than depending on a specific third-party cache library. This means `cacheProvider` selects a **BoxLang cache provider by name**, not a Hibernate/EHCache implementation:

```js
this.ormSettings = {
    secondaryCacheEnabled : true,
    // use the "userCache" provider registered in your CacheBox/CacheService config
    cacheProvider : "userCache"
};
```

* The default, `"BoxCacheProvider"`, uses BoxLang's built-in in-memory cache.
* `"ConcurrentHashMap"` and `"HashTable"` are legacy aliases kept for CFML/Lucee compatibility; both simply resolve to the default BoxLang cache provider.
* Any other value must be the name of a cache provider already registered with BoxLang's `CacheService` (e.g. via CacheBox). If no provider with that name is found, ORM startup throws an error.
* `cacheConfigProperties` lets you pass secondary-cache settings as a BoxLang struct instead of (or alongside) an XML `cacheConfig` file.


# Built-in Functions

bx-orm ships a set of Built-in Functions (BIFs) for working with entities and the underlying Hibernate session. They fall into two groups:

## Entity Functions

| Function                                                                                             | Description                                                                         |
| ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)               | Delete an entity from the database.                                                 |
| [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)       | Check whether an entity is attached to the current ORM session.                     |
| [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)                   | Load an entity or array of entities from the database.                              |
| [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample) | Load entities matching an example entity.                                           |
| [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)           | Load an array of entities by the primary key.                                       |
| [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)                 | Merge the state of the given entity into the current persistence context (session). |
| [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)         | Retrieve an array of entity names for this ORM application.                         |
| [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)           | Retrieve a list of entity names for this ORM application.                           |
| [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)                     | Instantiate a new entity, optionally with a struct of properties.                   |
| [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)               | Reload an entity from the database.                                                 |
| [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)                   | Save the provided entity to the persistence context.                                |
| [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)             | Convert an entity or array of entities to a Query object.                           |

## ORM Session Functions

| Function                                                                                                   | Description                                                                                      |
| ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)               | Clear the Hibernate session for the current context and provided (or default) datasource.        |
| [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)       | Close all Hibernate sessions for the current context on all datasources.                         |
| [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)               | Close the Hibernate session for the current context and provided (or default) datasource.        |
| [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)         | Evict all entity data for a given collection on a given entity type from the second-level cache. |
| [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)                 | Evict all entity data for this entity name from the second-level cache.                          |
| [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)               | Evict all queries from the named or default cache on the named or default datasource.            |
| [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)               | Execute an HQL query with (optional) parameters and specific query options.                      |
| [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)                             | Flush the Hibernate session, synchronizing the in-memory state with the database.                |
| [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)                       | Flush all open Hibernate sessions in the current request.                                        |
| [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion) | Retrieve the installed Hibernate version.                                                        |
| [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)                   | Retrieve the Hibernate Session configured for this datasource or default datasource.             |
| [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)     | Retrieve the Hibernate SessionFactory configured for this datasource or default datasource.      |
| [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)                           | Reload the ORM application.                                                                      |


# EntityDelete

Delete an entity from the database.

Delete operations will cascade to related entities if `cascade` is enabled on the relationship property.

## Method Signature

```
EntityDelete(entity=[class])
```

### Arguments

| Argument | Type    | Required | Description                    | Default |
| -------- | ------- | -------- | ------------------------------ | ------- |
| `entity` | `class` | `true`   | The entity instance to delete. |         |

## Examples

Delete an entity by passing the entity object to `entityDelete()`:

```java
entityDelete( entityLoadByPK( "Vehicle", "1HGCM82633A123456" ) );
```

Note that this operation will also remove associated child entities depending on the `cascade` configuration in the entity property mapping. In this case, we wish a deletion of a blog post to also delete all associated comments:

```java
property
    name="comments"
    cfc="Comment"
    fieldtype="one-to-many"
    inverse="true"
    cascade="delete";
...
entityDelete( entityLoadByPK( "blogPost", "779ccbb8-a444-11eb-ab6f-0290cc502ae3" ) );
```

## Related

* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntityIsAttached

Check whether an entity is attached to the current ORM session.

## Method Signature

```
EntityIsAttached(entity=[Any])
```

### Arguments

| Argument | Type  | Required | Description                   | Default |
| -------- | ----- | -------- | ----------------------------- | ------- |
| `entity` | `Any` | `true`   | The entity instance to check. |         |

## Examples

Check whether a loaded entity is still attached to its datasource's session:

```java
manufacturer = entityLoadByPK( "Manufacturer", 1 );
isAttached   = entityIsAttached( manufacturer );

ormEvictEntity( "Manufacturer" );
isAttached   = entityIsAttached( manufacturer ); // false
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntityLoad

Load an entity or array of entities from the database.

You can pass a struct of query options, including pagination, caching, and sort options.

## Parameters

The `parameters` argument can be used to bind parameters to the SQL query. You can use either an array of binding parameters or a struct of named binding parameters.

## Options

* **`unique`** - Boolean. Specifies whether to retrieve a single, unique item. Default is \`false\`.
* **`ignorecase`** - Boolean. Ignores the case of sort order when set to true. Use only if you specify the sortorder parameter. Defaults to \`false\`.
* **`offset`** - Number. Specifies the pagination offset. Defaults to 0.
* **`maxresults`** - Number. Specifies the maximum number of objects to be retrieved.
* **`cacheable`** - Boolean. Whether the result has to be cached in the secondary cache. Default is \`false\`.
* **`cachename`** - String. Name of the cache in secondary cache.
* **`timeout`** - Number. Specifies the timeout value (in seconds) for the query. No timeout by default.

## Method Signature

```
EntityLoad(entityName=[string], idOrFilter=[any], uniqueOrOrder=[any], options=[struct])
```

### Arguments

| Argument        | Type     | Required | Description                                                                                           | Default |
| --------------- | -------- | -------- | ----------------------------------------------------------------------------------------------------- | ------- |
| `entityName`    | `string` | `true`   | The name of the entity to load.                                                                       |         |
| `idOrFilter`    | `any`    | `false`  | Either the ID of the entity to load, or a struct of filter criteria.                                  |         |
| `uniqueOrOrder` | `any`    | `false`  | Either a boolean indicating whether to return a unique result, or a string/array of order by clauses. |         |
| `options`       | `struct` | `false`  | A struct of options to modify the load operation. See below for supported options.                    |         |

## Examples

## Loading an Entity Array

To load an array of Autos from the database where the `Make` is `Ford`, you would do the following:

```java
var allFords = entityLoad( "Auto", { Make = "Ford" } );
```

By default, all matching records are returned. If you want to paginate the result set, you can pass a struct with query options as the fourth argument:

```java
var firstTenFords = entityLoad(
    "Auto",                         // first arg: entity name
    { Make = "Ford" },              // second arg: criteria struct
    false,                          // third arg: false for "not unique"
    { maxResults = 10, offset = 0 } // fourth arg: option struct
);
```

### Loading Unique Entities

We can also load single, unique entity results by passing `true` in the third argument to indicate that we want a single, unique result. For example, to load an entity named `Auto` with an ID of `123`, you would do the following:

```java
var myEntity = entityLoad( "Auto", 123, true );
```

This will retrieve the entity from the database and populate the `myEntity` variable with its data. If the entity is not found, an error will be thrown.

You can also use the `entityLoad()` function to load an entity by its unique properties, even if they are not the primary key. For example, to load an `Auto` entity with a specific `VIN`, you could do the following:

```java
var myEntity = entityLoad( "Auto", { VIN = "1HGCM82633A123456" }, true );
```

This will search for the `Auto` entity with the specified `VIN` and return it if found.

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntityLoadByExample

Load entities matching an example entity.

## Method Signature

```
EntityLoadByExample(sampleEntity=[any], unique=[boolean])
```

### Arguments

| Argument       | Type      | Required | Description                                                                     | Default |
| -------------- | --------- | -------- | ------------------------------------------------------------------------------- | ------- |
| `sampleEntity` | `any`     | `true`   | Instance of an ORM entity to use as an example for the query.                   |         |
| `unique`       | `boolean` | `false`  | Whether to return a single unique result (true) or an array of results (false). | `false` |

## Examples

Load all matching entities using a sample entity as the filter.

```java
sample = entityNew( "Manufacturer", { name: "Honda" } );
matches = entityLoadByExample( sample );
```

Pass `unique=true` to return a single matching entity:

```java
sample = entityNew( "Manufacturer", { name: "Honda" } );
singleMatch = entityLoadByExample( sample, true );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntityLoadByPK

Load an array of entities by the primary key.

`var myAuto = entityLoadByPK( "Automobile", "1HGCM82633A123456" );`

In Lucee, by default, an array of entities is returned and you must pass a third \`unique=true\` argument to return only a single entity. In BoxLang, only a single entity is returned - matching the Adobe ColdFusion behavior - and no \`unique\` attribute is supported. To return an array of entities, use the \`entityLoad\` BIF.

Composite keys are also supported:

```
 entityLoadByPK( "VehicleType", { make : "Ford", model: "Fusion" } );
 
```

## Method Signature

```
EntityLoadByPK(entity=[String], id=[Any], unique=[String])
```

### Arguments

| Argument | Type     | Required | Description                                                               | Default |
| -------- | -------- | -------- | ------------------------------------------------------------------------- | ------- |
| `entity` | `String` | `true`   | The name of the entity to load.                                           |         |
| `id`     | `Any`    | `true`   | The primary key value, or a struct of key/value pairs for composite keys. |         |
| `unique` | `String` | `false`  | Not implemented. In BoxLang, a single entity is always returned.          |         |

## Examples

### Load by Primary Key

Load entity by primary key:

```java
vehicle = entityLoadByPK( "Vehicle", "1HGCM82633A123456" );
```

### Load by Composite Key

Pass a struct when the entity key is composite.

```java
vehicleType = entityLoadByPK( "VehicleType", { make: "Ford", model: "Fusion" } );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntityMerge

Merge the state of the given entity into the current persistence context (session).

## Method Signature

```
EntityMerge(entity=[Any])
```

### Arguments

| Argument | Type  | Required | Description                   | Default |
| -------- | ----- | -------- | ----------------------------- | ------- |
| `entity` | `Any` | `true`   | The entity instance to merge. |         |

## Examples

```java
vehicle = entityLoadByPK( "Vehicle", "1HGCM82633A123456" );
ormGetSession().detach( vehicle );

vehicle.setModel( "Accord EX" );
entityMerge( vehicle );
ormFlush();
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntityNameArray

Retrieve an array of entity names for this ORM application.

## Method Signature

```
EntityNameArray(delimiter=[String], datasource=[String])
```

### Arguments

| Argument     | Type     | Required | Description                                                                                                          | Default |
| ------------ | -------- | -------- | -------------------------------------------------------------------------------------------------------------------- | ------- |
| `delimiter`  | `String` | `false`  | The delimiter to use between entity names.                                                                           | `,`     |
| `datasource` | `String` | `false`  | The name of the datasource to filter on. If provided, only entities configured for this datasource will be returned. |         |

## Examples

Retrieve names of all entities in the ORM app:

```java
entityNames = entityNameArray();
```

Retrieve entity names for entities under a specific datasource:

```java
entityNames = entityNameArray( datasource = "admin" );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntityNameList

Retrieve an array of entity names for this ORM application.

## Method Signature

```
EntityNameList(delimiter=[String], datasource=[String])
```

### Arguments

| Argument     | Type     | Required | Description                                                                                                          | Default |
| ------------ | -------- | -------- | -------------------------------------------------------------------------------------------------------------------- | ------- |
| `delimiter`  | `String` | `false`  | The delimiter to use between entity names.                                                                           | `,`     |
| `datasource` | `String` | `false`  | The name of the datasource to filter on. If provided, only entities configured for this datasource will be returned. |         |

## Examples

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntityNew

Instantiate a new entity, optionally with a struct of properties.

## Method Signature

```
EntityNew(entityName=[String], properties=[Struct], ignoreExtras=[Boolean])
```

### Arguments

| Argument       | Type      | Required | Description                                                                                                    | Default |
| -------------- | --------- | -------- | -------------------------------------------------------------------------------------------------------------- | ------- |
| `entityName`   | `String`  | `true`   | The name of the entity to create.                                                                              |         |
| `properties`   | `Struct`  | `false`  | A struct of properties to populate on the new entity.                                                          |         |
| `ignoreExtras` | `Boolean` | `false`  | If false, an error will be thrown if properties are provided that do not exist on the entity. Not implemented. |         |

## Examples

### Creating Simple Entities

Creating an instance of an ORM entity is as simple as calling `entityNew()` with the name of the entity you wish to create. For example, to create a new instance of an entity named `Auto`, you would do the following:

```java
var myEntity = entityNew( "Auto" );
```

To populate the entity with initial values, you can pass a struct of properties as the second argument:

```java
var myEntity = entityNew( "Auto", {
    Make = "Toyota",
    Model = "Camry",
    Year = 2020
} );
```

### Ignoring Extra Properties

(Coming soon) By default, `ignoreExtra` is set to `false`, meaning that if you provide properties that do not exist on the entity, an error will be thrown.

For example, this will throw an error if `Color` is not a defined property on the `Auto` entity:

```java
var myEntity = entityNew( "Auto", {
    Make = "Toyota",
    Model = "Camry",
    Year = 2020,
    Color = "Blue"
}, true );
```

To change this behavior, you can set the `ignoreExtra` argument to `true`:

```java
var myEntity = entityNew( "Auto", {
    Make = "Toyota",
    Model = "Camry",
    Year = 2020,
    Color = "Blue"
}, true );
```

This will create the entity and ignore the `Color` property if it does not exist on the `Auto` entity.

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntityReload

Reload an entity from the database.

Will repopulate all persistent properties on the entity with the latest values from the database.

## Method Signature

```
EntityReload(entity=[Any])
```

### Arguments

| Argument | Type  | Required | Description                    | Default |
| -------- | ----- | -------- | ------------------------------ | ------- |
| `entity` | `Any` | `true`   | The entity instance to reload. |         |

## Examples

Reload an entity by passing the entity object directly:

```java
manufacturer = entityLoadByPK( "Manufacturer", 1 );
reloaded = entityReload( manufacturer );
```

Reload all in-session entities by entity name:

```java
manufacturer = entityLoadByPK( "Manufacturer", 1 );
reloaded = entityReload( "manufacturer" );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntitySave

Save the provided entity to the persistence context

## Method Signature

```
EntitySave(entity=[Any], forceinsert=[Boolean])
```

### Arguments

| Argument      | Type      | Required | Description                                                                                     | Default |
| ------------- | --------- | -------- | ----------------------------------------------------------------------------------------------- | ------- |
| `entity`      | `Any`     | `true`   | The entity instance to save.                                                                    |         |
| `forceinsert` | `Boolean` | `false`  | If true, will force an insert operation. Otherwise, a saveOrUpdate operation will be performed. |         |

## Examples

### Save a New Entity

Create a new entity and persist it in one flow.

```java
entitySave( entityNew( "Manufacturer", { name: "Audi Corp", address: "101 Audi Way" } ) );
```

### Force Insert Behavior

Use the second argument when you need explicit insert-oriented behavior.

```java
manufacturer = entityNew( "Manufacturer", { name: "Volvo", address: "123 Main St" } );
entitySave( manufacturer, true );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# EntityToQuery

Convert an entity or array of entities to a Query object.

The query holds one row per entity and one column per id, column, version and timestamp property, inherited ones included.

{% hint style="warning" %}
The result query will not contain any relation data. Relationship properties (`one-to-one`, `one-to-many`, `many-to-one`, `many-to-many`) are not included as columns. See [Entities as Queries](https://bxorm.ortusbooks.com/usage/queries) for details and alternatives.
{% endhint %}

## Method Signature

```
EntityToQuery(entity=[Any], name=[Any])
```

### Arguments

| Argument | Type  | Required | Description                                                                                                        | Default |
| -------- | ----- | -------- | ------------------------------------------------------------------------------------------------------------------ | ------- |
| `entity` | `Any` | `true`   | An instance of an ORM entity or an array of entities. All entities in an array must be of the same type.           |         |
| `name`   | `Any` | `false`  | The name of the entity. Inferred from the (first) entity when omitted. Useful to pick the entity with inheritance. |         |

## Examples

### Convert a Single Entity

Pass one loaded entity to get a single-row query result.

```java
result = entityToQuery( entityLoadByPK( "Vehicle", "1HGCM82633A123456" ), "Vehicle" );
```

### Convert an Entity Array

Pass an array of entities to get one row per entity.

```java
result = entityToQuery( entityLoad( "Vehicle", { Make = "Honda" } ), "Vehicle" );
```

You can also omit the entity name and let the function infer it from the entity type:

```java
result = entityToQuery( entityLoadByPK( "Vehicle", "1HGCM82633A123456" ) );
```

Note that for performance reasons we recommend passing the entity name explicitly.

See [Entities as Queries](https://bxorm.ortusbooks.com/usage/queries) for the full guide.

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMClearSession

Clear the Hibernate session for the current context and provided (or default) datasource

## Method Signature

```
ORMClearSession(datasource=[String])
```

### Arguments

| Argument     | Type     | Required | Description                                                                                                 | Default |
| ------------ | -------- | -------- | ----------------------------------------------------------------------------------------------------------- | ------- |
| `datasource` | `String` | `false`  | The datasource on which to clear the current session. If not provided, the default datasource will be used. |         |

## Examples

Clear the ORM session for the default datasource:

```java
ormClearSession();
```

Since an ORM session is datasource-specific, you can clear a specific session by passing the datasource name:

```java
ormClearSession( "hr" );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMCloseAllSessions

Close all Hibernate sessions for the current context on all datasources.

## Method Signature

```
ORMCloseAllSessions()
```

### Arguments

This function does not accept any arguments

## Examples

```java
mySession = ormGetSession();
alternateSession = ormGetSession( "admin" );

ormCloseAllSessions();
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMCloseSession

Close the Hibernate session for the current context and provided (or default) datasource

## Method Signature

```
ORMCloseSession(datasource=[String])
```

### Arguments

| Argument     | Type     | Required | Description                                                                                                 | Default |
| ------------ | -------- | -------- | ----------------------------------------------------------------------------------------------------------- | ------- |
| `datasource` | `String` | `false`  | The datasource on which to close the current session. If not provided, the default datasource will be used. |         |

## Examples

Close the ORM session for the default datasource:

```java
ormCloseSession();
```

Close the ORM session for a secondary, named datasource:

```java
ormCloseSession( "admin" );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMEvictCollection

Evict all entity data for a given collection on a given entity type from the second-level cache.

## Method Signature

```
ORMEvictCollection(entityName=[String], collectionName=[String], primaryKey=[String])
```

### Arguments

| Argument         | Type     | Required | Description                                                                                                                                                   | Default |
| ---------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `entityName`     | `String` | `true`   | The name of the entity on which the collection is defined.                                                                                                    |         |
| `collectionName` | `String` | `true`   | The name of the collection property to evict.                                                                                                                 |         |
| `primaryKey`     | `String` | `false`  | <p>Optional primary key of the entity instance for which to evict the collection. If not provided, all cached data for the<br>collection will be evicted.</p> |         |

## Examples

Evict all cached entries for a collection mapping:

```java
ormEvictCollection( "Manufacturer", "vehicles" );
```

You can also pass a primary key to evict the collection for a specific entity:

```java
record = entityLoadByPK( "Manufacturer", 1 );
ormEvictCollection( "Manufacturer", "vehicles", record.getId() );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMEvictEntity

Evict all entity data for this entity name from the second-level cache.

## Method Signature

```
ORMEvictEntity(entityName=[String], primaryKey=[String])
```

### Arguments

| Argument     | Type     | Required | Description                                                                                                                                            | Default |
| ------------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
| `entityName` | `String` | `true`   | The name of the entity on which to evict all cached data.                                                                                              |         |
| `primaryKey` | `String` | `false`  | <p>Optional primary key of the entity instance for which to evict cached data. If not provided, all cached data for the entity<br>will be evicted.</p> |         |

## Examples

### Evict All Entities by Type

Clear second-level cache entries for a full entity type.

```java
ormEvictEntity( "Manufacturer" );
```

### Evict Entity by Primary Key

Pass the primary key to remove a single entity cache entry.

```java
record = entityLoadByPK( "Manufacturer", 1 );
ormEvictEntity( "Manufacturer", record.getId() );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMEvictQueries

Evict all queries from the named or default cache on the named or default datasource.

## Method Signature

```
ORMEvictQueries(cacheName=[String], datasource=[String])
```

### Arguments

| Argument     | Type     | Required | Description                                                                                                   | Default |
| ------------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------- | ------- |
| `cacheName`  | `String` | `false`  | The name of the cache region to evict. If not provided, the default query cache will be evicted.              |         |
| `datasource` | `String` | `false`  | The name of the datasource on which to evict the cache. If not provided, the default datasource will be used. |         |

## Examples

### Evict All Query Caches

Call with no arguments to clear all query cache regions.

```java
ormEvictQueries();
```

### Evict by Region and Datasource Cache

You can target a specific cache region and datasource.

```java
ormEvictQueries( "queries", "admin" );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMExecuteQuery

Execute an HQL query with (optional) parameters and specific query options.

## Parameters

The `parameters` argument can be used to bind parameters to the SQL query. You can use either an array of binding parameters or a struct of named binding parameters.

The SQL must have the parameters bound using the syntax `?` for positional parameters or `:name` for named parameters.

Example:

```
 ORMExecuteQuery( hql: "FROM autos WHERE make = ?", params: [ 'Ford' ] );
 ORMExecuteQuery( hql: "FROM autos WHERE make = :make", params: { make: 'Ford' } );
 
```

## Options

The options struct can contain any of the following keys:

* **`unique`** - Specifies whether to retrieve a single, unique item. Default is false.
* **`datasource`** - The datasource to use for the query. If not specified, the default datasource will be used.
* **`offset`** - Specifies the position from which to retrieve the objects. Default is 0.
* **`maxresults`** - Specifies the maximum number of objects to be retrieved. Default is no limit.
* **`readonly`** - If true, the query will be read-only. Default is false.

## Method Signature

```
ORMExecuteQuery(hql=[String], params=[Any], unique=[Any], options=[Struct])
```

### Arguments

| Argument  | Type     | Required | Description                                                                                                                                                                              | Default |
| --------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `hql`     | `String` | `true`   | The HQL query string to execute.                                                                                                                                                         |         |
| `params`  | `Any`    | `false`  | Optional parameters for the HQL query. Can be a struct of named parameters or an array of positional parameters.                                                                         |         |
| `unique`  | `Any`    | `false`  | <p>Optional boolean indicating whether to return a unique result (true) or a list of results (false). If true, the query will return<br>a single object or null if no results found.</p> |         |
| `options` | `Struct` | `false`  | Optional struct of additional query options.                                                                                                                                             |         |

## Examples

### Simple HQL Query Execution

The `ORMExecuteQuery` function allows you to execute HQL (Hibernate Query Language) queries against your ORM entities. This function is useful for retrieving data based on specific criteria defined in your HQL query.

```java
var allToyotas = ORMExecuteQuery(
    hql = "FROM Auto WHERE Make = :make",
    params = { make = "Toyota" },
    options = { unique = false }
);
```

## Passing Parameters

You can pass parameters to your HQL query using either named parameters (as a struct) or positional parameters (as an array).

```java
var allToyotas = ORMExecuteQuery(
    hql = "FROM Auto WHERE Make = ?",
    params = [ "Toyota" ]
);
```

Using named parameters:

```java
var toyota = ORMExecuteQuery(
    hql = "FROM Auto WHERE Make = :make",
    params = { make = "Toyota" }
);
```

Named parameters are converted to JPA-style positional placeholders in the HQL string prior to execution. Thus, the above query is rewritten as:

```sql
FROM Auto WHERE Make = ?1
```

prior to query execution.

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMFlush

Flush the Hibernate session - synchronizing the in-memory state with the database.

## Method Signature

```
ORMFlush(datasource=[String])
```

### Arguments

| Argument     | Type     | Required | Description                                                                                                 | Default |
| ------------ | -------- | -------- | ----------------------------------------------------------------------------------------------------------- | ------- |
| `datasource` | `String` | `false`  | The datasource on which to flush the current session. If not provided, the default datasource will be used. |         |

## Examples

Flush the ORM session for the default datasource:

```java
ormFlush();
```

Flush the ORM session for a secondary, named datasource:

```java
ormFlush( "admin" );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMFlushAll

Flush all open Hibernate sessions in the current request.

## Method Signature

```
ORMFlushAll()
```

### Arguments

This function does not accept any arguments

## Examples

```java
entitySave( entityNew( "Manufacturer", { name: "Dodge", address: "101 Dodge Circle" } ) );
entitySave( entityNew( "AlternateDS", { id: createUUID(), name: "test" } ) );

ormFlushAll();
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMGetHibernateVersion

Retrieve the installed Hibernate version.

## Method Signature

```
ORMGetHibernateVersion()
```

### Arguments

This function does not accept any arguments

## Examples

```java
version = ormGetHibernateVersion();
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMGetSession

Retrieve the Hibernate Session configured for this datasource or default datasource.

## Method Signature

```
ORMGetSession(datasource=[String])
```

### Arguments

| Argument     | Type     | Required | Description                                                                                                             | Default |
| ------------ | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------- | ------- |
| `datasource` | `String` | `false`  | The name of the datasource to retrieve the Session for. If not specified, the Application's default datasource is used. |         |

## Examples

Retrieve the ORM session for the default datasource:

```java
session = ormGetSession();
```

Retrieve the ORM session for the "admin" datasource:

```java
session = ormGetSession( "admin" );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMGetSessionFactory

Retrieve the Hibernate SessionFactory configured for this datasource or default datasource.

## Method Signature

```
ORMGetSessionFactory(datasource=[String])
```

### Arguments

| Argument     | Type     | Required | Description                                                                                                                    | Default |
| ------------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------ | ------- |
| `datasource` | `String` | `false`  | The name of the datasource to retrieve the SessionFactory for. If not specified, the Application's default datasource is used. |         |

## Examples

Omitting a datasource name will return the default session factory:

```java
factory = ormGetSessionFactory();
```

Pass a datasource name when working with alternate datasources within the ORM app:

```java
factory = ormGetSessionFactory( "admin" );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMReload](https://bxorm.ortusbooks.com/reference/built-in-functions/ormreload)


# ORMReload

Reload the ORM application.

## Method Signature

```
ORMReload()
```

### Arguments

This function does not accept any arguments

## Examples

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/reference/built-in-functions/entitydelete)
* [EntityIsAttached](https://bxorm.ortusbooks.com/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/reference/built-in-functions/entityloadbypk)
* [EntityMerge](https://bxorm.ortusbooks.com/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/entitytoquery)
* [ORMClearSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormclosesession)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSession](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/reference/built-in-functions/ormgetsessionfactory)


# CLI Tools

Command-line tooling for debugging entity mapping generation

## GenerateMappings

`GenerateMappings` is a standalone command-line tool for generating Hibernate `.hbm.xml` mapping files from your entity classes, without booting a full BoxLang application or web request. It's most useful for:

* Debugging why an entity fails to generate a mapping, in isolation from your application's startup process
* Pre-generating and committing `.hbm.xml` files to disk so you can set `generateMappings = false` in production (see [Performance](https://bxorm.ortusbooks.com/getting-started/performance))

It runs the same `MappingGenerator` used internally at ORM startup, so its output matches what your application generates automatically.

### Usage

Run it with both `boxlang.jar` and the bx-orm module jar on the classpath:

```bash
java -cp "boxlang.jar:bx-orm-1.6.8.jar" ortus.boxlang.modules.orm.cli.GenerateMappings --path models
```

This generates a `{entityName}.hbm.xml` file alongside each entity class file found under `models`.

### Options

| Option                | Description                                                                                                                                                       |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--path PATH`         | **Required** (repeatable). Relative path to a directory of entity files to scan. Pass it multiple times to scan more than one directory.                          |
| `--mapping NAME:PATH` | Registers a BoxLang module/directory mapping (equivalent to a runtime mapping) before scanning, so entity paths that reference it resolve correctly. Repeatable.  |
| `--failFast`          | Abort mapping generation on the first entity that fails to parse. Without this flag, unparseable entities are skipped (equivalent to `ignoreParseErrors = true`). |
| `--debug`             | Enable debug-level logging for the `orm` log category.                                                                                                            |

### Example

```bash
java -cp "boxlang.jar:bx-orm-1.6.8.jar" ortus.boxlang.modules.orm.cli.GenerateMappings \
    --path models \
    --path modules/contentbox/models \
    --failFast \
    --debug
```

{% hint style="warning" %}
This tool is intended for local debugging and CI mapping-generation checks. It always generates mappings with `saveMapping = true`, writing `.hbm.xml` files directly next to your entity source files.
{% endhint %}


# Introduction

The BoxLang ORM module allows your BoxLang application to integrate with the powerful Hibernate ORM

## BoxLang ORM

<figure><img src="https://2020812868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqBhFxu7wDL7yTyiK4QBg%2Fuploads%2Fgit-blob-b6ec966006908fbbb3a8d9ad794b2a5ed3c9a363%2Fbxorm-wide.jpg?alt=media" alt=""><figcaption></figcaption></figure>

The [BoxLang ORM module](https://github.com/ortus-boxlang/bx-orm) allows your BoxLang\
application to integrate with the powerful [Hibernate ORM](https://hibernate.org/orm/). With Hibernate, you can interact with your database records in an object oriented fashion, using a BoxLang class to denote each record and simple getters and setters for each field value:

```js
@persistent
@entityName( "Auto" )
class {

	@fieldtype( "id" )
	@ormtype( "string" )
	property string id;

	property string make;
	property string model;

    function preInsert( entity ){
        writeLog( "Inserting new Auto: #getMake()# #getModel()#" );
    }
}
```

BoxLang ORM also enables transactional persistence, where an error during a save will roll back the entire transaction to prevent leaving the database in a broken state:

```js
transaction{
    try{
        entitySave(
            entityNew( "Purchase", {
                productID : "123-expensive-watch",
                purchaseTime : now(),
                customerID : customer.getId()
            })
        );
        var cartProducts = entityLoad( "CartProduct", customer.getID() );
        entityDelete( cartProducts );
    } catch ( any e ){
        // don't clear the user's cart if the purchase failed
        transactionRollback();
        rethrow;
    }
}
```

### Hibernate Version Support

bx-orm bundles Hibernate ORM `7.4.8.Final`.

### Open Source Product

bx-orm is an open source BoxLang module with no license purchase necessary. If you are looking to further the development of this extension, consider [sponsoring a feature or opening a support contract](#support).

### Features In A Nutshell

* Map BoxLang classes to database tables and work with rows as objects, with generated getters and setters.
* 47 built-in functions (BIFs) to create, load, save, delete, query and inspect entities (`entityNew()`, `entitySave()`, `entityLoad()`, `ormExecuteQuery()`, ...).
* A fluent query builder, `entityCriteria()`, with automatic joins, projections, paging and bulk statements.
* Entities as structs for JSON APIs with `entityToStruct()`, compatible with mementifier's `this.memento`.
* Entities as queries for reports, grids and exports with `entityToQuery()`. See [Entities as Queries](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/queries).
* ORM work shares BoxLang's `transaction{}`, so ORM writes and plain SQL commit or roll back together.
* Soft delete, automatic timestamps, pessimistic locking, read-only loads and a second-level cache.
* Entity events (`preInsert()`, `postUpdate()`, `postCommit()`, ...) with the power to veto a write.
* Clear `orm.*` errors that name your entities and say how to fix the problem, plus `ormDiagnostics()`.
* A boot cache that lets production start without parsing a single entity.
* Supports every database Hibernate supports, from MySQL, MariaDB and PostgreSQL to SQL Server, Oracle and SQLite.

{% hint style="success" %}
New to bx-orm? Start with the [Quick Start](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/quick-start). Upgrading from 1.x? Read [What's New in 2.0.0](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/whats-new-2.0.0) and [Upgrading to 2.0.0](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/upgrading-to-2.0.0).
{% endhint %}

### Support

By launching [BoxLang](https://boxlang.io/) we are able to give back to the community, as well as offer premium support to enterprises looking for a level up in their Hibernate implementations. If you need performance optimization, session management or caching integrations, please [contact us for support](https://ortussolutions.atlassian.net/servicedesk/customer/portal/9).

* Source Code: [github.com/ortus-boxlang/bx-orm](https://github.com/ortus-boxlang/bx-orm)
* Support Plans: <https://www.ortussolutions.com/services/support>
* Bug Tracker: <https://ortussolutions.atlassian.net/browse/BLMODULES>


# About This Book

About this book: notice of liability, how to contribute and where the proceeds go

The source code for this book is hosted in GitHub:

{% @github-files/github-code-block url="<https://github.com/ortus-docs/bxorm>" %}

You can freely contribute to it and submit pull requests. The contents of this book is copyright by [Ortus Solutions, Corp](https://www.ortussolutions.com/) and cannot be altered or reproduced without author's consent. All content is provided *"As-Is"* and can be freely distributed.

* The majority of code examples in this book are done in `cfscript`.
* The majority of code generation and running of examples are done via **CommandBox**: The ColdFusion (CFML) CLI, Package Manager, REPL - <https://www.ortussolutions.com/products/commandbox>​

## Notice of Liability <a href="#notice-of-liability" id="notice-of-liability"></a>

The information in this book is distributed “as is”, without warranty. The author and Ortus Solutions, Corp shall not have any liability to any person or entity with respect to loss or damage caused or alleged to be caused directly or indirectly by the content of this training book, software and resources described in it.

## Contributing <a href="#contributing" id="contributing"></a>

We highly encourage contribution to this book and our open source software. The source code for this book can be found in our [GitHub repository](https://github.com/ortus-docs/bxorm) where you can submit pull requests.

## Charitable Proceeds <a href="#charitable-proceeds" id="charitable-proceeds"></a>

10% of the proceeds of this book will go to charity to support orphaned kids in El Salvador - [https://www.harvesting.org/](https://www.harvesting.org). So please donate and purchase the printed version of this book, every book sold can help a child for almost 2 months.

### Shalom Children's Home <a href="#shalom-childrens-home" id="shalom-childrens-home"></a>

{% embed url="<https://harvesting.org>" %}
[www.harvesting.org](http://www.harvesting.org)
{% endembed %}

**Shalom Children’s Home** is one of the ministries that is dear to our hearts located in El Salvador. During the 12 year civil war that ended in 1990, many children were left orphaned or abandoned by parents who fled El Salvador. The Benners saw the need to help these children and received 13 children in 1982. Little by little, more children came on their own, churches and the government brought children to them for care, and the Shalom Children’s Home was founded.

Shalom now cares for over 80 children in El Salvador, from newborns to 18 years old. They receive shelter, clothing, food, medical care, education and life skills training in a Christian environment. The home is supported by a child sponsorship program.

We have personally supported Shalom for over 6 years now; it is a place of blessing for many children in El Salvador that either have no families or have been abandoned. This is good earth to seed and plant.


# Release History

Release history for all bx-orm versions

In this section, you will find the release notes for each version we release under this major version. If you are looking for the release notes of previous major versions, use the version switcher at the top left of this documentation book. Here is a breakdown of our major version releases.

## v2.x

bx-orm 2 runs on Hibernate ORM 7.4. It adds fluent criteria queries, `orm.*` errors, a boot cache for fast production starts, entities as structs and much more.

* [What's New in 2.0.0](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/whats-new-2.0.0): the tour of new features.
* [Upgrading to 2.0.0](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/upgrading-to-2.0.0): the checklist to move a 1.x application.
* [2.x release notes](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/2x): every change, release by release.

## v1.x

The 1.x release notes live in the BXORM 1.x documentation space.


# What's New in 2.0.0

A tour of everything new in bx-orm 2.0.0, from Hibernate 7.4 to fluent criteria queries

bx-orm 2.0.0 moves the module onto Hibernate ORM 7.4, adds a fluent query builder, clear errors, a boot cache for fast production starts, and a long list of conveniences inspired by Grails GORM, cborm and mementifier. Your existing BIF calls keep working: read [Upgrading to 2.0.0](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/upgrading-to-2.0.0) for the few behavior changes to check.

## Engine and Startup

### Hibernate ORM 7.4

bx-orm now runs on Hibernate ORM `7.4.8.Final` (up from 5.6.15). You get Hibernate's modern query engine, current database dialects and years of fixes, while the BoxLang side (`entityNew()`, `entitySave()`, `entityLoad()`, `ormExecuteQuery()` and the rest) behaves as before.

* Each entity maps to a generated Java class (a facade) that delegates to your BoxLang entity. This unlocks `uuid` and other id generators, composite primary keys, single-table and joined inheritance, `binary` properties and value collections (`fieldtype="collection"`).
* Mappings use Hibernate's modern `mapping.xml` format and are handed to Hibernate in memory. `savemapping : true` writes them beside each entity for debugging. Each file is named after the entity's source file: `User.bx` gives `User.orm.xml`.
* Legacy dialect names such as `MySQL57` or `Oracle10g`, and Hibernate 5 dialect classes such as `org.hibernate.dialect.MySQL5InnoDBDialect`, still work: they map to the current dialect with a one-time warning. See [Dialects](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration#dialects).

### Boot Cache

Applications can now skip entity discovery, parsing and code generation at startup. On a 250-entity model, this cuts the boot time about in half. `ormManifest : "auto"` writes the resolved model and the generated classes to a `.bxorm/` folder, and `ormManifest : "trust"` boots straight from it in production. In `auto` mode, bx-orm also watches your entity files and reloads the ORM on the next request after you edit one.

```js
this.ormSettings = {
    entityPaths : [ "models" ],
    ormManifest : "auto" // "trust" in production
};
```

The new [`bxorm` CLI](https://bxorm.ortusbooks.com/bxorm-2.x/reference/cli-tools#bxorm-boot-cache-cli) builds the cache without starting your application (`boxlang module:orm generate`, for Docker and CI builds), and inspects, validates and clears it. See [Boot Cache](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/performance#boot-cache).

* `ormManifestLocation` moves the `.bxorm/` folder. A relative path resolves against the application root.
* Several applications can share one `.bxorm/` folder. Each application's files carry its name (`manifest-{app}.json`), and the CLI picks one with `--app=<name>`.

### Faster Boot

Startup also does less work, without any setting:

* Generated ids (`native`, `identity`, `increment`, `uuid`, `sequence` and the like) tell Hibernate that a `null` id means "not saved yet". Hibernate no longer creates a throwaway instance of every entity at startup.
* The new `unsavedValue` id annotation sets the value that marks a new entity, for example `unsavedValue="0"` on an assigned numeric id. See [Unsaved Value](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/identifiers#unsaved-value).
* The per-entity mappings are joined in memory, and apps with more than 20 entities add the static entity methods in parallel.

See [Performance](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/performance#measured-boot-times) for measured boot times.

### Transactions Ride BoxLang

ORM work inside `transaction{}` now uses the same JDBC connection as `queryExecute()`. BoxLang owns the commit and rollback, so ORM writes and plain SQL commit or roll back together, and queries inside a transaction see the ORM writes made earlier in it. See [Transactions](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions).

## Querying

### Case-Insensitive HQL Names

Hibernate 6+ resolves HQL names case-sensitively, but BoxLang is case-insensitive, so bx-orm resolves them for you: `ORMExecuteQuery( "from user where firstname = ?", [ "Luis" ] )` finds the `User` entity's `firstName` property. HQL in the declared case runs as is, and a corrected query is cached, so there is no ongoing cost. See [Querying](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/querying).

### Criteria Queries

`entityCriteria()` is a fluent query builder with automatic joins, groups, subqueries, projections, paging and streaming. It uses cborm's method names, so cborm code reads the same.

```js
var page = entityCriteria( "User" )
    .isEq( "status", "active" )
    .like( "role.name", "admin%" )
    .order( "lastName" )
    .paginate( page = 2, maxRows = 25 );
```

Functions work inside property paths (`isEq( "year(createdDate)", 2025 )`), `updateAll()` and `deleteAll()` run bulk statements, `getSQL()` shows the SQL a query will run, and cborm's `c.restrictions`, quantified subqueries (`subGeAll`, `propertyLtSome`, ...) and SQL log (`startSqlLog()`, `logSQL()`, `getSqlLog()`) work too. See [Criteria Queries](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria).

### Named SQL Functions

Register SQL templates once and call them by name from HQL and criteria paths:

```js
this.ormSettings.sqlFunctions = {
    nameLen : { sql : "char_length(?1)", returns : "integer" }
};

ormExecuteQuery( "from User u where nameLen( u.lastName ) > 10" );
```

See [Named SQL Functions](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration#named-sql-functions).

### Streaming and Unique Results

* `asStream : true` on `ormExecuteQuery()` and `entityLoad()` returns a Java `Stream` that reads rows as you consume it, instead of an array. See [Streaming Results](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/querying#streaming-results).
* `unique` is now strict: more than one match raises `orm.query.nonUnique`. `uniqueFirst : true` takes the first row of a multi-row result, as 1.x did.
* Criteria `paginate()` includes `offset` (the rows skipped before the page) in its `pagination` struct.

### Default Sort Order

`defaultSort="lastName, firstName desc"` on an entity sets the order `entityLoad()` and `entityCriteria()` use when you don't give one. See [Default sort order](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/entities#default-sort-order).

## Static Entity Methods

Every entity class gets static methods that call the matching BIF: `User::get( 1 )`, `User::findWhere( { email : email } )`, `User::count()`, `User::list()` and more. Instances reach them too (`user.count()`). They are on by default; set `staticMethods : false` in `ormSettings` to turn them off. See [Static Entity Methods](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/static-methods).

```js
var user  = User::getOrFail( id );
var total = User::count( { active : true } );
```

## Entities as Structs

`entityToStruct()` turns entities into structs for APIs and views, compatible with mementifier's `this.memento` (includes, excludes, `neverInclude`, mappers, defaults and profiles). Dates come out as ISO 8601 strings, and your own getters are honored.

```js
return entityToStruct( user, { includes : "roles.name" } );
```

`entityLoadAsStruct()` and criteria `asStruct()` build the same structs with projection queries, without loading entities at all. See [Entities as Structs](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs).

## Modeling

| Feature                 | Shape                                                                                                                         | Learn more                                                                                                                            |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Soft delete             | `class softDelete="true"`: `entityDelete()` marks the row deleted and every load skips it. Also `"active"` and `"timestamp"`. | [Soft delete](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/entities#soft-delete)                                                   |
| Automatic timestamps    | `property name="createdDate" autoTimestamp="create";` and `autoTimestamp="update"`.                                           | [Automatic Timestamps](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/properties#automatic-timestamps)                               |
| Entity `where`          | `class where="is_active = 1"` restricts every load and query of the entity. It was silently ignored before.                   | [Filtering rows](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/entities#filtering-rows-with-where)                                  |
| Unique keys and indexes | `uniquekey` and `index` property annotations create their constraints and indexes, including multi-column ones.               | [Properties](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/properties)                                                              |
| `useDBForMapping`       | Adobe ColdFusion compatibility: untyped properties and missing ids are read from the existing tables at startup.              | [Using the Database for Mapping](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration#using-the-database-for-mapping) |

## Working with Entities

| Feature                | Shape                                                                                                                                                                                   |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Load or create         | `entityLoadOrNew()`, `entityLoadOrSave()`                                                                                                                                               |
| Load or fail           | `entityLoadOrFail()`, `entityLoadByPKOrFail()` raise `orm.notFound`                                                                                                                     |
| Load many by id        | `entityLoadByPK( "User", [ 3, 1, 99 ] )` returns `[ user3, user1, null ]` from one query                                                                                                |
| Save and delete arrays | `entitySave( [ a, b ], { flush : true } )`, `entityDelete( list, { flush : true } )`                                                                                                    |
| References             | `entityGetReference( "User", 1 )` gives a reference without a `SELECT`                                                                                                                  |
| Evict                  | `entityEvict( entityOrArray )` removes entities from the session                                                                                                                        |
| Pessimistic locking    | `entityLock()`, `entityLoadByPK( name, id, { lock : "write" } )`, criteria `lock()`                                                                                                     |
| Read-only loads        | `ormReadOnly( closure )`, `entityLoadReadOnly()`, `{ readOnly : true }`                                                                                                                 |
| Inspection             | `entityGetName()`, `entityGetId()`, `entityGetMetadata()`, `entityGetDatasource()`, `entityIsDirty()`, `entityGetDirtyProperties()`, `ormIsSessionDirty()`, `ormGetSessionStatistics()` |

See [Working with Entities](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/working-with-entities) for the whole tour.

## Events

* **Veto**: a `preInsert`, `preUpdate` or `preDelete` handler that returns `false` cancels the operation.
* **`postNew`**: fired by `entityNew()` on the entity and the global event handler.
* **`postCommit( entity, action )`**: fired once a write is committed, never for a rolled-back write. The place to send emails or clear caches.

See [Events](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/events).

## Observability

Tools can listen to ORM activity without reaching into Hibernate:

* `onORMQuery` is announced after each SQL statement, with the SQL, timing, row count, datasource and entity. `announceQueryParams : true` adds the bound values.
* `onORMFlush` reports insert, update and delete counts per flush, and `onORMException` reports failures.
* `generateStatistics : true` turns on Hibernate statistics.
* `ORMPreConfigLoad` and `ORMPostConfigLoad` are announced before and after bx-orm reads an application's `ormSettings`.

See [Observability](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/observability).

## Second-Level Cache on BoxCache

The second-level cache now runs on BoxLang's own BoxCache. Every cache region is a BoxLang cache: tune all of them or each one with `cacheConfig`, keep using an old `ehcache.xml` (it is read and mapped), put a region on a cache you define in `boxlang.json` (any BoxLang provider, including distributed ones), and cache collections with `cacheUse`:

```js
this.ormSettings = {
    secondaryCacheEnabled : true,
    cacheConfig           : { maxObjects : 1000, regions : { "countries" : { defaultTimeout : 0 } } }
};
```

See [Caching](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/caching).

## Errors and Diagnostics

Every error bx-orm raises is now an `orm.*` typed exception with a message in BoxLang terms, a fix in `detail`, and "Did you mean" suggestions for misspelled entity and property names:

```js
try {
    entityLoad( "Usr" );
} catch ( "orm.entity.notFound" e ) {
    // There is no entity named [Usr]. Did you mean [User]?
}
```

Startup checks catch duplicate entity names and unknown `ormtype` values, and `ormDiagnostics()` reports the ORM's state for the current application. See [Errors and Diagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/errors-and-diagnostics).

## Fixes

2.0.0 also fixes a long list of 1.x issues, among them optimistic-locking `version` columns, `text` columns mapping to `TEXT`, `binary` properties, inverse one-to-many without `fkcolumn`, millisecond date precision, `ormFlush( datasource )`, the `cacheable`, `cacheName` and `timeout` query options, and the `sqlScript` setting. `native` ids use a sequence again on PostgreSQL and Oracle, as in 1.x. See the [2.x release notes](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/2x) for the complete list.


# Upgrading to 2.0.0

Step by step guide to upgrade a bx-orm 1.x application to 2.0.0

bx-orm 2.0.0 swaps the engine underneath (Hibernate 5.6 to 7.4) but keeps the BoxLang API: `entityNew()`, `entitySave()`, `entityLoad()`, `ormExecuteQuery()` and friends are called the same way. Most applications upgrade by bumping the version and checking the items below.

{% hint style="info" %}
Coming from Adobe ColdFusion or Lucee instead of bx-orm 1.x? Start with the [ACF/Lucee Migration Guide](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/migration-from-cfml), then come back here.
{% endhint %}

## Requirements

* **BoxLang 1.18.0 or later.** 2.0.0 depends on runtime features added in that release.
* **Hibernate ORM 7.4.8** is bundled. Nothing to install.

```bash
box install bx-orm@2
```

Until 2.0.0 is final, `bx-orm@2` finds nothing to install: ask for a pre-release such as `box install bx-orm@2.0.0-beta.1` instead. See [Installation](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/installation).

## Upgrade Checklist

Work through these in order. Each item says what changed and what to do.

### 1. Turn On `eventHandling` If You Use Events

1.x fired ORM events even when `eventHandling` was `false` (the default). 2.0.0 honors the setting, like Adobe ColdFusion and Lucee: with `eventHandling=false` no event fires. That covers entity methods such as `preInsert()`, the global `eventHandler` and `postNew`.

```js
this.ormSettings = {
    eventHandling : true,
    eventHandler  : "models.ORMEventHandler"
};
```

**Do this if** your entities or a global event handler have event methods. See [Events](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/events).

### 2. Catch `orm.*` Errors Instead of Hibernate Classes

ORM errors are now `orm.*` typed exceptions instead of raw Hibernate or JPA exceptions. The type tells you what went wrong (`orm.query.syntax`, `orm.constraint.unique`, `orm.stale`, ...), the message speaks in your entity names, and `detail` says how to fix it.

```js
// Before
catch ( "org.hibernate.StaleObjectStateException" e ) { ... }

// After
catch ( "orm.stale" e ) { ... }
catch ( "orm" e ) { ... } // any ORM error
```

**Do this if** you catch Hibernate or JPA exception class names, or inspect `e.type`. See the [error catalog](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/errors-and-diagnostics#error-catalog).

### 3. Check `unique` Queries

`unique=true` on `ormExecuteQuery()` and on the filter form of `entityLoad()` is now strict: when more than one row matches, you get an `orm.query.nonUnique` error instead of the first row.

```js
// Keep the 1.x behavior: take the first match
var user = entityLoad( "User", { lastName : "Smith" }, true, { uniqueFirst : true } );
```

`unique : true` given inside the options struct is now honored too, so a query such as `ormExecuteQuery( hql, params, { unique : true } )` returns one object instead of an array.

**Do this if** a `unique` query can match several rows. Narrow the query, or pass `uniqueFirst : true`. Also check calls that pass `unique` in the options struct and expect an array.

### 4. `entityLoadByPK()` Takes Options

The third argument of `entityLoadByPK()` is now an options struct (`lock`, `timeout`, `skipLocked`, `readOnly`). A boolean third argument (Lucee's `unique`) is still accepted and ignored, so existing calls keep working.

### 5. Replace Pre-Generated `.hbm.xml` Files

2.0.0 writes Hibernate's modern mapping format. `savemapping : true` now writes an `.orm.xml` file beside each entity, named after the entity's source file (`User.bx` gives `User.orm.xml`), and `generateMappings : false` (together with `savemapping : true`) reads those `.orm.xml` files from beside each entity. Old `.hbm.xml` files are not read.

**Do this if** you run with `generateMappings : false` (or `autoGenMap : false`):

1. Delete the old `.hbm.xml` files.
2. Boot once with `generateMappings : true` and `savemapping : true` to write the new `.orm.xml` files, or use the [GenerateMappings CLI](https://bxorm.ortusbooks.com/bxorm-2.x/reference/cli-tools#generatemappings).
3. Commit them and set `generateMappings : false`, keeping `savemapping : true` so bx-orm looks for the files beside the entities.

Or skip the files and use the [boot cache](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/performance#boot-cache) (`ormManifest : "trust"`), which also skips parsing and code generation.

### 6. Review Code That Mixes ORM and Plain SQL in a Transaction

Inside `transaction{}`, the ORM now uses the transaction's own JDBC connection instead of running a separate Hibernate transaction. ORM writes and `queryExecute()` now commit and roll back together, and a query inside the transaction sees the ORM writes made earlier in it.

This is what most code expected already. **Check it if** you relied on ORM writes being committed separately from SQL in the same `transaction{}`. See [Transactions](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions).

### 7. Criteria `asStruct()` Dates Are ISO 8601 Strings

Criteria `asStruct()` returns date values as ISO 8601 strings (`2024-03-05T10:20:30Z`), like `entityToStruct()` and `entityLoadAsStruct()`. **Check it if** you read dates from `asStruct()` rows as date objects.

### 8. `useDBForMapping` Now Does Something

In 1.x `useDBForMapping` did nothing. In 2.0.0, `useDBForMapping : true` makes the ORM look at your database tables at startup (JDBC metadata, not mapping files) to find the type of properties without an `ormtype` and the id of entities without one, as Adobe ColdFusion does. It is off by default, which matches 1.x: untyped properties map as `string`, and an entity without an id uses its `id` property. **Check it if** your settings set it to `true`: remove it, or keep it on purpose. See [Using the Database for Mapping](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration#using-the-database-for-mapping).

### 9. Entity `where` Is Now Applied

The entity-level `where` annotation (`class persistent="true" where="..."`) was ignored in 1.x. It now restricts every load and query of the entity, including `entityLoadByPK()`. **Check it if** an entity declares `where`: rows that don't match it no longer load.

### 10. Legacy Dialect Names Log a Warning

Version-specific dialect names such as `MySQL57`, `Oracle10g` or `DerbyTenSeven` still work: bx-orm maps each to the current Hibernate 7 dialect and logs a one-time deprecation warning. Hibernate 7 detects the database version itself, so you can leave `dialect` unset or use the plain database name. Hibernate 5 dialect class names, such as `org.hibernate.dialect.MySQL5InnoDBDialect`, are mapped the same way, with a one-time warning. Dialects for a few discontinued databases (FrontBase, McKoi, Pointbase, Progress, JDataStore, Interbase) were removed by Hibernate. See [Dialects](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration#dialects).

### 11. Test Your HQL and Raw Hibernate Code

HQL is parsed by Hibernate 7's query engine, which is stricter than Hibernate 5's. Run your queries: a query that no longer parses raises `orm.query.syntax` with the line, column and token. Named parameters that a query never uses are now logged as a warning.

If you call the Hibernate API directly through `ormGetSession()` or `ormGetSessionFactory()`, review that code against the [Hibernate 7 migration guides](https://hibernate.org/orm/releases/). Those two functions return wrappers that accept BoxLang entity names and instances. A call on an entity the session does not hold still throws `org.hibernate.TransientObjectException`, as Hibernate 5 did (Hibernate 7 itself throws `IllegalArgumentException`), so code such as ColdBox's object populator keeps detecting new entities.

### 12. `proxyLazyLoading` and `lazy="extra"` No Longer Change Anything

`proxyLazyLoading` is accepted but has no effect: every lazy to-one relationship is a lazy proxy. `lazy="extra"` is accepted and works like `lazy="true"`, because Hibernate 7 has no extra-lazy collections. **Check it if** you relied on `size()` of an `extra` collection not loading the collection. See [Lazy Loading](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/relationships#lazy-loading).

### 13. `entityNew()` Skips Keys That Are Not Properties

`entityNew( "User", data )` only sets keys that match a declared property of the entity (or a parent class). Other keys are skipped without an error; 1.x copied every key onto the entity. A third `ignoreExtras` argument is accepted and ignored. **Check it if** you passed extra keys to `entityNew()` and read them back from the entity.

### 14. `native` Ids Use a Sequence on PostgreSQL and Oracle

`generator="native"` uses the database's own strategy, as bx-orm 1.x did: an identity column on MySQL, MariaDB, SQL Server and Derby, and the shared `hibernate_sequence` (increment 1) on PostgreSQL and Oracle, or the sequence named by the `sequence` attribute. Databases created by bx-orm 1.x need no change. **Check it if** you created PostgreSQL or Oracle tables with an earlier 2.0 pre-release, where `native` meant `identity`: switch those ids to `generator="identity"`, or create `hibernate_sequence` starting above the highest existing id.

### 15. The Second-Level Cache Is BoxCache

Every cache region is now a BoxLang cache, and `cacheConfig` sets its BoxCache properties. An `ehcache.xml` from Adobe ColdFusion or Lucee is read and mapped to BoxCache properties; EHCache itself is not used. **Check it if** you tuned the cache with EHCache-specific settings (disk stores, clustering): those are ignored. See [Caching](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/caching).

## Things You Don't Need to Change

* BIF names, arguments and return values, apart from the items above.
* Entity annotations and property annotations.
* ORM settings in `Application.bx`. All 1.x settings are still read. `proxyLazyLoading` is ignored.

## After Upgrading

* Call [`ormDiagnostics()`](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics) to check the ORM started cleanly: it lists the entities per datasource, startup warnings and key settings.
* Read [What's New in 2.0.0](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/whats-new-2.0.0) for the features you can adopt next.


# 2.x

Version 2.x release notes for the BoxLang ORM Module

## 2.0.0 - Unreleased

A major release: bx-orm moves to Hibernate ORM 7.4. Start with [What's New in 2.0.0](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/whats-new-2.0.0) for the tour and [Upgrading to 2.0.0](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/upgrading-to-2.0.0) for the upgrade checklist.

### ❌ Removed

* Removed the class-less (MAP) entity representation and the `entityFacades` setting; the generated POJO facade is now the only representation. No application change needed.
* Removed the legacy `hbm.xml` writer (`HibernateXMLWriter`) and the `ormXmlMapping` setting; the module always emits the modern Hibernate 7 `mapping.xml`.

### ⚡ Changed

* Boot cache manifests record entity sources as BoxLang paths under their entity root (for example `/models/Task.cfc`) instead of absolute machine paths, so a cache built on a CI runner, in a Docker build stage or in another folder still detects changed entities where it is deployed. The manifest format is now 2: regenerate existing caches (`module:orm generate` or one `auto` boot); a `trust` boot refuses a format 1 manifest.
* `unique=true` on `ormExecuteQuery()` and `entityLoad()` (filter form) is strict: more than one matching row raises `orm.query.nonUnique` instead of silently returning the first. Pass `{ uniqueFirst : true }` for the old behavior. `unique` given inside the options struct is now honored.
* ORM errors are `orm.*` exceptions instead of raw Hibernate/JPA exceptions. Code catching Hibernate class names should catch `"orm"` instead.
* Unused named HQL parameters are logged as a warning.
* `eventHandling` is honored: ORM events (entity methods, the global `eventHandler`, `postNew`) only fire when `eventHandling=true`. Before, they always fired. Apps that use events without setting `eventHandling: true` must add it.
* `entityLoadByPK()`'s third argument is an options struct (`lock`, `timeout`, `skipLocked`, `readOnly`). A boolean third argument (Lucee's `unique`) is accepted and ignored.
* Criteria `asStruct()` returns date values as ISO 8601 strings, like `entityToStruct()` and `entityLoadAsStruct()`.
* `useDBForMapping` now works (it was ignored before). It stays off by default.
* Upgraded the ORM engine from Hibernate 5.6.15 to 7.4.8. BoxLang-facing BIF behavior is preserved.
* The minimum BoxLang version is now 1.18.0 (was 1.11.0), due to several updates the new approach required.
* Legacy dialect aliases (e.g. `MySQL57`, `Oracle10g`, `DerbyTenSeven`) and removed Hibernate 5 dialect classes (e.g. `org.hibernate.dialect.MySQL5InnoDBDialect`) now map to their Hibernate 7 equivalents with a one-time deprecation warning; community-dialect databases (SQLite, Derby, Firebird, …) resolve automatically.
* `ormGetSession()` / `ormGetSessionFactory()` return facade-aware wrappers so a BoxLang entity name or instance works against the raw Hibernate API. Calls on an entity the session does not hold still throw Hibernate 5's `org.hibernate.TransientObjectException` (Hibernate 7 throws `IllegalArgumentException`), so code such as ColdBox's object populator keeps detecting new entities.
* ORM operations inside a BoxLang `transaction{}` now ride the transaction's JDBC connection instead of the ORM running its own separate Hibernate transaction. BoxLang owns the real commit/rollback, so ORM writes are governed by the same demarcation as native `queryExecute` calls (rolled back together, committed together). The `TransactionManager` interceptor now only flushes the session on commit/end and clears it on rollback, and in-transaction ORM queries flush first so they observe their own pending writes (read-your-writes).
* `ORMPreConfigLoad` and `ORMPostConfigLoad` are now registered as interception points.
* Faster ORM boot. Generated ids (`native`, `identity`, `increment`, `uuid`, `sequence` and the like) now tell Hibernate that a null id means "not saved yet", so Hibernate no longer creates one throwaway instance of every entity at startup to find out. The per-entity mappings are also joined as text instead of through a DOM merge, and with `enableThreadedMapping` on (the default) apps with more than 20 entities add the static entity methods in parallel.
* The `native` id generator uses the database's own strategy, as bx-orm 1.x did: an identity column on MySQL, MariaDB, SQL Server and Derby, and a sequence on PostgreSQL and Oracle. The sequence is the shared `hibernate_sequence` with an increment of 1 (or the property's `sequence` annotation), so databases created by bx-orm 1.x keep working. Before, `native` always meant `identity`.
* `entityNew()` only sets keys that are declared properties of the entity (or a parent class); other keys are skipped. The unimplemented `ignoreExtras` argument is removed (a third argument is accepted and ignored).
* `proxyLazyLoading` has no effect and logs a one-time warning: a lazy to-one association is always loaded through a proxy.
* The secondary cache is BoxLang's BoxCache: every Hibernate cache region is a BoxLang cache. A BoxLang cache that already exists with a region's name (for example one defined in `boxlang.json`) is used as that region, and `cacheProvider` can name any registered BoxLang cache provider.

### 🚀 Added

* Switch annotations can be written as BoxLang annotations without a value, and the switch is on: `@persistent`, `@readOnly`, `@dynamicInsert`, `@dynamicUpdate`, `@mappedSuperClass` and `@softDelete` on an entity, and `@persistent`, `@unique`, `@notNull`, `@insert`, `@update`, `@optimisticLock`, `@inverse`, `@constrained`, `@missingRowIgnored` and `@lazy` on a property. An explicit value still wins: `@persistent( false )` turns the switch off. See [Annotation Styles](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/entities#annotation-styles).
* `cacheConfig` configures the second-level cache regions: a struct of BoxCache properties (`maxObjects`, `defaultTimeout`, ...) with an optional `regions` struct of per-region overrides, a JSON file of the same shape, or an EHCache 2 or 3 `ehcache.xml` whose settings are mapped to BoxCache properties.
* `cacheUse` and `cacheName` on a collection property (`one-to-many`, `many-to-many`, `collection`) cache the collection in the second-level cache.
* The `unsavedValue` property annotation on an id is honored: it is the id value that marks an entity as new (not yet saved), for example `unsavedValue="0"` on an assigned numeric id.
* Static entity methods: every entity class gets `User::get( 1 )`, `getOrFail`, `getAll`, `read`, `getReference`, `findWhere`, `findWhereOrFail`, `findAllWhere`, `first`, `exists`, `count`, `list`, `executeQuery`, `criteria` / `newCriteria`, `new`, `firstOrNew`, `firstOrCreate`, `deleteWhere` and `updateWhere`, each calling the matching BIF. A static method the entity declares itself is kept, and instances reach them too (`user.count()`) unless they declare a method of that name. On by default; set `ormSettings.staticMethods = false` to turn them off. In development (trusted cache off), an edited entity gets its methods back on the next request. See [Static Entity Methods](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/static-methods).
* `asStream` option for `ormExecuteQuery()` and `entityLoad()`: return a Java `Stream` that reads rows from the database as it is consumed, instead of an array. Works with BoxLang closures (`.filter()`, `.map()`, `.toList()`), `maxResults`, `offset` and sort orders. Not allowed with `unique` or an update/delete (`orm.argument`).
* Criteria `paginate()` includes `offset` (rows skipped before the page) in its `pagination` struct.
* Case-insensitive HQL names: entity and property names in `ormExecuteQuery()` HQL resolve in any case (`from user where firstname = ?`), as BoxLang is case-insensitive. HQL written in declared case costs nothing extra; a wrong-case name is rewritten to its declared case once and the corrected HQL is cached per application. String literals and parameter names are never touched, and a misspelled name still fails with "Did you mean".
* Clear ORM errors: every error bx-orm raises is an `orm.*` typed exception (catch all with `catch( "orm" e )`, or a family such as `"orm.query"`). Messages use BoxLang entity and property names (never generated facade class names), say how to fix the problem in `detail`, carry the context (entity, property, HQL, params, SQL, constraint) in `extendedInfo`, and suggest the right name for misspelled entities, properties, field types and ormtypes ("Did you mean \[name]?"). Covers HQL syntax and unknown names, missing or mistyped query parameters, lazy loads after the session closed, unsaved associations, missing assigned ids, not-null and unique/foreign-key violations, stale (optimistic lock) updates, and wrong arguments to entity BIFs.
* `ormDiagnostics()`: the ORM's state for the current application (status, last startup error, entities per datasource, warnings, key settings, this request's open sessions). Never throws.
* Startup validation: duplicate entity names on one datasource are reported with both classes; unknown `ormtype` values are warned about and listed as possible causes (after Hibernate's own reason) if Hibernate fails to start, while a relationship's collection `type` (`array`, `struct`) is not mistaken for an ormtype; broken startups (bad entity path, fieldtype, cfc or datasource) raise one `orm.config` error, and the last failure is remembered for later ORM calls and `ormDiagnostics()`.
* `uniqueFirst` option for `ormExecuteQuery()` and `entityLoad()`: take the first row of a multi-row result.
* Entity inspection BIFs: `entityGetName()`, `entityGetDatasource()`, `entityGetId()`, `entityGetMetadata()` (cached per ORM application), `entityIsDirty()` and `entityGetDirtyProperties()` (Hibernate's own dirty check; no SQL for managed entities), `ormIsSessionDirty()` and `ormGetSessionStatistics()`.
* `entityCriteria( entityName )`: a fluent query builder. Conditions (cborm names and aliases, `not*` negation, `anyOf`/`allOf` groups, `where()` shorthands, native `sql()` with bound params), automatic joins for dotted paths, aliases and `with{Association}()`, fetch joins, subqueries (`exists`, `isIn`, cborm `property*`/`sub*`), projections (`project()`, cborm `withProjections()`), struct/query/stream results, ordering, paging and query options. Terminals: `list`, `count`, `exists`, `get`, `getOrFail`, `first`, `firstOrFail`, `paginate`, `simplePaginate`, `pluck`, `sum`/`avg`/`min`/`max`, `each`, `chunk`. Property names are checked while building ("Did you mean"), `getSQL()`/`peekSQL()`/`logSQL()` show the SQL without running it, `writeDump()` shows the calls, HQL, params and SQL, and cborm's criteria interception points are announced (in the calling request's context, so listeners can use its scopes).
* `entityCriteria()` cborm extras: `c.restrictions.*` builds condition objects that `add()`, `or()`, `and()` and `not()` accept (e.g. `c.or( c.restrictions.isEq( "role", "admin" ), c.restrictions.isGt( "age", 30 ) )`); quantified subqueries `subEqAll`, `subGt/Ge/Lt/LeAll` and `...Some`, `propertyEqAll`, `propertyGt/Ge/Lt/LeAll` and `...Some` (`x >= all (select ...)`); and the SQL log: `logSQL( label )` appends `{ type, sql }` to `getSqlLog()`, `startSqlLog( returnExecutableSql, formatSql )` / `stopSqlLog()` / `canLogSql()` / `getSqlLoggerActive()`.
* `orm.notFound` error type for `getOrFail()` / `firstOrFail()`.
* Soft delete: entity `softDelete="true"` (boolean `deleted` column), `"active"` (inverted `active` column) or `"timestamp"` (deletion date), with `softDeleteColumn` to rename the column. `entityDelete()` marks the row, and every load, query and association skips deleted rows (Hibernate `@SoftDelete`, carried by the generated facade).
* Automatic timestamps: property `autoTimestamp="create"` (set on insert) or `"update"` (set on insert and every update), via Hibernate `@CreationTimestamp` / `@UpdateTimestamp`.
* `entityLoadOrNew()`, `entityLoadOrSave()`, `entityLoadOrFail()` and `entityLoadByPKOrFail()`: load by id or filter, or return a new unsaved entity, save a new one, or raise `orm.notFound`.
* `entityEvict( entityOrArray )`: remove entities from the session. `entityGetReference( name, id )`: a reference without a SELECT.
* Pessimistic locking: `entityLock( entity, mode, options )`, `entityLoadByPK( name, id, { lock } )`, criteria `lock()` and `ormExecuteQuery( ..., { lock } )`, with modes `read`, `write`, `force` and `timeout` / `skipLocked` options. Locks need `transaction{}`.
* Read-only loading: `ormReadOnly( closure )`, `entityLoadReadOnly()` and a `readOnly` option on `entityLoad()` and `entityLoadByPK()`.
* Criteria bulk statements: `updateAll( { prop : value } )` and `deleteAll()` run one HQL statement and return the row count (no events or cascades; loaded entities are not refreshed).
* `entityLoadByPK( name, [ ids ] )`: load several entities in one batched query; the array keeps the asked order, with null for missing ids.
* `entitySave()` and `entityDelete()` take one entity or an array, and `{ flush : true }` to flush right away.
* `defaultSort` entity annotation (`defaultSort="lastName, firstName desc"`): the order `entityLoad()` and criteria use when none is given. Checked at boot.
* Functions in criteria paths: `isEq( "year(createdDate)", 2025 )`, `order( "lower(name)" )`, nested calls, literals and `cast()`.
* Named SQL functions: `ormSettings.sqlFunctions = { name : "sql(?1)" }` (or `{ sql, returns }`) registers SQL templates for HQL and criteria; `ormGetSQLFunctions()` lists them.
* `postCommit( entity, action )` event on the entity and the global event handler, fired once a write is committed (never for rolled-back writes).
* `useDBForMapping=true` (Adobe ColdFusion compatibility): at boot, untyped properties get their `ormtype` from the column type and entities without an id get it from the table's primary key.
* `entityToStruct( entityOrArray, options )`: entities as structs, mementifier-compatible (`this.memento` defaults, excludes, never-include, mappers, defaults, profiles), with dotted association paths, cycle safety and ISO 8601 dates.
* `entityLoadAsStruct( name, idOrFilter, includes, options )` and criteria `asStruct( includes )`: the same structs read with projection queries, without loading entities. Getters you write for a property are honored in all three, so they shape the output the same way.
* Event veto: a `preInsert`, `preUpdate` or `preDelete` handler (on the entity or the global `eventHandler`) that returns `false` cancels the operation. Vetoing the insert of a database-identity entity raises `orm.event.veto`, since Hibernate cannot skip that insert.
* POJO-facade entity representation (now the only representation): each entity maps to a generated Java facade whose accessors delegate to the BoxLang instance, unlocking `uuid` (and other) id generators, composite ids, `byte[]`, and full metamodel access.
* Facades are namespaced per ORM application, so same-named entities in different apps do not collide.
* Composite (multi-column) primary keys and entity inheritance (single-table + joined) in the facade representation.
* Associations and lazy proxies in the facade representation
* Mappings use Hibernate 7's modern `mapping.xml` format.
* Value/element collections (`fieldtype="collection"`) as a JPA `<element-collection>`: array (BAG) and struct/map (MAP).
* New core `postNew` ORM event, fired by `entityNew()` on the entity's own `postNew( entity, entityName )` and the global `eventHandler`. (Hibernate has no instantiate event; previously only cborm offered `ORMPostNew`.)
* ORM manifest boot cache (`ormManifest` setting: `off`/`auto`/`trust`). In `auto` the resolved boot model (per-entity metadata + mapping) is written to `.bxorm/manifest-{app}.json` after each boot; in `trust` the app boots straight from that manifest with zero entity discovery, parsing or mapping generation (integrity-checked, fail-closed). Aimed at cold-start-heavy and large-entity apps. Off by default.
* Pre-generated ByteBuddy facade bytecode is cached to `.bxorm/facades-{app}.jar` in `auto` mode and injected in `trust` mode, so production boots skip facade code generation.
* `bxorm` CLI (`boxlang module:orm <verb>`) to inspect the `.bxorm/` boot cache: `info`, `validate`, `entities`, `entity <name>`, `mappings`, `clear`, `version`, `help`. Reads the manifest only; `generate` (below) or one `ormManifest="auto"` boot builds it.
* `boxlang module:orm generate` builds the `.bxorm/` boot cache (manifest and `facades-{app}.jar`) from the command line, with no server, no database and no application start, so a Docker build or CI step can ship a `trust`-ready image: `boxlang --bx-config runtime/boxlang.json module:orm generate`. It runs the `Application.bx`/`.cfc` pseudo-constructor only (empty `cgi`, `url`, `form` and `cookie` scopes are provided), never `onApplicationStart()`. `--dir` sets the app root.
* Several ORM applications can share one `.bxorm/` folder (sub-applications under the same root): each application's boot cache files carry its name (`manifest-{app}.json`, `manifest-{app}.sha256`, `facades-{app}.jar`, where `{app}` is the application name slugified like BoxLang's `slugify()`: `My Shop` becomes `my-shop`). The manifest records its application, and a `trust` boot refuses a manifest written for another application. The `bxorm` CLI takes `--app=<name>` to pick an application (`info` and `validate` cover every application when it is left out) and `clear --all` removes the whole folder. See [Several Applications in One Folder](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/performance#several-applications-in-one-folder).
* `ormManifestLocation` ORM setting (`Application.bx` → `this.ormSettings`): choose where the `.bxorm/` boot cache is stored. Blank (default) keeps it at the application root; a relative path resolves against the app root, an absolute path is used as-is. The folder name stays `.bxorm`; only its parent moves. Mirrors the `bxorm` CLI `--dir` flag.
* `ormManifest="auto"` now starts a source watcher over the entity paths: editing an entity marks the ORM application for reload, and the next request reloads it automatically (no manual `ormReload()`). Generated `*.orm.xml` and the `.bxorm/` cache are ignored so a reload's own writes never loop. The watcher is stopped on shutdown/reload and degrades gracefully when the runtime has no watcher service.
* ORM observability events for tools that want to watch ORM activity without reflecting into Hibernate. `onORMQuery` is announced after each JDBC statement with `sql`, `kind`, `elapsedNanos`, `rows`, `datasource`, `appName`, `hql`, `entityName`, `error` and, optionally, `params`. `onORMFlush` reports insert, update and delete counts per flush, and `onORMException` reports failures. Nothing is wrapped or built when there are no listeners. See [Observability](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/observability).
* `announceQueryParams` ORM setting (default `false`) to include bound parameter values in `onORMQuery`.
* `generateStatistics` ORM setting (default `false`), plus `ORMService.getStatistics( appName )` and `ORMService.setStatisticsEnabled( appName, enabled )` for a plain-struct view of Hibernate statistics.

### 🐛 Fixed

* `dynamicInsert` and `dynamicUpdate` on an entity work again; they had no effect in the earlier 2.0 betas. `selectBeforeUpdate` has no Hibernate 7 equivalent: it still has no effect, and an entity that sets it now logs a warning.
* `constrained` given as a boolean (`@constrained( true )`) no longer fails the mapping.
* [BOX-178](https://ortussolutions.atlassian.net/browse/BOX-178) After a `trust` boot, entity classes kept their raw annotations, so code reading entity metadata saw a different entity than after an `off` or `auto` boot. ColdBox's `populate()` then failed on every relationship (`The class [models.users.Employee] could not be found`), because it reads the `entityName` that discovery adds. A `trust` boot now publishes the cached, normalized metadata (`entityName`, `table`, default `fieldtype` and `ormType`, normalized association types, inherited classes included) onto each entity class at boot, so `getClassMetadata()` and `getMetadata()` return the same values in every mode. See [Boot Cache](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/performance#boot-cache).
* `ormGetSessionFactory().getMetamodel().getAllEntityNames()` and `ormGetSession().getEntityName( entity )` returned the generated facade class names (`...EmployeeFacade`) instead of the entity names. They return the entity names again (`Employee`), as in bx-orm 1, and the raw API accepts those names back.
* [BLMODULES-306](https://ortussolutions.atlassian.net/browse/BLMODULES-306) `<cfquery dbtype="hql">` / `<bx:query dbtype="hql">` and `queryExecute( hql, params, { dbtype : "hql" } )` run HQL and return the same array as `ormExecuteQuery()`. Before, `dbtype` was ignored and the HQL ran as SQL, returning a query. `<cfqueryparam>` binds positional parameters (cast to its `cfsqltype`), and `ormoptions`, `maxrows`, `timeout`, `datasource` and `result` apply. See [HQL in the Query Component](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/querying#hql-in-the-query-component-and-queryexecute).
* `boxlang module:orm` verbs that fail (for example `validate` on a missing or corrupt cache) now exit non-zero, so CI steps can rely on them. Before, every verb exited 0.
* The ORM no longer creates any entity while it starts, so an entity `init()` that needs the application (for example a cborm `ActiveEntity` reading `application.wirebox` before ColdBox loads) no longer makes ORM startup fail. bx-orm now declares the unsaved value of every id and version.
* `entityLoad()` with a `cachename` option did not cache unless `cacheable : true` was also passed.
* The `sqlScript` setting was never read, so the script never ran after `dbcreate` created the tables.
* The `cacheConfig` struct was ignored for the default BoxCache provider.
* The mapping CLI's `--debug` flag had no effect.
* `entitySave()` of a new entity with a database-generated id (`generator="identity"` or `"native"` on MySQL) sets the id right away again, inside a `transaction{}` too. Hibernate 7 had delayed the insert until the flush, so `getId()` returned null.
* The entity-level `where` annotation was never read, so it had no effect; it now restricts every load and query of the entity.
* Optimistic-locking `<version>` columns now work end-to-end.
* `text`/`clob` properties map to `TEXT`/`LONGTEXT` (via `<lob/>`) instead of an in-row `varchar`, avoiding MySQL row-size failures.
* An inverse one-to-many with no explicit `fkcolumn` is emitted as a `mapped-by` collection instead of synthesizing a join table.
* `binary`/`byte[]` properties are mapped and persisted (previously silently skipped).
* A capitalized association property name (e.g. `Client`) no longer breaks boot; `mapped-by` is decapitalized to match the facade accessor.
* A discriminated single-table subclass with a `<secondary-table>` now persists and deletes its own columns (emits `owned="true"`).
* A primary-key load (`entityLoadByPK`, `session.get`) of a session-managed entity no longer returns `null`.
* `removeX()` on a to-many removes by identity/equality, not by the owner's id property names.
* A to-many association can be structurally modified while iterating its getter
* Updating an entity with an association/collection no longer double-fires `preUpdate`/`postUpdate`.
* Hardened `entityLoad()` filter queries against HQL injection (the `order by` property is validated against the entity's properties).
* `entityLoad()` / `ormExecuteQuery()` accept a primary key or entity instance for a to-one association filter/parameter, resolving to a managed reference before binding.
* `ormExecuteQuery()` list parameters bound to an association resolve every element, not just the first.
* `entityLoadByExample()` builds predicates from the inheritance-aware property set and excludes ids, version, and associations.
* `entitySave()` on a detached entity leaves the passed-in object live and carrying generated ids/event changes (Hibernate 7 removed `saveOrUpdate()`).
* Date/time properties retain millisecond precision (`DateTimeConverter` maps to `java.sql.Timestamp`).
* Removed a stale `fieldtype="collection" … not yet supported` warning that logged on every value/element collection even though collections are now supported.
* Inherited to-many associations now get the stable-snapshot getter, so `parent.getChildren().each( c => parent.removeChild( c ) )` is safe for a collection declared on a persistent parent entity (previously only associations declared directly on the entity were protected).
* `removeX()` on an unmanaged (transient) collection now prefers an exact identity match, so a distinct-but-equal transient element is not removed by mistake.
* An owning `one-to-many` without `fkcolumn` reuses the target's back-reference foreign key instead of creating a join table.
* A struct-typed (`type="struct"`) `one-to-many`/`many-to-many` maps its key (`structKeyColumn`/`structKeyType`) and round-trips by key.
* A `fieldtype="timestamp"` version property boots and is stamped on save.
* Hibernate isolated work (e.g. sequence/table id allocation) inside a `transaction{}` runs on its own pooled connection, so it can no longer commit or roll back the surrounding BoxLang transaction mid-flight.
* `duplicate()` of an ORM entity produces an independent copy that saves its own state instead of sharing the original's Hibernate facade.
* ORM BIFs no longer fail with a `NullPointerException` when the application is not ORM-enabled or the ORM failed to start; they raise `orm.notEnabled` / `orm.notReady` with the reason.
* Entity lookup no longer fails with "No entities found for datasource" when every entity lives on a non-default datasource.
* A detached entity bound as an `ormExecuteQuery()` or `entityLoad()` filter parameter resolves correctly (the generated facade name no longer leaks into the lookup).
* `ormExecuteQuery()` now applies the `cacheable`, `cacheName` and `timeout` options (they were ignored), and `entityLoad()` applies `cacheName` as the query cache region.
* `entityLoad()` with `ignorecase` no longer wraps numeric or date sort properties in `lower()`.
* `ormFlush( datasource )` flushes that datasource's session instead of the default one.
* An association parameter given as an id (`ormExecuteQuery()`, `entityLoad()`) no longer fails with "cannot be used as ...Facade" when the session already holds a lazy proxy for that row.
* A failed flush at the end of a request still closes the request's ORM sessions.
* The `uniquekey` and `index` property annotations create their unique constraints and indexes again (lost in the move to `mapping.xml`). Properties sharing a name form one multi-column constraint or index; both accept a comma-separated list, and both work on `many-to-one` foreign keys.
* [BL-2739](https://ortussolutions.atlassian.net/browse/BL-2739) - `generator="identity"` no longer fails on PostgreSQL when `dialect` is set explicitly and the table name is on the reserved-word list (`comment`, `collection`, `release`, `synonym`, `user`, ...). Hibernate read the new key back with `select currval('"comment"_id_seq')`, which PostgreSQL rejects with `invalid name syntax`. An explicit PostgreSQL dialect now tells Hibernate the driver returns generated keys, as auto-detection already did. Set `hibernate.jdbc.use_get_generated_keys` in `hibernateProperties` to override it.


# Installation

Install bx-orm with CommandBox or the BoxLang module installer

## Requirements

* BoxLang 1.18.0 or later
* Java 21 or later
* A JDBC driver module for your database (for example `bx-mysql`, `bx-postgresql` or `bx-derby`)

## CommandBox

If you're using CommandBox to manage your BoxLang server, it's as easy as running `install bx-orm`:

```
box install bx-orm
```

You may need to install `bx-compat-cfml` as well for backwards-compatible ORM behaviors:

```
box install bx-orm bx-compat-cfml
```

## bx-module

For the BoxLang runtime or MiniServer outside of CommandBox, use the `bx-module` command from the BoxLang installer:

```
bx-module install bx-orm
```

Install your JDBC driver module in the same command: `bx-module install bx-orm bx-mysql`. `bx-module` replaces the older `install-bx-module` command.

## Staying on 1.x

bx-orm 2.0 is a major upgrade. To keep an application on the 1.x line, pin the major version:

```bash
box install bx-orm@1
```

Read [Upgrading to 2.0.0](https://bxorm.ortusbooks.com/bxorm-2.x/release-history/upgrading-to-2.0.0) before you move to 2.0.

Future pre-releases are published from the `next` branch.


# Quick Start

Build your first entity and save, load, query and delete it in five minutes

This page takes you from an empty application to saving, loading and querying your first entity. Each step links to the page that covers it in depth.

## 1. Install the Module

Install bx-orm and the JDBC driver module for your database. This guide uses MySQL:

```bash
box install bx-orm bx-mysql
```

See [Installation](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/installation) for other ways to install.

## 2. Configure the Application

Define a datasource and turn on the ORM in your `Application.bx`:

```js
class {

    this.name = "quickstart";

    this.datasources = {
        appDB : {
            driver   : "mysql",
            host     : "localhost",
            port     : 3306,
            database : "quickstart",
            username : "root",
            password : ""
        }
    };
    this.datasource = "appDB";

    this.ormEnabled  = true;
    this.ormSettings = {
        // Where your entities live
        entityPaths   : [ "models" ],
        // Create and update tables from your entities (development only)
        dbcreate      : "update",
        // Fire entity events such as preInsert()
        eventHandling : true
    };
}
```

`dbcreate : "update"` creates the tables for you, which is handy while you learn. See [Configuration](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration) for every setting.

## 3. Create an Entity

An entity is a BoxLang class marked `@persistent`. Each property is a column. Create `models/User.bx`:

```js
@persistent
@table( "users" )
@defaultSort( "lastName" )
class {

    @fieldtype( "id" )
    @generator( "native" )
    @ormtype( "integer" )
    property id;

    @ormtype( "string" )
    property firstName;

    @ormtype( "string" )
    property lastName;

    @ormtype( "string" )
    @unique
    property email;

    @ormtype( "timestamp" )
    @autoTimestamp( "create" )
    property createdDate;

    function getFullName(){
        return getFirstName() & " " & getLastName();
    }
}
```

bx-orm generates the getters and setters (`getEmail()`, `setEmail()`, ...) for you. See [Entities](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/entities) and [Properties](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/properties).

## 4. Save

Create entities with `entityNew()` and save them with `entitySave()` inside a `transaction`. The transaction commits the insert when it ends:

```js
transaction {
    var ann = entityNew( "User", {
        firstName : "Ann",
        lastName  : "Lee",
        email     : "ann@example.com"
    } );
    entitySave( ann );
}

println( ann.getId() ); // the id the database generated
```

## 5. Load

```js
// By primary key: null when there is no such row
var user = entityLoadByPK( "User", 1 );

// By primary key, or throw orm.notFound
var user = entityLoadByPKOrFail( "User", 1 );

// All users, in the entity's defaultSort order
var users = entityLoad( "User" );

// A filter, a sort and paging
var lees = entityLoad( "User", { lastName : "Lee" }, "firstName asc", { maxResults : 10 } );
```

## 6. Query

For anything beyond a simple filter, use `entityCriteria()`:

```js
var recent = entityCriteria( "User" )
    .like( "email", "%@example.com" )
    .isGt( "createdDate", dateAdd( "d", -7, now() ) )
    .order( "lastName" )
    .list();
```

Or write HQL, Hibernate's object query language, with `ormExecuteQuery()`:

```js
var total = ormExecuteQuery( "select count(*) from User where lastName = :name", { name : "Lee" }, true );
```

See [Criteria Queries](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria) and [Queries and HQL](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/querying).

## 7. Return It as JSON

`entityToStruct()` turns entities into plain structs, ready for an API response:

```js
return entityToStruct( users, { includes : "fullName" } );
// [ { id : 1, firstName : "Ann", lastName : "Lee", email : "ann@example.com", createdDate : "2026-09-27T10:20:30Z", fullName : "Ann Lee" } ]
```

See [Entities as Structs](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs).

## 8. Update and Delete

A loaded entity is watched by the ORM: change it inside a transaction and the change is saved when the transaction commits.

```js
transaction {
    var user = entityLoadByPKOrFail( "User", 1 );
    user.setEmail( "ann.lee@example.com" );
}

transaction {
    entityDelete( entityLoadByPK( "User", 1 ) );
}
```

## Next Steps

* [Working with Entities](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/working-with-entities): every way to create, load, save and delete.
* [Relationships](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/relationships): connect entities to each other.
* [Transactions](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions): how the ORM shares BoxLang's `transaction{}`.
* [Events](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/events): react when entities are inserted, updated or deleted.
* [Errors and Diagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/errors-and-diagnostics): read ORM errors and check the ORM's state.


# Configuration

Every ORM setting for Application.bx: datasource, entity paths, dialects, SQL functions and more

## Application.bx

The ORM can be configured by a struct of settings set in `this.ormSettings` in your main `Application.bx`:

```js
class{
    this.ORMenabled = true;
    this.ormSettings = {
        // << Here Be ORM Configuration! 🤪 >>
    };
}
```

## ORM Settings

The full list of available properties you can use to configure the ORM are the following:

| Setting Name            | Default                  | Description                                                                                                                                                                                                                                                                                                                                                                                |
| ----------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `announceQueryParams`   | `false`                  | Includes bound parameter values in the `onORMQuery` event. Values can be sensitive, so they are never announced unless you ask. See [Observability](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/observability).                                                                                                                                                           |
| `generateMappings`      | `true`                   | Automatically generate entity mappings for persistent classes. When `false`, bx-orm reads pre-generated `.orm.xml` files beside each entity; keep `savemapping : true` so it looks there. Each file is named after the entity's source file: `User.bx` gives `User.orm.xml`.                                                                                                               |
| `autoGenMap`            | `true`                   | Backwards-compatible alias for `generateMappings`. Deprecated.                                                                                                                                                                                                                                                                                                                             |
| `autoManageSession`     | `false`                  | Allows the engine to manage the Hibernate session. Use `transaction` blocks to demarcate transaction regions. See [Transactions](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions).                                                                                                                                                                               |
| `cacheConfig`           | *empty*                  | Second-level cache settings, used when `secondaryCacheEnabled=true`: a struct of BoxCache properties for every region with an optional `regions` struct of per-region overrides, or the path of a JSON file or an EHCache 2 or 3 `ehcache.xml` (mapped to BoxCache properties). See [Caching](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/caching#tuning-the-caches-with-cacheconfig). |
| `cacheProvider`         | `"BoxCacheProvider"`     | The BoxLang cache provider for the cache regions bx-orm creates: `BoxCacheProvider` (the default; `ConcurrentHashMap`, `HashTable` and `ehcache` are aliases), or the name of a registered BoxLang cache provider. A BoxLang cache that already exists with a region's name is always used as is.                                                                                          |
| `catalog`               |                          | Default database catalog.                                                                                                                                                                                                                                                                                                                                                                  |
| `entityPaths`           | *empty*                  | Directory or array of directories searched for persistent classes. Specify this to avoid a startup performance cost.                                                                                                                                                                                                                                                                       |
| `datasource`            | `application.datasource` | Datasource used by the ORM. Defaults to `this.datasource` in `Application.bx` when not specified.                                                                                                                                                                                                                                                                                          |
| `defaultBatchSize`      | `16`                     | Default batch size Hibernate uses when fetching lazy collections or proxies.                                                                                                                                                                                                                                                                                                               |
| `dbcreate`              | `none`                   | Schema strategy: `update` creates incremental updates, `dropcreate` recreates the database on reload, and `none` leaves the database unchanged. Hibernate `hbm2ddl.auto` values are accepted too, such as `create`, `create-drop`, `create-only`, `drop`, `validate` and `truncate`.                                                                                                       |
| `dialect`               | `autodiscover`           | Database dialect. Hibernate introspects the datasource by default, or you can provide a fully qualified Java class name. See [Dialects](#dialects).                                                                                                                                                                                                                                        |
| `eventHandling`         | `false`                  | Must be `true` for any ORM event to fire: entity event methods, the global `eventHandler` and `postNew`. See [Events](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/events).                                                                                                                                                                                                |
| `eventHandler`          |                          | Path to the `.bx` class that manages global ORM events.                                                                                                                                                                                                                                                                                                                                    |
| `enableThreadedMapping` | `true`                   | With more than 20 entities, parses entity metadata and adds the static entity methods on parallel threads at startup. Set to `false` to force single-threaded startup.                                                                                                                                                                                                                     |
| `flushAtRequestEnd`     | `false`                  | Automatically flushes the ORM at the end of a request. Persistence should generally be done through `transaction` blocks.                                                                                                                                                                                                                                                                  |
| `generateStatistics`    | `false`                  | Collects Hibernate statistics at startup, for `ORMService.getStatistics()`. Collection has a small cost. See [Observability](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/observability).                                                                                                                                                                                  |
| `hibernateProperties`   | `empty`                  | Flat struct of raw Hibernate property name/value pairs applied directly to Hibernate configuration. Applied last, so it overrides ORM defaults and `ormconfig`. See [Custom Hibernate Config](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration/custom-hibernate-config).                                                                                               |
| `logSQL`                | `false`                  | Logs SQL queries to the console.                                                                                                                                                                                                                                                                                                                                                           |
| `namingstrategy`        | `default`                | Naming convention used for table and column names. See [Naming Strategies](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration/naming-strategies).                                                                                                                                                                                                                        |
| `ormconfig`             |                          | Path to a flat `hibernate.properties` file. Applied before `hibernateProperties`; matching keys in `hibernateProperties` take precedence. The XML `hibernate.cfg.xml` format is not supported. See [Custom Hibernate Config](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration/custom-hibernate-config).                                                                |
| `proxyLazyLoading`      | `false`                  | Accepted for compatibility, but has no effect: every lazy to-one relationship is loaded through a proxy. Setting it logs a one-time warning. See [Relationships](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/relationships).                                                                                                                                                           |
| `quoteIdentifiers`      | `false`                  | Quotes generated table and column identifiers in the Hibernate mapping.                                                                                                                                                                                                                                                                                                                    |
| `ormManifest`           | `off`                    | Boot cache mode: `off`, `auto` (write the `.bxorm/` boot cache on every boot and reload on entity changes) or `trust` (boot straight from the cache). See [Boot Cache](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/performance#boot-cache).                                                                                                                                            |
| `ormManifestLocation`   | *empty*                  | Parent folder for the `.bxorm/` boot cache. Blank uses the application root; a relative path resolves against it. See [Boot Cache](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/performance#boot-cache).                                                                                                                                                                                |
| `savemapping`           | `false`                  | Writes each generated Hibernate mapping beside the entity, for debugging. The file is named after the entity's source file: `User.bx` gives `User.orm.xml`.                                                                                                                                                                                                                                |
| `schema`                |                          | Default database schema.                                                                                                                                                                                                                                                                                                                                                                   |
| `secondaryCacheEnabled` | `false`                  | Enables the secondary cache. See [Caching](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/caching).                                                                                                                                                                                                                                                                                       |
| `ignoreParseErrors`     | `false`                  | Ignores classes with compile-time errors when `true`; otherwise throws exceptions.                                                                                                                                                                                                                                                                                                         |
| `sqlScript`             |                          | Path of a SQL script Hibernate runs right after it creates the tables, so only when `dbcreate` creates them (`dropcreate`, or `create` / `create-drop`). A path that does not exist as written is expanded like `expandPath()`.                                                                                                                                                            |
| `staticMethods`         | `true`                   | Adds static helper methods such as `User::get( 1 )` and `User::findWhere( filter )` to every entity class. Set `false` to leave entity classes untouched. See [Static Entity Methods](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/static-methods).                                                                                                                        |
| `sqlFunctions`          | *empty struct*           | Named SQL functions that HQL and `entityCriteria()` paths can call. See [Named SQL Functions](#named-sql-functions).                                                                                                                                                                                                                                                                       |
| `useDBForMapping`       | `false`                  | Adobe ColdFusion compatibility: fill in untyped property types and missing ids from the existing tables at startup. Foreign keys are not inferred. See [Using the Database for Mapping](#using-the-database-for-mapping).                                                                                                                                                                  |

## Named SQL Functions

`sqlFunctions` registers SQL templates with Hibernate under a name, so [HQL](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/querying#named-sql-functions) and [criteria paths](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria#functions-in-paths) can call them like built-in functions:

```js
this.ormSettings = {
    sqlFunctions : {
        nameLen : { sql : "char_length(?1)", returns : "integer" },
        shout   : "upper(?1)"
    }
};
```

```js
ormExecuteQuery( "select nameLen( m.name ) from Manufacturer m where m.id = 1", [], true ); // 18
entityCriteria( "Manufacturer" ).isEq( "nameLen(name)", 18 ).count();
entityCriteria( "Manufacturer" ).pluck( "shout(name)" );
```

* The value is the SQL template, or a struct with `sql` (the template) and `returns` (the result type).
* `?1`, `?2`, ... `?n` are the function's arguments.
* `returns` is one of `string`, `text`, `integer`, `int`, `long`, `bigint`, `double`, `float`, `decimal`, `numeric`, `boolean`, `date`, `time`, `timestamp` or `datetime`. Leave it out to let Hibernate infer the type.
* The SQL is passed to the database as written, so it must be valid for your database.

A name that is not letters, digits and underscores (starting with a letter or underscore), a function without SQL, an unknown `returns` type, or a `sqlFunctions` value that is not a struct stops the ORM from starting with an `orm.config` error.

[ormGetSQLFunctions()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions) returns the registered functions, and the `settings` of [ormDiagnostics()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics) list their names.

## Using the Database for Mapping

`useDBForMapping` is for Adobe ColdFusion applications whose entities rely on the database to complete their mapping. It is `false` by default. With `useDBForMapping : true`, at startup the ORM reads each entity's existing table (JDBC metadata) and fills in:

* The `ormtype` of every plain property that declares no `ormtype`, `sqltype` or BoxLang `type`, from its column's JDBC type.
* For a root entity with no id property: `@fieldtype( "id" )` on the properties mapped to the table's primary key columns.

| Column type                                 | `ormtype`     |
| ------------------------------------------- | ------------- |
| `varchar`, `char` (and `nvarchar`, `nchar`) | `string`      |
| `clob`, `longvarchar`                       | `text`        |
| `integer`                                   | `integer`     |
| `smallint`, `tinyint`                       | `short`       |
| `bigint`                                    | `long`        |
| `decimal`, `numeric`                        | `big_decimal` |
| `real`, `float`                             | `float`       |
| `double`                                    | `double`      |
| `bit`, `boolean`                            | `boolean`     |
| `date`, `timestamp`                         | `timestamp`   |
| `time`                                      | `time`        |
| `binary`, `varbinary`, `blob`               | `binary`      |

Other column types are left alone. Foreign keys are not inferred: declare relationships with their `fkcolumn`. A table that does not exist yet (for example, one `dbcreate` will create) is skipped, and a table whose metadata cannot be read is logged as a warning.

## Dialects

By using the `ormsettings.dialect` you can tell Hibernate which specific database dialect to use for building queries. By default, Hibernate tries to inspect the datasource and define it for you. 95% of the time, this works. However, if you want a specific one, then you can use the following names or a fully qualified Java class name.

> **Hibernate 7 note:** Hibernate 7 replaced the version-specific dialects (for example `MySQL5`, `Oracle10g`, `DerbyTenSeven`) with a single, version-detecting dialect per database. The legacy names in the table below are still accepted for backwards compatibility: bx-orm maps each to the current dialect for that database and logs a one-time deprecation warning, so you no longer need to pick a version. Databases such as SQLite, Derby, Firebird, Informix, Ingres, and CUBRID now come from the `hibernate-community-dialects` artifact, which bx-orm bundles. A few dialects for long-dead databases (FrontBase, McKoi, Pointbase, Progress, JDataStore, Interbase) were removed by Hibernate and are no longer supported. Prefer leaving `dialect` unset (auto-discovery) or using the plain database name.

Hibernate 5 dialect class names, such as `org.hibernate.dialect.MySQL5InnoDBDialect`, are mapped the same way. bx-orm logs a one-time warning for each.

| Dialect (short name)   | Database                                                    |
| ---------------------- | ----------------------------------------------------------- |
| `Cache71`              | InterSystems Caché.                                         |
| `CockroachDB192`       | CockroachDB.                                                |
| `CockroachDB201`       | CockroachDB.                                                |
| `CUBRID`               | CUBRID.                                                     |
| `DB2`                  | DB2.                                                        |
| `DB297`                | DB2.                                                        |
| `DB2390`               | DB2 for z/OS, also known as DB2/390.                        |
| `DB2400`               | DB2 for i, also known as DB2/400.                           |
| `DB2400V7R3`           | DB2 for i, also known as DB2/400.                           |
| `DerbyTenFive`         | Apache Derby.                                               |
| `DerbyTenSix`          | Apache Derby.                                               |
| `DerbyTenSeven`        | Apache Derby.                                               |
| `Firebird`             | Firebird.                                                   |
| `H2`                   | H2.                                                         |
| `HANACloudColumnStore` | SAP HANA (Cloud column store).                              |
| `HANAColumnStore`      | SAP HANA (column store).                                    |
| `HANARowStore`         | SAP HANA (row store).                                       |
| `HSQL`                 | HSQL (HyperSQL).                                            |
| `Informix`             | Informix.                                                   |
| `Ingres`               | Ingres.                                                     |
| `Ingres9`              | Ingres.                                                     |
| `Ingres10`             | Ingres.                                                     |
| `MimerSQL`             | Mimer SQL.                                                  |
| `MySQL5`               | MySQL.                                                      |
| `MySQL5InnoDB`         | MySQL.                                                      |
| `MySQL57InnoDB`        | MySQL.                                                      |
| `MariaDB`              | MariaDB.                                                    |
| `MariaDB53`            | MariaDB.                                                    |
| `Oracle8i`             | Oracle.                                                     |
| `Oracle9i`             | Oracle.                                                     |
| `Oracle10g`            | Oracle.                                                     |
| `PostgresPlus`         | Postgres Plus (EDB).                                        |
| `PostgreSQL81`         | PostgreSQL.                                                 |
| `PostgreSQL82`         | PostgreSQL.                                                 |
| `PostgreSQL9`          | PostgreSQL.                                                 |
| `SAPDB`                | SAP DB / MaxDB.                                             |
| `SQLite`               | SQLite. Detected automatically. Needs a SQLite JDBC driver. |
| `SQLServer`            | Microsoft SQL Server.                                       |
| `SQLServer2005`        | Microsoft SQL Server.                                       |
| `SQLServer2008`        | Microsoft SQL Server.                                       |
| `Sybase11`             | Sybase Adaptive Server Enterprise.                          |
| `SybaseAnywhere`       | SAP SQL Anywhere (Sybase Anywhere).                         |
| `SybaseASE15`          | Sybase Adaptive Server Enterprise.                          |
| `SybaseASE157`         | Sybase Adaptive Server Enterprise.                          |
| `Teradata`             | Teradata.                                                   |
| `TimesTen`             | Oracle TimesTen.                                            |

{% hint style="info" %}
See the Hibernate Dialect Section: [Hibernate\_User\_Guide.html#database-dialect](https://docs.hibernate.org/orm/7.4/userguide/html_single/Hibernate_User_Guide.html#database-dialect)
{% endhint %}

### SQLite

bx-orm automatically detects SQLite from the JDBC connection, so you do not need to configure `dialect: "SQLite"` explicitly.

```js
this.datasources = {
    "myDB" : {
        "connectionString" : "jdbc:sqlite:/path/to/my.db"
    }
};

this.ormSettings = {
	datasource : "myDB"
};
```

{% hint style="warning" %}
You'll need a SQLite JDBC driver (e.g. `org.xerial:sqlite-jdbc`) on your application's classpath, as bx-orm does not bundle one.
{% endhint %}

### PostgreSQL

With an explicit PostgreSQL `dialect`, bx-orm tells Hibernate to read generated keys from the JDBC driver, as auto-detection does. This keeps `@generator( "identity" )` working on tables whose names are reserved words, such as `comment` or `user`. To override it, set `hibernate.jdbc.use_get_generated_keys` in `hibernateProperties`:

```js
this.ormSettings = {
    dialect             : "PostgreSQL",
    hibernateProperties : { "hibernate.jdbc.use_get_generated_keys" : false }
};
```

## Sample Config

Here is an example configuration from the popular ContentBox Modular CMS application

```js
// THE CONTENTBOX DATASOURCE NAME
this.datasource  = "contentbox";
// ORM SETTINGS
this.ormEnabled  = true;
this.ormSettings = {
	// An array of paths where your entity classes are located
	entityPaths           : [
		// If you create your own app entities
		"models",
		// The ContentBox Core Entities
		"modules/contentbox/models",
		// Custom Module Entities
		"modules_app",
		// Custom Module User Entities
		"modules/contentbox/modules_user"
	],
	// THE DIALECT OF YOUR DATABASE OR LET HIBERNATE FIGURE IT OUT, UP TO YOU TO CONFIGURE.
	dialect              : request.$systemHelper.getSystemSetting( "ORM_DIALECT", "" ),
    // The database creation strategy (e.g., "update", "create", "dropcreate")
	dbcreate             : "update",
    // Enable or disable the secondary cache
	secondarycacheenabled: request.$systemHelper.getSystemSetting( "ORM_SECONDARY_CACHE", false ),
    // The cache provider to use for the secondary cache
	cacheprovider        : "BoxCacheProvider",
	// Whether to log SQL statements
    logSQL               : request.$systemHelper.getSystemSetting( "ORM_LOGSQL", false ),
    // The SQL script to execute during ORM initialization
	sqlScript            : request.$systemHelper.getSystemSetting( "ORM_SQL_SCRIPT", "" ),
    // Whether to flush the session at the end of each request
	flushAtRequestEnd    : false,
    // Whether to automatically manage the session
	autoManageSession    : false,
    // Whether to enable event handling
	eventHandling        : true,
    // The event handler class to use
	eventHandler         : "cborm.models.BxEventHandler",
    // Whether to ignore parse errors
	ignoreParseErrors     : true,
	// TURN ON FOR Debugging if ORM mappings are not working.
	savemapping          : false
}
```


# Custom Hibernate Config

Pass raw Hibernate settings with a properties file or an inline struct

Sometimes bx-orm doesn't have a dedicated setting for a Hibernate property you need. There are two ways to set arbitrary Hibernate properties directly: a `hibernate.properties` file via `ormconfig`, or an inline struct via `hibernateProperties`.

## ormConfig: A Properties File

Point `ormconfig` at a flat, standard Java `hibernate.properties`-formatted file:

```js
this.ormSettings = {
    // ...
    ormconfig : "./config/hibernate.properties"
};
```

The file is a simple list of `key=value` pairs, one Hibernate property per line:

```properties
# hibernate.properties
hibernate.use_sql_comments=true
hibernate.jdbc.batch_size=25
```

{% hint style="warning" %}
Only the flat `key=value` properties file format is supported. The XML `hibernate.cfg.xml` format is not yet implemented.
{% endhint %}

## hibernateProperties: An Inline Struct

For settings you'd rather keep alongside the rest of your ORM config instead of in a separate file, use the `hibernateProperties` struct:

```js
this.ormSettings = {
    // ...
    hibernateProperties = {
        "hibernate.use_sql_comments" = "true",
        "hibernate.jdbc.batch_size" = "25"
    }
};
```

Every entry is applied directly to the Hibernate configuration, giving you an escape hatch for tuning any Hibernate setting bx-orm doesn't expose a dedicated setting for.

## Precedence

Both settings are applied **after** bx-orm's own internal defaults, so either can override bx-orm's hardcoded Hibernate settings (e.g. flush and auto-close behavior). When using both together:

1. `ormconfig` (the file) is applied first.
2. `hibernateProperties` (the inline struct) is applied second, so it wins on a conflicting key.

{% hint style="info" %}
A few settings that bx-orm needs to work are re-applied internally *after* `ormconfig` and `hibernateProperties`. You cannot override them:

* the JDBC connection provider
* the connection handling mode
* the classloaders
* the session context class
* identifier quoting (use the `quoteIdentifiers` setting)
  {% endhint %}


# Secondary Caches

Turn on the second-level cache and pick where its regions live

The second-level cache keeps entities, collections and query results across sessions and requests. In bx-orm 2 it is backed by BoxLang's own BoxCache: every cache region is a BoxLang cache. See [Caching](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/caching) for the full guide, including strategies, collection and query caching, and tuning each region.

## Settings

| Setting                 | Default              | Description                                                                                                                                                                               |
| ----------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `secondaryCacheEnabled` | `false`              | Turns the second-level cache on.                                                                                                                                                          |
| `cacheProvider`         | `"BoxCacheProvider"` | The BoxLang cache provider for the caches bx-orm creates. `ConcurrentHashMap`, `HashTable` and `ehcache` are aliases for BoxCache; any other value must be a registered BoxLang provider. |
| `cacheConfig`           | *empty*              | BoxCache properties for the regions: a struct (top-level keys for every region, `regions` for one region), or the path of a JSON file or an EHCache 2 or 3 `ehcache.xml`.                 |

```js
this.ormSettings = {
    secondaryCacheEnabled : true,
    cacheConfig           : {
        maxObjects : 1000,
        regions    : { "countries" : { defaultTimeout : 0 } }
    }
};
```

A BoxLang cache that already exists with a region's name (for example one defined in `boxlang.json`) is used for that region as is. See [Using Your Own BoxLang Caches](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/caching#using-your-own-boxlang-caches).


# Logging

Where bx-orm, SQL and Hibernate logs go, and how to turn them on

There are several categories of logs generated during normal use of a bx-orm application:

1. `bx-orm` logs
2. SQL logs
3. Hibernate logs
4. Startup Metrics

## bx-orm logs

Logging statements generated from bx-orm itself will be output to the `orm.log` file located in the boxlang runtime `logs/` directory.

This log file may look something like the below when DEBUG mode is enabled:

```
[2025-04-25T09:50:34,965] [Test worker] [DEBUG] [ORM] beforeApplicationListenerLoad fired; checking for ORM configuration 
[2025-04-25T09:50:34,972] [Test worker] [DEBUG] [ORM] ORMEnabled, starting up ORM app for [myApp] 
[2025-04-25T09:50:34,979] [Test worker] [DEBUG] [ORM] ORMApp created for application: [myapp_1428735748] 
[2025-04-25T09:50:35,001] [Test worker] [DEBUG] [ORM] Found more than 20 entities; parallelizing metadata introspection 
[2025-04-25T09:50:35,006] [Test worker] [DEBUG] [ORM] Loading metadata for class /app/models/cms/Author.bx 
[2025-04-25T09:50:35,007] [Test worker] [DEBUG] [ORM] Parsing class file: [/app/models/cms/Author.bx] 
...
```

For more information on configuring loggers, see the [Boxlang Logging](https://boxlang.ortusbooks.com/getting-started/configuration/logging) documentation.

## SQL Logs

bx-orm has the ability to log every SQL statement generated from ORM code. For example, firing `entityDelete( myEntity )` will generate a `DELETE` SQL statement for deleting the entity (table row) in question from the entity table.

A quick example might be this log, generated after firing `entityNew( "Manufacturer", properties )`:

```
[2025-04-25T09:50:46,264] [Test worker] [DEBUG] [org.hibernate.SQL] 
    /* insert Manufacturer
        */ insert 
        into
            manufacturers
            (name, address, id) 
        values
            (?, ?, ?) 
```

To enable this behavior, set `this.ormSettings.logSQL` to `true` in your `Application.bx`:

```js
this.ormSettings={
	"logSQL" : "true"
	// ...
}
```

These SQL statements will also log to the `orm.log` file located in `${boxlang-home}/logs`.

## Hibernate-native logs

Hibernate-native logging statements will also be captured in the `orm.log` file located in `${boxlang-home}/logs`.

## Startup Metrics

In debug mode, bx-orm will log the time taken for each step of the startup process, including entity discovery, metadata parsing, XML mapping generation, and SessionFactory building. Here are some example log entries:

```bash
ORM startup metric - entity file discovery: 42ms (187 candidate files found)
ORM startup metric - entity metadata parsing: 310ms (23 persistent entities found, sequential mode)
ORM startup metric - XML mapping generation: 88ms (23 mapping files generated)
ORM startup metric - total entity discovery, parsing and meta collection: 455ms
ORM startup metric - Hibernate SessionFactory build time [myDatasource]: 1243ms
ORM startup metric - Hibernate SessionFactory build time [defaultDatasource]: 987ms
```

The mapping line says `generated` when bx-orm generates the mappings, or `pre-generated` when `generateMappings` is `false` and existing `.orm.xml` files are read. The `total entity discovery, parsing and meta collection` line is the sum of the steps before Hibernate starts.

{% hint style="info" %}
Only available in bx-orm\@1.6.4 and later.
{% endhint %}


# Naming Strategies

Control how entity and property names become table and column names

Boxlang ORM provides flexible naming strategies to control how entity and property names are mapped to database tables and columns. This allows you to easily customize schema, table, column and other physical names to match your database conventions without having to change your source code.

## Predefined Naming Strategies

You have several choices of naming strategies to choose from:

* **default**: No conversion is performed. Entity and property names are mapped to table and column names exactly as defined in your code.
* **smart**: Applies a smart conversion:
  * All names are forced to uppercase.
  * camelCase names are automatically separated with underscores. For example, `userProfile` becomes `USER_PROFILE`.
* **custom**: Specify a custom naming strategy class that implements the `INamingStrategy` interface. This allows you to implement your own logic for converting names. See [Custom Naming Strategy](#custom-naming-strategy).

## Custom Naming Strategy

Need something else? Try a custom naming strategy. This allows you to implement your own logic for converting entity and property names to table and column names.

```js
this.ormSettings = {
	// ...
	namingStrategy : "models.orm.UnderscoreNamingStrategy"
}
```

The naming strategy may implement [the `INamingStrategy` interface](https://github.com/ortus-boxlang/bx-orm/blob/development/src/main/bx/models/INamingStrategy.bx#L23), or you may omit the declaration and simply provide a class with the appropriate methods. The following methods are supported:

* `public string function getTableName( string tableName )`
* `public string function getColumnName( string columnName )`
* `public string function getCatalogName( string catalogName )`
* `public string function getSchemaName( string schemaName )`
* `public string function getSequenceName( string sequenceName )`


# ACF/Lucee Migration Guide

Migrating to BoxLang ORM from Adobe ColdFusion and Lucee

BoxLang ORM is designed to be compatible with existing CFML ORM code, but there are some differences and considerations when migrating from Adobe ColdFusion (ACF) or Lucee.

## Configuration Differences

There are several ORM settings which have been renamed OR the default value changed in `bx-orm`. Rename these settings in your configuration.

### Renamed Settings

| Setting name (ACF/Lucee) | Setting name (BoxLang) |
| ------------------------ | ---------------------- |
| `skipCFCWithError`       | `ignoreParseErrors`    |
| `cfcLocation`            | `entityPaths`          |

bx-orm does not read the old names. A setting under its old name is ignored, so rename it in your configuration.

### Changed Defaults

| Setting                                           | Lucee Default | ACF Default | BoxLang Default            |
| ------------------------------------------------- | ------------- | ----------- | -------------------------- |
| `ignoreParseErrors` (formerly `skipCFCWithError`) | `true`        | `true`      | `false`                    |
| `autoManageSession`                               | `true`        | `true`      | `false`                    |
| `flushAtRequestEnd`                               | `true`        | `true`      | `false`                    |
| `proxyLazyLoading`                                | `true`        | `true`      | `false` (no effect in 2.0) |

Set these explicitly if your application relies on the ACF/Lucee defaults.

### Database Inspection (`useDBForMapping`)

Adobe ColdFusion inspects the database by default to complete entity mappings. In BoxLang, `useDBForMapping` is `false` by default, so every entity must declare what it needs. If your entities leave out their `ormtype` or their id and rely on the table to fill them in, set it:

```js
this.ormSettings = {
    useDBForMapping : true
};
```

BoxLang then reads each existing table at startup and fills in the `ormtype` of untyped properties (from the column type) and the id of a root entity that declares none (from the primary key). Unlike Adobe ColdFusion, it does not infer foreign keys: declare relationships with their `fkcolumn`. See [Using the Database for Mapping](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration#using-the-database-for-mapping).

### Event Handling

As in Adobe ColdFusion and Lucee, ORM events only fire when `eventHandling` is `true`. With the default (`false`), neither entity event methods, the global `eventHandler`, nor `postNew` run. Earlier bx-orm versions fired events even without this setting, so set `eventHandling: true` if your application uses ORM events:

```js
this.ormSettings = {
    eventHandling : true,
    eventHandler  : "models.ORMEventHandler"
};
```

## Built-in Function Differences

Most of the built-in functions (BIFs) from other CFML engines are functionally identical in BoxLang. A few notable exceptions:

### `EntityLoadByPK()`

In ACF/Lucee, this BIF returns an array of entities by default, and you must pass a `unique=true` argument to return a single entity. In BoxLang, a single entity is returned by default. A boolean third argument (Lucee's `unique`) is accepted and ignored; in BoxLang the third argument is a struct of load options (`lock`, `timeout`, `skipLocked`, `readOnly`). To return an array of entities in BoxLang, use the `entityLoad` BIF instead, or pass an array of ids: `entityLoadByPK( "Automobile", [ id1, id2 ] )` returns an array in the order of the ids.

```js
// Lucee/ACF returns an array
var myAuto = entityLoadByPK( "Automobile", "1HGCM82633A123456" ).first();
// BoxLang returns a single item
var myAuto = entityLoadByPK( "Automobile", "1HGCM82633A123456" );
```

### `EntityNew()`

In ACF, a third argument `ignoreExtras` lets you ignore struct keys that do not match properties on the entity. In Lucee, this argument is called `ignoreNotExisting`.

In BoxLang, extra keys are always skipped: only keys that match a declared property are set, and other keys cause no error. A third argument is accepted and ignored, so ACF and Lucee code keeps working.

```js
var entityProps = { color: "Blue", nonExistentKey: "Blue" };
// no error: color is set, nonExistentKey is skipped
var myNewEntity = entityNew( "Automobile", entityProps, true );
```


# Entities

Turn BoxLang classes into ORM entities, with tables, row filters, default sorting and soft delete

A persistent entity is a boxlang class that is marked as a database entity via the `persistent` annotation upon the class definition:

```js
@persistent
class {

}
```

## Annotation Styles

Entities are configured with BoxLang annotations, such as `@persistent` and `@table( "authors" )`. Each annotation goes on its own line before the class or property it configures:

```js
@persistent
@table( "authors" )
class {

    @fieldtype( "id" )
    @generator( "native" )
    property id;

    @unique
    @notNull
    property email;
}
```

A switch annotation written without a value is on: `@persistent` is the same as `@persistent( true )`. Write `( false )` to turn it off, as in `@lazy( false )`. These are the switch annotations:

* On a class: `persistent`, `readOnly`, `dynamicInsert`, `dynamicUpdate`, `mappedSuperClass` and `softDelete`. `softDelete` also takes `"active"` or `"timestamp"`, as in `@softDelete( "timestamp" )`.
* On a property: `persistent`, `unique`, `notNull`, `insert`, `update`, `optimisticLock`, `inverse`, `constrained`, `missingRowIgnored` and `lazy`. `lazy` also takes `"extra"`, `"proxy"` or `"no-proxy"`.

Switches without a value need a bx-orm build later than `2.0.0-beta.8`; on `2.0.0-beta.8` and earlier, write `@persistent( true )`.

The CFML attribute form and doc-comment annotations still work and mean the same thing, so existing entities need no change. For example, `class persistent="true" table="authors" {` is the same class as the one above.

## Entity Name and Table

By default, the entity name will be the boxlang class file name - minus the file extension, of course. We can modify the entity name via the `entityname` annotation:

```js
@persistent
@entityName( "Author" )
class {

}
```

The `entity` annotation does both in one step. It marks the class as persistent, and a value sets the entity name:

```js
@entity
class {

}
```

```js
@entity( "Author" )
class {

}
```

With no value, the entity name is the class file name.

And the table name via the `table` annotation:

```js
@persistent
@entityName( "Author" )
@table( "authors" )
class {

}
```

Here's the full list of available annotations for a persistent class:

| Annotation            | Type      | Default | Description                                                                                                                                                            |
| --------------------- | --------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `persistent`          | `boolean` | `false` | Mark this class as an ORM entity                                                                                                                                       |
| `entity`              | `string`  |         | Mark this class as an ORM entity, like `@persistent`. A value also sets the entity name, and wins over `entityname`.                                                   |
| `entityname`          | `string`  |         | Set a custom entity name which is different than the boxlang class name                                                                                                |
| `table`               | `string`  |         | Specify the database table name                                                                                                                                        |
| `schema`              | `string`  |         | Specify the database schema name.                                                                                                                                      |
| `catalog`             | `string`  |         | Specify the database catalog name.                                                                                                                                     |
| `dynamicinsert`       | `boolean` | `false` | Generate the `INSERT` at runtime with only the columns that are not null.                                                                                              |
| `dynamicupdate`       | `boolean` | `false` | Generate the `UPDATE` at runtime with only the columns that changed.                                                                                                   |
| `readonly`            | `boolean` | `false` | Specify whether the table is read-only.                                                                                                                                |
| `selectbeforeupdate`  | `boolean` |         | No effect: Hibernate 7 has no select-before-update. bx-orm logs a warning when it is set.                                                                              |
| `optimisticlock`      | `string`  |         | Determines the locking strategy: `all`, `dirty`, `version`, or `none`.                                                                                                 |
| `batchsize`           | `integer` |         | Number of records to retrieve at a single instance.                                                                                                                    |
| `discriminatorColumn` | `string`  |         | Define the discriminator column used in inheritance mapping.                                                                                                           |
| `discriminatorValue`  | `string`  |         | Define the discriminator value used in inheritance mapping.                                                                                                            |
| `joinColumn`          | `string`  |         | Define a join column for inheritance mapping.                                                                                                                          |
| `mappedSuperClass`    | `boolean` | `false` | Mark a non-persistent parent class as a mapped superclass. Its properties are folded into each persistent subclass's table.                                            |
| `cacheUse`            | `string`  |         | Caching strategy: `read-only`, `nonstrict-read-write`, `read-write`, or `transactional`.                                                                               |
| `cacheName`           | `string`  |         | Specify the name of the secondary cache.                                                                                                                               |
| `cacheInclude`        | `string`  | `all`   | Set to `non-lazy` to exclude lazy-loaded properties from the secondary cache entry.                                                                                    |
| `datasource`          | `string`  |         | Name a specific datasource to persist this entity to.                                                                                                                  |
| `where`               | `string`  |         | A raw SQL condition added to every query and load of this entity. See [Filtering rows with `where`](#filtering-rows-with-where).                                       |
| `defaultSort`         | `string`  |         | The order `entityLoad()` and `entityCriteria()` return rows in when no order is given, e.g. `lastName, firstName desc`. See [Default sort order](#default-sort-order). |
| `softDelete`          | `string`  |         | Mark rows deleted instead of removing them: `true` (also `yes` or `deleted`), `active` or `timestamp`. See [Soft delete](#soft-delete).                                |
| `softDeleteColumn`    | `string`  |         | The column `softDelete` uses. Defaults to `deleted` (`active` for `@softDelete( "active" )`).                                                                          |

## Sharing Properties with `mappedSuperClass`

Use `mappedSuperClass` when you want several entities to share a set of properties (like audit columns) without those properties living in their own database table:

```js
// BaseEntity.bx - not persistent itself
@mappedSuperClass
class {
    @ormtype( "timestamp" )
    property createdDate;

    @ormtype( "timestamp" )
    property modifiedDate;
}

// Author.bx
@persistent
class extends="BaseEntity" {
    @fieldtype( "id" )
    property authorID;

    @ormtype( "string" )
    property name;
    // createdDate and modifiedDate columns are added to the "Author" table
}
```

This differs from `joinColumn`/`discriminatorValue` inheritance, where subclasses share rows through a join or a discriminator column in a single parent table. With `mappedSuperClass`, there is no parent table at all: every property is copied into each subclass's own table.

## Filtering rows with `where`

The `where` annotation adds a raw SQL condition (not HQL) to every query and load of the entity: `entityLoad()`, `entityLoadByPK()`, HQL and criteria queries. Rows that do not match are invisible to the ORM.

```js
@persistent
@table( "notes" )
@where( "is_active = 1" )
class {
    @fieldtype( "id" )
    @generator( "increment" )
    property id;

    property title;

    @column( "is_active" )
    @ormtype( "boolean" )
    property isActive;
}
```

```js
entityLoadByPK( "Note", idOfAnInactiveNote ); // null
```

Use column names, not property names, since the condition is SQL. In an inheritance hierarchy, only the root entity's `where` is used. To filter only one collection instead of the whole entity, put `where` on the one-to-many or many-to-many property. See [Filtering Collections](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/relationships#filtering-collections-where).

## Default sort order

`defaultSort` sets the order rows come back in when the caller gives none. It is a comma-separated list of properties, each optionally followed by `asc` (the default) or `desc`:

```js
@persistent
@table( "people" )
@defaultSort( "lastName, firstName desc" )
class {
    @fieldtype( "id" )
    @generator( "increment" )
    property id;

    property firstName;
    property lastName;
}
```

```js
entityLoad( "Person" );                          // by lastName, then firstName descending
entityLoad( "Person", { lastName : "Baker" } );  // same order
entityLoad( "Person", {}, "id desc" );           // an explicit order wins
entityCriteria( "Person" ).list();               // same order
entityCriteria( "Person" ).order( "id" ).list(); // an explicit order wins
```

* It applies to `entityLoad()` (all rows and the filter forms) and to `entityCriteria()` `list()`, `get()`, `first()` and `paginate()`. It is not used by `count()`, and criteria `each()` and `chunk()` without an order still go by id.
* Use plain properties of the entity itself (no association paths).
* A subclass entity inherits its parent entity's `defaultSort` unless it declares its own.
* An unknown property or a direction other than `asc` or `desc` stops the ORM from starting with an `orm.config` error that suggests the right name.

## Soft delete

With `softDelete`, `entityDelete()` runs an `UPDATE` that marks the row deleted instead of a `DELETE`, and every load (`entityLoadByPK()`, `entityLoad()`, HQL, criteria queries and collections) skips deleted rows. This is Hibernate's `@SoftDelete`.

```js
@persistent
@table( "notes" )
@softDelete
class {
    @fieldtype( "id" )
    @generator( "increment" )
    property id;

    property title;
}
```

```js
entityDelete( note );                 // an UPDATE that sets deleted to true, not a DELETE
entityLoadByPK( "Note", note.getId() ); // null
```

Hibernate maps the column itself, so do not declare a property for it. Like any other column, it must exist in the table (`dbcreate` creates it).

| Value                      | Column                | Meaning                                                     |
| -------------------------- | --------------------- | ----------------------------------------------------------- |
| `true`, `yes` or `deleted` | `deleted` (boolean)   | `false` while the row is live, `true` once deleted          |
| `active`                   | `active` (boolean)    | `true` while the row is live, `false` once deleted          |
| `timestamp`                | `deleted` (timestamp) | Empty while the row is live, the deletion time once deleted |

`softDeleteColumn` renames the column:

```js
@persistent
@table( "notes" )
@softDelete( "timestamp" )
@softDeleteColumn( "archived_at" )
class {
    // ...
}
```

A criteria [`deleteAll()`](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria#bulk-updates-and-deletes) on a soft-delete entity also marks the rows deleted.

{% hint style="warning" %}
Declare `softDelete` on the root entity of an inheritance hierarchy only; its subclasses inherit it. A subclass that declares it, or an unknown `softDelete` value, stops the ORM from starting with an `orm.config` error.
{% endhint %}


# Properties

Map entity properties to columns: types, defaults, constraints, automatic timestamps and formulas

Entity properties are how we map table columns to boxlang object values. You can specify an entity property by adding `@persistent` to any `property` inside a persistent boxlang class:

```js
@persistent
class {
    @persistent
    property string name;
}
```

By default, all properties inside a `@persistent` class are assumed to be persistent as well. Thus, we can skip the `@persistent` annotation for brevity:

```js
@persistent
class {
    property string name;
}
```

## Common Property Annotations

| Annotation   | Type      | Description                                                                                                                 |
| ------------ | --------- | --------------------------------------------------------------------------------------------------------------------------- |
| `persistent` | `boolean` | Define this property as a persistent property. If `false`, this property will be completely ignored from an orm standpoint. |
| `name`       | `string`  | Property name                                                                                                               |
| `default`    | `string`  | Default value for the property. This only reaches the boxlang engine, and *does not affect creation of the entity table.*   |
| `column`     | `string`  | Table column where the property value is stored.                                                                            |
| `dbDefault`  | `string`  | Set the default value for the property.                                                                                     |

Make sure you quote datetime `dbdefault` values to avoid invalid date errors in MySQL:

```js
@ormtype( "datetime" )
@dbDefault( "'2016-10-10'" )
property createdOn;
```

## Automatic Timestamps

The `autoTimestamp` annotation fills a date property for you when the entity is written:

```js
@persistent
class {
    @fieldtype( "id" )
    @generator( "increment" )
    property id;

    @ormtype( "timestamp" )
    @autoTimestamp( "create" )
    property createdDate;

    @ormtype( "timestamp" )
    @autoTimestamp( "update" )
    property updatedDate;
}
```

| Value                                 | When the property is set                         |
| ------------------------------------- | ------------------------------------------------ |
| `create` (also `created` or `insert`) | Once, when the entity is inserted                |
| `update` (also `updated`)             | When the entity is inserted, and on every update |

The value comes from the JVM clock when the session flushes. These are Hibernate's `@CreationTimestamp` and `@UpdateTimestamp`, so no event handler is needed (and `eventHandling` does not have to be on). Any other value stops the ORM from starting with an `orm.config` error.

{% hint style="warning" %}
Bulk statements such as the criteria [`updateAll()`](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria#bulk-updates-and-deletes) bypass entities, so they do not set `autoTimestamp` properties.
{% endhint %}

## Property Types

There are several "type" concepts and annotations you may need to use to keep the proper format when persisting or retrieving table data. While these may look similar, they are not equivalent.

| Annotation  | Examples                     | Description                                                                            |
| ----------- | ---------------------------- | -------------------------------------------------------------------------------------- |
| `type`      | `date`,`numeric`             | Boxlang data type                                                                      |
| `fieldtype` | `column`,`id`, `one-to-many` | Denote a special type of field, like an identifier or relationship field.              |
| `ormType`   | `big_decimal`,`timestamp`    | Data type for the database value.                                                      |
| `sqlType`   | `nvarchar`                   | A vendor-specific SQL type used for table creation only. This can normally be ignored. |

## Field Type

The `fieldtype` attribute allows you to define the behavior and purpose of this property:

```js
@fieldtype( "id" )
property string userID;
```

There are several options for the `fieldtype` value:

* `column` - By far the most common, this is the default behavior of every field.
* `id` - Notes this field as the primary key or part of the a composite key.
* `collection` - Denote a collection of items - this could represent a struct, an array
* `version` - Denote a version field, useful for [optimistic locking](https://en.wikipedia.org/wiki/Optimistic_concurrency_control) on an entity
* `timestamp` - Denote a timestamp field
* `one-to-one` - Denote a [one-to-one relationship](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/relationships#one-to-one)
* `one-to-many` - Denote a [one-to-many relationship](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/relationships#one-to-many)
* `many-to-one` - Denote a [many-to-one relationship](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/relationships#many-to-one)
* `many-to-many` - Denote a [many-to-many relationship](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/relationships#many-to-many)

Any other value, such as the old `primary`, stops the ORM from starting with an `orm.config` error.

## ORM Type

The `ormType` attribute allows you to define the database type of the property. This is important for ensuring that data is properly converted when being persisted or retrieved from the database. The `ormType` values are based on Hibernate types, and are documented in the [Hibernate 7.4 User Guide](https://docs.hibernate.org/orm/7.4/userguide/html_single/Hibernate_User_Guide.html#basic).

While not an exhaustive list, here are some of the more common `ormType` values:

* blob
* bit
* tinyint
* yesno
* truefalse
* bigdecimal
* biginteger
* integer
* numeric
* date
* datetime
* char
* nchar
* text

See [Type Conversion](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/type-conversion) for exactly how each `ormType` value is bridged to a JDBC column type.

## Generator Annotations

| Annotation  | Type               | Description                                                                                                                                                                                                                                           |
| ----------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `generator` | `string`           | One of the built-in generators: `assigned`, `foreign`, `guid`, `identity`, `increment`, `native`, `select`, `sequence`, `sequence-identity`, `uuid`, `uuid2`. Any other value is treated as a fully-qualified Java class name for a custom generator. |
| `params`    | `struct`, `string` | Generator parameters, as a struct or a JSON string: `'{ "table" : "uuid_table", "column" : "uuid_value_column" }'`                                                                                                                                    |
| `sequence`  | `string`           | Specify the database sequence key name to use for value generation. Use with `@generator( "sequence" )`                                                                                                                                               |
| `selectkey` | `string`           | Only used with `@generator( "select" )`. Specify the select key to use when selecting sequence values from the database.                                                                                                                              |
| `property`  | `string`           | Only used with `@generator( "foreign" )`. The property whose related entity provides the id.                                                                                                                                                          |
| `generated` | `string`           | Only applies on an id property, where it is passed to the generator as a parameter. One of `always`, `insert`, `never`.                                                                                                                               |

```js
@fieldtype( "id" )
@generator( "sequence" )
@sequence( "userIDGenerator" )
property userID;
```

{% hint style="warning" %}
The legacy CFML/Lucee generator name `seqhilo` is **not** a recognized built-in generator in bx-orm. Use `@generator( "sequence" )` instead. See [Identifiers](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/identifiers) for the full list of built-in generators.
{% endhint %}

{% hint style="info" %}
See [Identifiers and Generators](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/identifiers#common-generator-types) for more information on generated value properties.
{% endhint %}

## Validation

| Annotation       | Type      | Description                                                                                                                                                                     |
| ---------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `notnull`        | `boolean` | Specify a not-null constraint.                                                                                                                                                  |
| `insert`         | `boolean` | Allow inserting values to new rows.                                                                                                                                             |
| `update`         | `boolean` | Allow value updates on existing rows.                                                                                                                                           |
| `uniquekey`      | `string`  | A name for a unique constraint. Properties with the same name form one multi-column constraint. Takes a comma-separated list of names. Works on `many-to-one` foreign keys too. |
| `unique`         | `boolean` | Specify a unique constraint. Default `false`.                                                                                                                                   |
| `validateParams` | `string`  | *Not currently supported*                                                                                                                                                       |
| `validate`       | `string`  | *Not currently supported*                                                                                                                                                       |

## Collection Modifiers

These property annotations are used when setting `@fieldtype( "collection" )` and `collectiontype` is either `struct` or `map`.

| Annotation         | Type     | Description                                                                                                           |
| ------------------ | -------- | --------------------------------------------------------------------------------------------------------------------- |
| `structkeycolumn`  | `string` | Specify the column name to use as the key in the collection struct.                                                   |
| `structkeytype`    | `string` | Specify the ORM type of the key column.                                                                               |
| `structKeyFormula` | `string` | A SQL formula for the struct key, used in place of the `structkeycolumn` column. `structkeycolumn` is still required. |
| `elementcolumn`    | `string` | Specify the column name to use as the value in the collection struct.                                                 |
| `elementtype`      | `string` | Specify the value type of the collection values.                                                                      |

```js
@cfc( "Earnings" )
@fieldtype( "collection" )
@collectiontype( "struct" )
@structKeyColumn( "year" )
@structkeytype( "integer" )
@elementColumn( "totalEarnings" )
@elementType( "bigdecimal" )
property yearlyEarnings;
```

## Relationship Modifiers

| Annotation          | Type                | Description                                                                                                                                                                                                                    |
| ------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `table`             | `string`            | Define the table where the foreign items are stored.                                                                                                                                                                           |
| `lazy`              | `boolean`, `string` | Define a lazy association retrieval type. One of `true`, `false`, `proxy`, `no-proxy` or `extra` (same as `true`).                                                                                                             |
| `inverse`           | `boolean`           | Specify that the association "owner" is referenced and managed on the opposite entity - not this current entity.                                                                                                               |
| `inversejoincolumn` | `string`            | Specify the join column on the associated entity. For `inverse` associations only.                                                                                                                                             |
| `linkschema`        | `string`            | Specify the schema name of the link table                                                                                                                                                                                      |
| `linkcatalog`       | `string`            | Specify the catalog name of the link table                                                                                                                                                                                     |
| `linktable`         | `string`            | Specify the name of the link table                                                                                                                                                                                             |
| `missingRowIgnored` | `boolean`           | Do not throw an error if a foreign key has no match in the foreign entity                                                                                                                                                      |
| `fkcolumn`          | `string`            | Specify the foreign key column in the link table referencing this entity's primary key                                                                                                                                         |
| `orderby`           | `string`            | Specify the order by clause for the association                                                                                                                                                                                |
| `fetch`             | `string`            | Specify the fetch strategy for the association. One of `join`, `select`.                                                                                                                                                       |
| `cascade`           | `string`            | Specify the cascade operation(s) to use upon manipulation of this entity or association. One of `all`,`none`,`save-update`,`delete`,`all-delete-orphan`,`delete-orphan`,`create`,`merge`,`lock`,`refresh`,`evict`,`replicate`. |
| `constrained`       | `boolean`           | Only valid for `one-to-one` relationships. [See the Hibernate 7.4 User Guide](https://docs.hibernate.org/orm/7.4/userguide/html_single/Hibernate_User_Guide.html#associations-one-to-one)                                      |
| `mappedby`          | `string`            | Specify the property on the association that maps to this entity.                                                                                                                                                              |
| `class`             | `string`            | Specify the location of the foreign entity.                                                                                                                                                                                    |
| `cfc`               | `string`            | Alias of `class`.                                                                                                                                                                                                              |
| `where`             | `string`            | Arbitrary SQL where clause for the relation.                                                                                                                                                                                   |
| `singularname`      | `string`            | Singular name to use when generating accessor methods for the relationship: `addPost()`, `removePost()`                                                                                                                        |

```js
@singularName( "post" )
@fieldtype( "one-to-many" )
@cfc( "Post" )
@lazy
@fkcolumn( "author_id" )
property posts;
```

{% hint style="info" %}
See [Modeling Relationships](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/relationships) for more details on modeling an ORM entity relationship.
{% endhint %}

## Other

| Annotation       | Type      | Description                                                                                                                                                                               |
| ---------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `scale`          | `integer` | Decimal scale                                                                                                                                                                             |
| `precision`      | `integer` | Decimal precision                                                                                                                                                                         |
| `length`         | `integer` | String length                                                                                                                                                                             |
| `formula`        | `string`  | Define this property as a computed property by using a SQL query to determine the property value. Formula properties cannot be modified.                                                  |
| `index`          | `string`  | A name for an index on this property's column. Properties with the same name form one multi-column index. Takes a comma-separated list of names. Works on `many-to-one` foreign keys too. |
| `unSavedValue`   | `string`  | On the id property: the id value that marks a new (unsaved) entity. See [Unsaved Value](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/identifiers#unsaved-value).                       |
| `autoTimestamp`  | `string`  | Set the property to the current time on insert (`create`) or on every insert and update (`update`). See [Automatic Timestamps](#automatic-timestamps).                                    |
| `optimisticLock` | `boolean` | Set to `false` to leave this property's column out of the version check. Default `true`.                                                                                                  |
| `datatype`       | `string`  | On a `version` property: the version type, such as `integer` or `timestamp`. Same as `ormType`.                                                                                           |

## Formula Property

```js
@ormtype( "integer" )
@formula( "(
    SELECT COUNT(*)
    FROM posts
    WHERE posts.FK_user = id
)" )
property totalPosts;
```

## Unsupported Attributes

These property annotations are read, but have no effect in bx-orm 2.0:

* `foreignKey` and `foreignKeyName`: the foreign key constraint name is not applied.
* `readOnly`: a property cannot be made read-only. Use `@insert( false )` and `@update( false )` instead.

`joinColumn` is not read on a property. Use `fkcolumn` to name the foreign key column.

{% hint style="info" %}
Looking for better support of a specific persistent attribute? [Contact our Support team to consider sponsoring this feature](https://boxlang.io/plans).
{% endhint %}


# Identifiers

All about entity identifiers, from primary keys, and generators to composite keys and field types.

Identifier properties are denoted via `@fieldtype( "id" )`.

We highly recommend disabling updates on identifier properties via `@update( false )`:

```js
@fieldtype( "id" )
@ormtype( "string" )
@generator( "assigned" )
@update( false )
property id;
```

## Common Generator Types

### Assigned Generator

The Assigned generator is the default identifier generator type, and simply allows the application (your boxlang code) to assign identifier values prior to insertion. You can think of this as `generator=none`.

The application must set the id before the entity is saved.

```js
@fieldtype( "id" )
@generator( "assigned" )
@update( false )
property id;
```

Assigned generators will commonly use [a `preInsert()` event listener](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/events#entity-event-handler) to assign the identifer value:

```js
function preInsert( entity ){
    setId( createUUID() );
}
```

### Select Generator

A select generator will attempt to select the next identifier value from the specified `selectKey` column:

Use it when a database trigger assigns the primary key. After the insert, Hibernate selects the row by a unique key and reads its primary key.

```js
@fieldtype( "id" )
@generator( "select" )
@selectKey( "ssn" )
@update( false )
property userID;
```

### UUID Generator

The UUID generator uses Hibernate's uuid generator under the hood. The id is a string of 32 hexadecimal characters, so use a string id column. `uuid2` and `guid` work the same way in bx-orm 2.0.

```js
@fieldtype( "id" )
@generator( "uuid" )
@update( false )
property userID;
```

### Increment Generator

The Increment generator uses a simple incrementing value to create identifiers. Do not use in concurrent applications, as the values may no longer be unique.

The ids are numbers. They are unique only when no other process inserts rows into the same table, so do not use it in a cluster.

```js
@fieldtype( "id" )
@generator( "increment" )
@update( false )
property userID;
```

#### Other Valid Generator Types

There are several lesser-known identifier generator types, including:

* `foreign` - use a specific property from a foreign entity
* `sequence` - use a database sequence (name it with the `sequence` attribute); replaces the legacy `seqhilo` generator name
* `sequence-identity` - use a database sequence, then retrieve the generated value via `INSERT ... RETURNING` (supported databases only)
* `identity` - use an identity column from the database (auto-increment)
* `native` - the database's own strategy: an identity column on MySQL, MariaDB, SQL Server and Derby, and a sequence on PostgreSQL and Oracle. The sequence is the shared `hibernate_sequence` with an increment of 1, as in bx-orm 1.x, or the one named by the `sequence` attribute
* `select` - select the next value from the column denoted in `selectKey`
* `uuid`, `uuid2` and `guid` - a UUID as a 32-character hexadecimal string

The full list of built-in generator names is: `assigned`, `foreign`, `guid`, `identity`, `increment`, `native`, `select`, `sequence`, `sequence-identity`, `uuid`, `uuid2`. Any other value is used as the fully-qualified Java class name of a custom generator. If no class with that name is on the classpath, the ORM does not start and raises an `orm.config` error.

{% hint style="warning" %}
The legacy CFML/Lucee generator name `seqhilo` is **not** a recognized built-in generator in bx-orm. Use `@generator( "sequence" )` with a `sequence` attribute naming your database sequence instead.
{% endhint %}

{% hint style="info" %}
See the [Hibernate 7.4 User Guide](https://docs.hibernate.org/orm/7.4/userguide/html_single/Hibernate_User_Guide.html#identifiers-generators) for more information on identifier generators.
{% endhint %}

## Unsaved Value

Hibernate decides whether `entitySave()` inserts or updates an entity by looking at its id. If the id equals the property's **unsaved value**, the entity is new and gets inserted; any other id means it already exists and gets updated.

bx-orm sets this for you, to the value a new entity's id starts with:

* An id with a `default` uses that default, including an empty one: `default=""` on a uuid id means an id of `""` is new.
* Any other id, generated or `assigned`, uses `null`: an entity with no id yet is new.
* A `version` property uses `null`, or `undefined` when it has a `default` (then the id decides).

Because bx-orm always declares the unsaved value, the ORM never creates an entity while it starts. Your entity's `init()` only runs when your code creates the entity, so an `init()` that needs the application (for example one that reads `application.wirebox`) is safe.

Set `unsavedValue` yourself when an id is never null before its first save. For example, an assigned numeric id that starts at `0`:

```js
@fieldtype( "id" )
@ormtype( "integer" )
@generator( "assigned" )
@unsavedValue( 0 )
property id;
```

Besides a literal id value, Hibernate accepts `null`, `any` (always insert), `none` (always update) and `undefined` (check the database).


# Relationships

Entity relationships let you define an association between two entity types.

Every relationship property must define the state of the relationship. In each case, the relationship property is defined in an entity which represents the "left" side of the relationship. If you bring a `Posts` relationship into the `User` entity, then from the `User` entity, the `User` is the left side of the relationship, and `Posts` is the right.

## One To One

A one to one relationship couples a single row on the left side to a single row on the right side:

```js
@fieldtype( "one-to-one" )
@cfc( "Address" )
property Address;
```

One to one relationships can be seen as simply extending the entity with additional information. Since there is no possibility of multiple records per entity instance, it may be worthwhile to set `@lazy( false )` to fetch the related entity along with any entity load:

```js
@fieldtype( "one-to-one" )
@cfc( "Address" )
@lazy( false )
property Address;
```

This one-to-one relationship can be visualized as follows:

![One User has one Address, an entity relationship diagram](https://2020812868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqBhFxu7wDL7yTyiK4QBg%2Fuploads%2Fgit-blob-d40df3bbf35479495ffb5e1c155f4caad22acb83%2Fentity-relationship-one-to-one.png?alt=media)

### Constrained (`constrained`)

The `constrained` attribute is specific to `one-to-one` relationships. When set to `true`, it declares that the owning entity's primary key has a foreign-key constraint pointing to the associated entity's primary key. In other words, the associated record must exist:

```js
@fieldtype( "one-to-one" )
@cfc( "UserProfile" )
@constrained
property userProfile;
```

Use `@constrained` when the `UserProfile` table's primary key is also a foreign key back to the `User` table (a shared-primary-key one-to-one). Without it, Hibernate treats the association as a simple reference with no FK constraint generated in the schema.

## One To Many

A one to many relationship couples a single row on the left side (the "one") to multiple rows on the right side (the "many"):

```js
@persistent
@entityName( "User" )
class {
    @fieldtype( "one-to-many" )
    @cfc( "Post" )
    @fkcolumn( "author_id" )
    property posts;
}
```

You'll normally want to set `@lazy` to (for example) avoid fetching every Post on a User:

```js
@fieldtype( "one-to-many" )
@cfc( "Post" )
@lazy
@fkcolumn( "author_id" )
property posts;
```

![One user writes many Posts, an entity relationship diagram](https://2020812868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqBhFxu7wDL7yTyiK4QBg%2Fuploads%2Fgit-blob-bd7db89d351739099a9f665c3b1de46af4e120bd%2Fentity-relationship-one-to-many.png?alt=media)

## Many To One

A many to one relationship couples multiple rows on the left side (the "many") to a single row on the right side( the "one"):

```js
@fieldtype( "many-to-one" )
@cfc( "User" )
@fkcolumn( "author_id" )
property Authors;
```

Thus, a single Post can have only one Author... but an Author (or a User, really) can have many Posts.

![Many Posts are written by one User, an entity relationship diagram](https://2020812868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqBhFxu7wDL7yTyiK4QBg%2Fuploads%2Fgit-blob-f2fc398fcff16871ff96b77dc974ad8d763a5620%2Fentity-relationship-many-to-one.png?alt=media)

## Many To Many

A many to many relationship allows each entity to relate to multiple rows on the opposite side. A good example might be the author/book relationship. Each book can have multiple authors, and each author may write multiple books:

```js
// Author.bx
@fieldtype( "many-to-many" )
@cfc( "Book" )
@linktable( "author_books_link" )
property books;
```

The `linktable` attribute is required on a `many-to-many` property to set the location for storing join records. You can further alter the storage location via `linkschema` and `linkcatalog`:

```js
@fieldtype( "many-to-many" )
@cfc( "Author" )
@linkschema( "blog" )
@linkcatalog( "dbo" )
property authors;
```

![Many Authors write Many Books, an entity relationship diagram](https://2020812868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FqBhFxu7wDL7yTyiK4QBg%2Fuploads%2Fgit-blob-43671360b57e12f60b92d0223dc970669d222081%2Fentity-relationship-many-to-many.png?alt=media)

### Singular Name

On many\* relationships like `one-to-many`, `many-to-one`, etc., you'll be manipulating the full set of items via the property name: `hasAuthors()`, `setAuthors()`, etc. However, this plural terminology becomes weird when used on a single item addition or removal, such as `addAuthors( Author )`. For this reason, you can define a `singularName` annotation to clean up your entity manipulation:

```js
@singularName( "Author" )
@fieldtype( "many-to-one" )
@cfc( "User" )
property Authors;
```

### Lazy Loading

The `lazy` attribute controls **when** Hibernate fetches the related data: immediately when the owning entity is loaded, or later, when the data is first accessed. Choosing the right strategy can have a significant impact on performance.

| Value               | Applies to                              | Behaviour                                                                                                                                    |
| ------------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `false`             | all                                     | Related data is fetched immediately with the owning entity (eager loading).                                                                  |
| `true`              | all                                     | Related data is fetched lazily; Hibernate issues a separate SQL query only when the association is first accessed. A to-one is a lazy proxy. |
| `proxy`, `no-proxy` | to-one (`many-to-one`, `one-to-one`)    | Same as `true`: the related entity is a lazy proxy.                                                                                          |
| `extra`             | to-many (`one-to-many`, `many-to-many`) | Accepted, and the same as `true`. Hibernate 7 has no extra-lazy collections.                                                                 |

#### `lazy=false`: Eager Loading

Eager loading fetches the association together with the parent entity. This is most useful for to-one relationships where the related data is almost always needed:

```js
@fieldtype( "one-to-one" )
@cfc( "Address" )
@lazy( false )
property Address;
```

Avoid using `@lazy( false )` on to-many collections. Fetching large collections eagerly can make query results much larger.

#### `lazy=true`: Lazy Loading

Related data is not fetched until you first access it. A separate SQL query is issued at that point:

```js
@fieldtype( "one-to-many" )
@cfc( "Post" )
@lazy
@fkcolumn( "author_id" )
property posts;
```

On a to-one relationship, `@lazy` gives a lazy proxy, the same as `@lazy( "proxy" )`.

#### `lazy=proxy`: Proxy-Based Lazy Loading

Only valid on to-one relationships (`many-to-one`, `one-to-one`). Hibernate returns a proxy object in place of the real entity. The proxy holds the primary key so that identity checks work without hitting the database; the real entity is loaded only when you call a non-identifier getter:

```js
@fieldtype( "many-to-one" )
@cfc( "Manufacturer" )
@fkcolumn( "FK_manufacturer" )
@lazy( "proxy" )
property manufacturer;
```

#### `lazy=extra`

`@lazy( "extra" )` is accepted for compatibility. It works the same as `@lazy`: Hibernate 7 has no extra-lazy collections, so `size()` or `contains()` load the whole collection.

#### `proxyLazyLoading` Application Setting

`proxyLazyLoading` has no effect in bx-orm 2.0: on a to-one, `@lazy`, `@lazy( "proxy" )` and `@lazy( "no-proxy" )` are all lazy proxies.

### Cascade

The `cascade` attribute controls which persistence operations performed on the owning entity are automatically propagated to the associated entity or collection. Without a cascade setting, you must explicitly save, delete, or update each related entity yourself.

| Value         | Behaviour                                                                                                              |
| ------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `none`        | No operations are cascaded. Each entity must be persisted independently. (Default)                                     |
| `all`         | All operations below are cascaded.                                                                                     |
| `save-update` | Cascades both persist and merge: `EntitySave()` on the owner also saves new related entities and merges detached ones. |
| `persist`     | Cascades persist only: saving a new owner also saves new related entities.                                             |
| `merge`       | Merging the owner into the session also merges the related entity.                                                     |
| `delete`      | Deleting the owner also deletes the related entity.                                                                    |
| `remove`      | JPA-style alias for `delete`.                                                                                          |
| `refresh`     | Refreshing the owner from the database also refreshes the related entity.                                              |
| `evict`       | Evicting the owner from the session cache also evicts the related entity.                                              |
| `lock`        | Locking the owner into the session also locks the related entity.                                                      |
| `replicate`   | Replicating the owner also replicates the related entity.                                                              |

You can combine multiple values as a comma-separated string:

```js
@fieldtype( "one-to-many" )
@cfc( "Post" )
@fkcolumn( "author_id" )
@cascade( "save-update,delete" )
property posts;
```

With `@cascade( "save-update,delete" )`, calling `EntitySave( user )` will automatically persist any new or modified `Post` objects in the collection, and calling `EntityDelete( user )` will delete all of the user's posts first.

> **Warning:** Use `@cascade( "all" )` or `@cascade( "delete" )` carefully on large collections. Deleting a `User` with thousands of posts will issue a DELETE for each one individually unless you configure bulk operations at the database level.

### Fetch Strategy

The `fetch` attribute controls *how* Hibernate retrieves the association when it does load: as a SQL JOIN in the same query, or as a separate SELECT:

| Value    | Behaviour                                                                          |
| -------- | ---------------------------------------------------------------------------------- |
| `select` | Hibernate issues a separate SELECT query to load the association. (Default)        |
| `join`   | Hibernate uses a SQL JOIN to load the association in the same query as the parent. |

```js
@fieldtype( "many-to-one" )
@cfc( "Manufacturer" )
@fkcolumn( "FK_manufacturer" )
@fetch( "join" )
property manufacturer;
```

`@fetch( "join" )` forces eager loading regardless of the `lazy` setting and is most useful on to-one associations where the related data is almost always needed. Avoid it on to-many collections, as it can multiply the result-set rows.

### Ordering Collections (`orderBy`)

The `orderBy` attribute applies a SQL `ORDER BY` clause whenever Hibernate loads a to-many collection. The value is a raw SQL fragment:

```js
@fieldtype( "one-to-many" )
@cfc( "Post" )
@fkcolumn( "author_id" )
@orderBy( "created_at DESC" )
property posts;
```

The collection returned from `getPosts()` will always be sorted by `created_at` descending. This is applied at the database level, not in memory.

### Filtering Collections (`where`)

The `where` attribute applies a fixed SQL `WHERE` condition to a collection, restricting which rows are ever included. The value is a raw SQL fragment (not HQL):

```js
@fieldtype( "one-to-many" )
@cfc( "Post" )
@fkcolumn( "author_id" )
@where( "status = 'published'" )
property publishedPosts;
```

`getPublishedPosts()` will only ever return rows where `status = 'published'`. This is useful for modelling a filtered view of a collection without a separate entity query. `where` works on `one-to-many` and `many-to-many` collections.

To hide rows from every query and load of an entity, not just from one collection, put `where` on the entity itself. See [Filtering rows with `where`](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/entities#filtering-rows-with-where).

### Inverse and Bidirectional Relationships

When you model a relationship from both sides (e.g. `User` has `posts` and `Post` has `author`), only one side should "own" the foreign key and be responsible for writing it to the database. The other side is the **inverse** side and should be marked accordingly to avoid Hibernate attempting to update the join column twice.

Use `@inverse` to mark a collection as the non-owning side:

```js
// User.bx: inverse side
@fieldtype( "one-to-many" )
@cfc( "Post" )
@fkcolumn( "author_id" )
@inverse
property posts;

// Post.bx: owning side (holds the FK column)
@fieldtype( "many-to-one" )
@cfc( "User" )
@fkcolumn( "author_id" )
property author;
```

Alternatively, use `mappedBy` on the collection to name the property on the child entity that owns the join:

```js
// User.bx
@fieldtype( "one-to-many" )
@cfc( "Post" )
@mappedBy( "author" )
property posts;
```

Both `@inverse` and `mappedBy` tell Hibernate the same thing: this collection side does not manage the foreign key. For `one-to-many` / `many-to-one` pairs, always mark the collection side as inverse (or use `mappedBy`). For `many-to-many`, pick one side.

### Batch Size (`batchsize`)

The `batchsize` attribute overrides the global `defaultBatchSize` ORM setting for this specific collection, controlling how many collections Hibernate fetches in a single round-trip when multiple parent entities are loaded:

```js
@fieldtype( "one-to-many" )
@cfc( "Post" )
@fkcolumn( "author_id" )
@lazy
@batchsize( 50 )
property posts;
```

If you load 100 `User` entities and then access each one's `posts`, Hibernate will fetch them in batches of 50 rather than issuing 100 individual SELECT queries.

When no per-property `batchsize` is set, Hibernate falls back to the application-wide `defaultBatchSize` ORM setting (see [Configuration](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration)), which defaults to `16`, the same as Adobe ColdFusion and Lucee.

### Caching a Collection (`cacheUse`)

With the second-level cache on, `cacheUse` (and optionally `cacheName`) on a `one-to-many`, `many-to-many` or `collection` property caches the collection across sessions:

```js
@fieldtype( "many-to-many" )
@cfc( "Role" )
@linktable( "user_roles" )
@cacheuse( "read-write" )
@cachename( "userRoles" )
property roles;
```

The collection cache stores the ids of its elements, so cache the element entity too. See [Caching](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/caching#collections).

## Relationship Methods

When you define a relationship property, a number of methods are automatically generated in each relationship entity instance which allow you to access and manipulate the relationship data.

| Method                            | Description                                          | Relationship types            |
| --------------------------------- | ---------------------------------------------------- | ----------------------------- |
| `has<PropertyName>()`             | Returns true if the relationship contains any items. | All                           |
| `add<PropertyName>( entity1 )`    | Add an entity instance to the relationship.          | `one-to-many`, `many-to-many` |
| `remove<PropertyName>( entity1 )` | Removes one or more entities from the relationship.  | `one-to-many`, `many-to-many` |

These method signatures are as follows:

```java
public boolean function hasPosts();
// returns `this` for method chaining
public component function addPosts( required any postItem );
// returns `this` for method chaining
public component function removePosts( required any postItem );
```

### One-To-One Example

The following relationship definition defines a `Contact` property on a `User` entity:

```java
@fieldtype( "one-to-one" )
@cfc( "Contact" )
property Contact;
```

Since this is a one-to-one relationship, *only the `hasContact()` method is generated*:

* `hasContact()`

Use the property accessor methods `getContact()` and `setContact()` to access and modify the relationship.

### One-To-Many Example

The following relationship definition defines a `posts` property on a `User` entity:

```java
@fieldtype( "one-to-many" )
@cfc( "Post" )
@lazy
property posts;
```

Since this is a one-to-many relationship, the following methods are generated:

* `hasPosts()`
* `addPosts()`
* `removePosts()`

### Singular Name

We can set a `singularName` attribute to change the `addPosts()` and `removePosts()` methods to `addPost()` and `removePost()`:

```java
@singularName( "post" )
@fieldtype( "one-to-many" )
@cfc( "Post" )
@lazy
property posts;
```

This will generate the following methods:

* `hasPosts()`
* `addPost()`
* `removePost()`

Note that the `hasPosts()` method remains plural since it checks for the existence of any posts in the relationship.


# Type Conversion

How BoxLang's dynamic types are bridged to JDBC column types

BoxLang is dynamically typed, but JDBC and Hibernate expect a specific Java type for every column. bx-orm bridges the two using a set of built-in JPA `AttributeConverter` classes, applied automatically based on each property's `ormType`.

## How It Works

When bx-orm generates the Hibernate mapping XML for a property, it normalizes the property's `ormType` value (folding aliases like `big_decimal`/`bigdecimal`, or `date`/`datetime`, down to a canonical name) and, for most properties, wires up a matching converter:

| `ormType` values (aliases folded)                    | Canonical type | Converter used                          |
| ---------------------------------------------------- | -------------- | --------------------------------------- |
| `string`, `varchar`, `nvarchar`                      | `string`       | `StringConverter`                       |
| `bigdecimal`, `big_decimal`, `big-decimal`           | `bigdecimal`   | `BigDecimalConverter`                   |
| `biginteger`, `big_integer`, `big-integer`, `bigint` | `biginteger`   | `BigIntegerConverter`                   |
| `integer`, `int`                                     | `integer`      | `IntegerConverter`                      |
| `long`                                               | `long`         | `LongConverter`                         |
| `tinyint`, `tinyinteger`                             | `short`        | `ShortConverter`                        |
| `numeric`, `number`, `decimal`                       | `double`       | `DoubleConverter`                       |
| `float`                                              | `float`        | `FloatConverter`                        |
| `bit`, `bool`                                        | `boolean`      | `BooleanConverter`                      |
| `yes-no`, `yesno`, `yes_no`                          | `yes_no`       | `BooleanConverter`                      |
| `true-false`, `truefalse`, `true_false`              | `true_false`   | `BooleanConverter`                      |
| `eurodate`, `usdate`, `date`, `datetime`             | `timestamp`    | `DateTimeConverter`                     |
| `time`                                               | `time`         | `TimeConverter`                         |
| `blob`, `byte[]`                                     | `binary`       | *(none - stored as raw binary)*         |
| `char`, `nchar`                                      | `character`    | *(none - stored as a single character)* |
| `clob`                                               | `text`         | *(none - stored as text)*               |

Each converter's job is to translate a BoxLang dynamic value into the JDBC type Hibernate expects on the way into the database, and back into a BoxLang-friendly value on the way out - using BoxLang's own type casters (e.g. `DateTimeCaster`, so a `DateTime` object round-trips correctly regardless of what dynamic type was assigned to the property in memory).

{% hint style="info" %}
**Identifier and version properties skip converters.** A property with `@fieldtype( "id" )` or `@fieldtype( "version" )` is written using its plain Hibernate basic type, not one of the converters above. This keeps primary key and optimistic-locking columns on Hibernate's native type handling.
{% endhint %}

## Custom Converters

There is currently no supported mechanism for registering your own `AttributeConverter` for a property - the converters above are applied automatically based on `ormType` and cover the standard Hibernate basic types. If you need a database column type not covered here, use `sqlType` to control the generated DDL, or reach for a [custom Hibernate config](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration/custom-hibernate-config) / `hibernateProperties` for engine-level tuning.

See [Properties](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/properties#orm-type) for the full list of `ormType` values you can set on a property.


# Working with Entities

Create, load, save, update and delete entities with the ORM built-in functions

This page walks through an entity's life: create it, save it, load it, change it and delete it. Each section names the built-in functions (BIFs) to use; their reference pages have every argument.

{% hint style="info" %}
Do your writes inside `transaction{}`. The ORM saves changes when the transaction commits and throws them away when it rolls back. See [Transactions](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions).
{% endhint %}

## Create

[entityNew()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew) creates a new, unsaved entity, optionally filled from a struct:

```js
var user = entityNew( "User" );
var user = entityNew( "User", { firstName : "Ann", lastName : "Lee" } );
```

With `eventHandling` on, `entityNew()` fires the `postNew` event on the entity and the global event handler. See [Events](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/events).

## Save

[entitySave()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave) saves a new entity, or an array of them:

```js
transaction {
    entitySave( user );
    entitySave( [ ann, bob, cy ] );
}
```

* A new entity is inserted. A detached entity (loaded in an earlier request) is merged back. An entity already in the session needs no call: its changes are saved anyway.
* The SQL runs when the session flushes, at the end of the `transaction{}`. Pass `{ flush : true }` to write right away, for example to get a database-generated id:

```js
entitySave( user, { flush : true } );
println( user.getId() );
```

## Load

| You want                                               | Use                                                                                                                                                                       |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| One entity by primary key, or `null`                   | [entityLoadByPK( name, id )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)                                                          |
| Several entities by primary key, in the order asked    | `entityLoadByPK( name, [ id1, id2 ] )`                                                                                                                                    |
| One entity by primary key, or an `orm.notFound` error  | [entityLoadByPKOrFail( name, id )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)                                              |
| All entities, or those matching a filter               | [entityLoad( name, \[filter\], \[sortOrder\], \[options\] )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)                              |
| One entity matching a filter                           | `entityLoad( name, filter, true )`                                                                                                                                        |
| One entity by id or filter, or an `orm.notFound` error | [entityLoadOrFail( name, idOrFilter )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)                                              |
| Entities that look like an example entity              | [entityLoadByExample( entity, \[unique\] )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)                                      |
| Anything more complex                                  | [entityCriteria()](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria) or [HQL](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/querying) |

```js
var user   = entityLoadByPK( "User", 1 );
var users  = entityLoadByPK( "User", [ 3, 1, 99 ] ); // [ user3, user1, null ], one query
var smiths = entityLoad( "User", { lastName : "Smith" }, "firstName asc", { maxResults : 20, offset : 40 } );
var ann    = entityLoad( "User", { email : "ann@example.com" }, true );
```

A `unique` load that matches more than one row raises `orm.query.nonUnique`. Pass `{ uniqueFirst : true }` to take the first row instead.

Without a sort order, `entityLoad()` uses the entity's [`defaultSort`](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/entities#default-sort-order) when it declares one.

### Load or Create

| You want                               | Use                                                                                                                                          |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| The entity, or a new unsaved one       | [entityLoadOrNew( name, idOrFilter, \[properties\] )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)   |
| The entity, or a new one that is saved | [entityLoadOrSave( name, idOrFilter, \[properties\] )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave) |

```js
transaction {
    var tag = entityLoadOrSave( "Tag", { name : "boxlang" } );
}
```

A new entity is filled from the filter's values, then from `properties`.

{% hint style="warning" %}
Two requests can both find nothing and both insert. Put a unique constraint on the filter's columns so the database rejects the second insert.
{% endhint %}

### Read-Only Loads

Entities you only read don't need dirty checking. Load them read-only to save memory and time:

```js
var orders = entityLoadReadOnly( "Order", { status : "shipped" } );
var orders = entityLoad( "Order", { status : "shipped" }, "createdDate desc", { readOnly : true } );
var user   = entityLoadByPK( "User", 1, { readOnly : true } );

// Everything loaded inside the closure is read-only
var report = ormReadOnly( () => buildReport() );
```

Changes to a read-only entity are never saved. See [Read-only loads](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions#read-only-loads).

## Update

An entity loaded in the current session is managed: the ORM compares it with the database at flush time and writes only what changed. You don't need `entitySave()`:

```js
transaction {
    var user = entityLoadByPKOrFail( "User", 1 );
    user.setEmail( "ann.lee@example.com" );
} // UPDATE runs here
```

Ask what changed before it is saved:

```js
entityIsDirty( user );            // true
entityGetDirtyProperties( user ); // [ "email" ]
ormIsSessionDirty();              // true: something in the session changed
```

## Delete

[entityDelete()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete) deletes an entity, or an array of them. Like saves, the `DELETE` runs at flush time, or right away with `{ flush : true }`:

```js
transaction {
    entityDelete( user );
    entityDelete( entityLoad( "Session", { expired : true } ) );
}
```

Relationships with a `cascade` delete their children too. An entity with [`softDelete`](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/entities#soft-delete) is marked deleted instead of removed, and every load skips it.

To delete many rows without loading them, use a criteria [bulk delete](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria#bulk-updates-and-deletes) (`deleteAll()`) or an HQL `delete` statement.

## The Session

Every entity you load or save lives in the ORM session of the current request until the session closes. These BIFs work with it:

| BIF                                                                                                                           | What it does                                                                                                                                        |
| ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| [entityGetReference( name, id )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)      | A lazy reference by id, without a `SELECT`. Ideal for setting an association when all you have is the id.                                           |
| [entityReload( entity )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)                    | Re-read the entity's values from the database.                                                                                                      |
| [entityMerge( entity )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)                      | Copy a detached entity's state into the session.                                                                                                    |
| [entityEvict( entityOrArray )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)               | Stop tracking entities: later changes are not saved. Nothing is deleted.                                                                            |
| [entityIsAttached( entity )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)            | Whether the entity is in the current session.                                                                                                       |
| [entityLock( entity, \[mode\], \[options\] )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock) | Lock the entity's row until the transaction ends. See [Locking](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions#locking). |
| [ormFlush()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)                                    | Write pending changes now.                                                                                                                          |
| [ormClearSession()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)                      | Drop every entity from the session.                                                                                                                 |

```js
var order = entityNew( "Order" );
order.setCustomer( entityGetReference( "Customer", form.customerId ) ); // no SELECT
entitySave( order );
```

See [Session Management](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/session-management) for how sessions open and close.

## Inspect

| BIF                                                                                                                                                                                                              | Returns                                                        |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| [entityGetName( entity )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)                                                                                                     | The entity name                                                |
| [entityGetId( entity )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)                                                                                                         | The primary key value (a struct for composite keys)            |
| [entityGetDatasource( entityOrName )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)                                                                                   | The datasource the entity is stored in                         |
| [entityGetMetadata( entityOrName )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)                                                                                       | Table, id, properties, relationships and settings, as a struct |
| [entityNameArray()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray), [entityNameList()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist) | The entity names of the application                            |

## Convert

| BIF                                                                                                                                            | Returns                                                                                                                     |
| ---------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| [entityToStruct( entityOrArray, \[options\] )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)             | Structs, ready for JSON. See [Entities as Structs](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs).   |
| [entityLoadAsStruct( name, idOrFilter, \[includes\] )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct) | The same structs, read without loading entities                                                                             |
| [entityToQuery( entityOrArray )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)                            | A query, no relation data. See [Entities as Queries](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/queries). |


# Queries and HQL

Query your entities with HQL, filter-based lookups and named SQL functions

bx-orm gives you three ways to query entities: **HQL** (Hibernate Query Language) for anything beyond a simple lookup, **filter-based queries** for quick equality lookups without writing a query string at all, and the fluent [entityCriteria()](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria) builder, which chains conditions, joins and projections without a query string.

## HQL Queries

HQL looks like SQL, but it queries **entity names and properties**, not table and column names. Use [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery) to run one:

```js
var toyotas = ORMExecuteQuery(
    hql: "FROM Auto WHERE make = :make",
    params: { make: "Toyota" }
);
```

{% hint style="info" %}
Entity and property names are case-insensitive, as in the rest of BoxLang: `FROM auto WHERE MAKE = :make` works. HQL in the declared case runs as is; a wrong-case name is corrected once and the corrected HQL is reused. Text inside string literals is never changed, and a misspelled name still fails with a "Did you mean" suggestion.
{% endhint %}

### Parameters

Bind parameters using either named parameters (`:name`, with a struct of params) or positional parameters (`?`, with an array of params) - don't mix the two styles in the same query:

```js
// Named
ORMExecuteQuery( hql: "FROM Auto WHERE make = :make", params: { make: "Toyota" } );

// Positional
ORMExecuteQuery( hql: "FROM Auto WHERE make = ?", params: [ "Toyota" ] );
```

An array-valued parameter is expanded into a comma-separated list of placeholders automatically, so `IN` clauses work as expected:

```js
ORMExecuteQuery(
    hql: "FROM Auto WHERE make IN (:makes)",
    params: { makes: [ "Toyota", "Honda", "Ford" ] }
);
```

### Options

Pass a struct of options to control pagination, caching, and result shape:

| Option        | Description                                                                                                                                                                                            |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `unique`      | Return a single object (or `null`) instead of an array                                                                                                                                                 |
| `offset`      | Skip this many results                                                                                                                                                                                 |
| `maxResults`  | Limit the number of results returned                                                                                                                                                                   |
| `readOnly`    | Load results as read-only (not tracked for dirty-checking)                                                                                                                                             |
| `datasource`  | Run the query against a specific datasource, instead of the entity's default                                                                                                                           |
| `lock`        | Lock the returned rows until the transaction ends: `read`, `write` or `force`. Needs `transaction{}`. See [Locking](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions#locking) |
| `lockTimeout` | Seconds to wait for the `lock` (`0` means do not wait)                                                                                                                                                 |
| `skipLocked`  | With `lock`, skip rows another transaction has locked instead of waiting                                                                                                                               |
| `asStream`    | Return a Java `Stream` read from the database as it is consumed, instead of an array. See [Streaming Results](#streaming-results)                                                                      |

### Named SQL Functions

HQL can call the SQL functions the application registers with the [`sqlFunctions`](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration#named-sql-functions) setting, by name, like any HQL function:

```js
// Application.bx: sqlFunctions : { nameLen : { sql : "char_length(?1)", returns : "integer" } }
var length = ORMExecuteQuery( "select nameLen( m.name ) from Manufacturer m where m.id = :id", { id : 1 }, true );
```

The same names work in [criteria paths](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria#functions-in-paths). [ormGetSQLFunctions()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions) lists them.

### Update and Delete Queries

HQL `UPDATE` and `DELETE` statements are executed directly against the database (bypassing the second-level cache and entity lifecycle events), and return the number of affected rows instead of a result list:

```js
var rowsUpdated = ORMExecuteQuery( hql: "UPDATE Auto SET discontinued = true WHERE make = :make", params: { make: "Yugo" } );
```

## HQL in the Query Component and queryExecute()

`<bx:query>` (`<cfquery>` in CFML templates) and `queryExecute()` run HQL when you set `dbtype="hql"`. They return the same result as [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery): an array of entities, or an array of rows for a projection. They do not return a query object.

```html
<bx:query name="toyotas" dbtype="hql">
    FROM Auto WHERE make = <bx:queryparam value="#form.make#" sqltype="varchar">
</bx:query>
```

```js
var toyotas = queryExecute(
    "FROM Auto WHERE make = :make",
    { make: "Toyota" },
    { dbtype: "hql" }
);
```

* `<bx:queryparam>` (`<cfqueryparam>`) in the body binds a positional parameter. With a `sqltype` (`cfsqltype`) the value is cast first, so an id that arrives as a string from a form matches an integer property. `list="true"` binds a list for `IN ( ... )`.
* `params` binds named (struct) or positional (array) parameters, as in `ORMExecuteQuery()`.
* `ormoptions` takes the [query options](#options), such as `maxResults`, `offset`, `readOnly` and `unique`. `maxrows`, `timeout` and `datasource` apply too.
* `result` gets a struct with `sql` (the HQL), `recordCount`, `executionTime` and `cached`.

Without `dbtype="hql"`, the query component and `queryExecute()` run SQL as usual.

## Filter-Based Queries

For simple equality lookups, skip HQL entirely and use [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload) with a struct of filter criteria:

```js
// All Toyotas
var toyotas = entityLoad( "Auto", { make: "Toyota" } );

// A single, unique Toyota
var toyota = entityLoad( "Auto", { make: "Toyota" }, true );

// With pagination and ordering
var page = entityLoad( "Auto", { make: "Toyota" }, "model asc", { offset: 0, maxResults: 25 } );
```

Every key in the filter struct must be a valid persistent property name on the entity; each key/value pair is combined with the others using `AND` equality. This only supports equality checks - reach for HQL as soon as you need `LIKE`, ranges, joins, or `OR` logic.

[EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample) works the same way, but takes a sample entity instance instead of a struct:

```js
var sample = entityNew( "Auto", { make: "Toyota" } );
var toyotas = entityLoadByExample( sample );
```

## Streaming Results

Pass `asStream : true` to `ORMExecuteQuery()` or `EntityLoad()` to get a Java `Stream` instead of an array. The rows are read from the database as the stream is consumed, so a large result never sits in memory at once. BoxLang closures work with the stream methods:

```js
var names = ORMExecuteQuery( "from Auto where make = :make", { make : "Toyota" }, false, { asStream : true } )
    .filter( ( auto ) => auto.getYear() > 2020 )
    .map( ( auto ) => auto.getModel() )
    .toList();

var count = entityLoad( "Auto", { make : "Toyota" }, "model", { asStream : true } ).count();
```

The stream holds an open database cursor until it is exhausted or closed, so consume it in the same request (Hibernate closes it with the session at the latest). `asStream` cannot be combined with `unique`, or with an update or delete: those raise an `orm.argument` error. Criteria have the same with [`asStream()`](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria).

## Converting Results to a Query Object

If you need to hand entity results to code that expects a BoxLang `Query` object (e.g. for a report or grid), use [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery):

```js
var toyotas = entityLoad( "Auto", { make: "Toyota" } );
var qryToyotas = entityToQuery( toyotas );
```

The query holds the entity's plain properties only, never relationship data. See [Entities as Queries](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/queries).

## Converting Results to Structs

For JSON APIs and views, [entityToStruct()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct) turns entities into structs, and [entityLoadAsStruct()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct) reads the same structs without loading the entities. See [Entities as Structs](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs).

```js
var toyotas = entityLoadAsStruct( "Auto", { make: "Toyota" }, "", { sortOrder: "model" } );
```

## Where Queries Run

Both HQL and filter-based queries execute against the current request's Hibernate session - see [Session Management](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/session-management) for how that session is opened and when it flushes. If `secondaryCacheEnabled` is on for an entity, HQL queries respect the query cache automatically; see [Caching](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/caching).


# Criteria Queries

Build queries fluently with entityCriteria(): conditions, joins, projections, paging and bulk statements

`entityCriteria()` builds a query one method at a time. You chain conditions, joins, projections and ordering, then run it with a terminal method such as `list()`, `count()`, `get()` or `paginate()`. There is no query string to write, property names are checked as you go, and values are always bound as parameters.

```js
users = entityCriteria( "User" )
    .isEq( "active", true )
    .like( "lastName", "Sm%" )
    .order( "lastName" )
    .list();
```

## How it works

* **Building methods** add to the criteria and return it, so they chain.
* **Terminal methods** run the query and return the result. They never change the criteria, so one criteria can run several queries (`count()` then `list()`, for example).
* `copy()` gives you an independent copy to branch from.
* Method names are case-insensitive and accept positional or named arguments: `isEq( "make", "Ford" )` or `isEq( property = "make", value = "Ford" )`.
* Property names are checked when you add them. A typo fails at once with a suggestion: `Vehicle has no property [mkae]. Did you mean [make]?`
* On a base entity you can also use properties its subclass entities declare. When several subclasses declare the same property (say `costRate` on both `Employee` and `Contractor`, queried from `User`), each row reads its own subclass's value, in projections, conditions and ordering alike.

```js
c = entityCriteria( "Vehicle" ).isEq( "make", "Honda" );
total = c.count();
page  = c.order( "model" ).maxResults( 10 ).list();
```

## Conditions

Every condition is added with `and`. Values are bound as parameters and converted to the property's type, so `isEq( "id", "42" )` works for a numeric id.

| Method (aliases)                                                                               | Meaning                                                                                      |
| ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `isEq( p, v )` (`eq`)                                                                          | `p = v`; a `null` value means `p is null`                                                    |
| `ne( p, v )` (`isNe`)                                                                          | `p <> v`; a `null` value means `p is not null`                                               |
| `isGt` (`gt`), `isGe` (`ge`, `gte`), `isLt` (`lt`), `isLe` (`le`, `lte`)                       | Comparisons                                                                                  |
| `like( p, pattern )`                                                                           | `p like pattern` (you include the `%` wildcards)                                             |
| `ilike( p, pattern )`                                                                          | `like`, ignoring case                                                                        |
| `between( p, min, max )`                                                                       | Inclusive range                                                                              |
| `isIn( p, values )` (`in`, `whereIn`)                                                          | `values` is an array, a comma-separated list, or a subquery. An empty list matches nothing   |
| `isNotIn( p, values )`                                                                         | The opposite of `isIn`                                                                       |
| `isNull( p )`, `isNotNull( p )`                                                                | Null checks                                                                                  |
| `isTrue( p )`, `isFalse( p )`                                                                  | Boolean properties                                                                           |
| `isEmpty( p )`, `isNotEmpty( p )`                                                              | Collections (one-to-many, many-to-many)                                                      |
| `sizeEq`, `sizeNe`, `sizeGt`, `sizeGe`, `sizeLt`, `sizeLe( p, n )`                             | Collection size                                                                              |
| `eqProperty`, `neProperty`, `gtProperty`, `geProperty`, `ltProperty`, `leProperty( p, other )` | Compare two properties                                                                       |
| `idEq( id )`                                                                                   | Match the id. For a composite id pass a struct: `idEq( { make : "Ford", model : "F-150" } )` |
| `sql( fragment, params )` (`sqlRestriction`)                                                   | A native SQL condition, see below                                                            |

### `where()` shorthands

```js
c.where( "make", "Honda" );              // isEq
c.where( "price", ">=", 20000 );         // =, !=, >, >=, <, <=, like, ilike, in, not in
c.where( { make : "Honda", year : 2024 } ); // several isEq; a null value means is null
c.where( ( c ) => c.isEq( "a", 1 ).isEq( "b", 2 ) ); // an and-group
```

### Groups: `anyOf()` and `allOf()`

`anyOf()` joins the conditions of its closure with `or`. `allOf()` joins them with `and`, which is useful inside `anyOf()`.

```js
// make = Honda OR make = Toyota
entityCriteria( "Vehicle" ).anyOf( ( c ) => c.isEq( "make", "Honda" ).isEq( "make", "Toyota" ) );

// (make = Honda AND model like R%) OR year < 2000
entityCriteria( "Vehicle" ).anyOf( ( c ) => c
    .allOf( ( a ) => a.isEq( "make", "Honda" ).like( "model", "R%" ) )
    .isLt( "year", 2000 )
);
```

Several closures passed to `anyOf()` are alternatives, and each closure's own conditions must all match:

```js
entityCriteria( "Vehicle" ).anyOf(
    ( c ) => c.isEq( "make", "Honda" ).isEq( "model", "Civic" ),
    ( c ) => c.isEq( "make", "Ford" )
);
```

Aliases: `$or`, `or`, `orWhere`, `disjunction` for `anyOf`; `$and`, `and`, `conjunction` for `allOf`.

### Negation

`not( closure )` negates a group. Any condition can also be negated with the `not` prefix: `notLike`, `notIn`, `notBetween`, `notEq`, `notEmpty`, ...

```js
entityCriteria( "Vehicle" ).notLike( "make", "Hon%" );
entityCriteria( "Vehicle" ).not( ( c ) => c.isEq( "make", "Honda" ).isEq( "model", "Civic" ) );
```

### Restrictions: `c.restrictions`

`c.restrictions` builds a condition without adding it, the cborm way. Pass the results to `add()`, `or()`, `and()` or `not()`. Every condition method is there, under the same names and aliases, including the `not...` forms, plus `or`, `and` and `not` to nest them. Restrictions and closures can be mixed.

```js
c = entityCriteria( "User" );
r = c.restrictions;

c.or( r.isEq( "role", "admin" ), r.isGt( "age", 30 ) );
c.add( r.like( "name", "A%" ), r.isNotNull( "email" ) );
c.not( r.isEq( "status", "banned" ) );
c.add( r.or( r.isEq( "a", 1 ), r.and( r.isEq( "b", 2 ), r.not( r.isNull( "c" ) ) ) ) );
c.or( r.isEq( "a", 1 ), ( c ) => c.isEq( "b", 2 ) );
```

A restriction is resolved against the criteria it is added to. Calling a method that is not a condition (for example `c.restrictions.list()`) is an `orm.argument` error.

### Native SQL: `sql()`

`sql( fragment, params )` adds a SQL condition. `?` takes the params in order (always bound). `{alias}.column` refers to a column of the entity, and `{property}` (or `{association.property}`) to a property.

```js
c.sql( "upper({alias}.first_name) = ?", [ "LUIS" ] );
c.sql( "lower({make}) = ? or {model} = ?", [ "ford", "Civic" ] );
```

## Associations and joins

A dotted path joins its associations automatically:

```js
entityCriteria( "Vehicle" ).isEq( "manufacturer.name", "Ford Motor Company" );
```

* A condition uses an **inner** join, so rows without the association are left out.
* Inside `anyOf()` and `not()` a **left** join is used, so a row without the association can still match another branch.
* Ordering and projections use a **left** join, so ordering never drops rows.
* The same path is joined once and reused.
* `manufacturer.id` compares the foreign key and needs no join.
* An association can be compared with an id or an entity: `isEq( "manufacturer", 42 )`, `isIn( "manufacturer", [ 1, 42 ] )`.

The root entity's alias is `this` (`this.name`).

### Aliases and join types

```js
entityCriteria( "Vehicle" )
    .joinTo( "manufacturer", "m" )          // alias createAlias; optional third argument: join type
    .isEq( "m.name", "Honda Motor Co." );

c.leftJoin( "manufacturer", "m" );          // also innerJoin, rightJoin, fullJoin
c.joinTo( "manufacturer", "m", "left" );    // inner, left, right, full, or c.LEFT_JOIN (cborm constants)
```

Right and full joins need database support (MySQL and MariaDB have no full join).

### `with{Association}()`

`with{Association}()` makes an association the start of unqualified paths. With a closure it applies to the closure's conditions; without one it applies until `end()`. `createCriteria( association )` is the cborm form.

```js
entityCriteria( "Vehicle" )
    .withManufacturer( ( m ) => m.like( "name", "Honda%" ) )
    .isEq( "model", "Civic" );

entityCriteria( "Vehicle" )
    .withManufacturer( "left" )
        .like( "name", "Honda%" )
    .end()
    .isEq( "model", "Civic" );
```

### Fetching

`fetch( association )` loads an association together with the root rows, so reading it later needs no extra query:

```js
vehicles = entityCriteria( "Vehicle" ).fetch( "manufacturer" ).list();
```

When a condition goes through a to-many association, each root entity is returned once, and `count()` counts each root once.

## Functions in paths

Any property argument can be a function call: in conditions, in `order()`, in `pluck()` and in projections.

```js
entityCriteria( "Order" ).isEq( "year(createdDate)", 2025 );
entityCriteria( "Manufacturer" ).isEq( "lower(name)", "ford motor company" );
entityCriteria( "Manufacturer" ).isEq( "upper(substring(name, 1, 4))", "FORD" );   // nested calls and number literals
entityCriteria( "Manufacturer" ).isEq( "coalesce(address, 'none')", "none" );       // 'quoted strings'
entityCriteria( "Manufacturer" ).isEq( "cast(id as String)", "42" );
entityCriteria( "Vehicle" ).isEq( "lower(manufacturer.name)", "honda motor co." );  // paths join as usual
entityCriteria( "Manufacturer" ).order( "length(name) desc" );
entityCriteria( "Manufacturer" ).pluck( "upper(name)" );
```

* Each argument must be a property path, a nested function call, a number or a `'quoted string'` (`''` escapes a quote). Anything else is an `orm.argument` error: pass other values as the condition value, where they are bound as parameters.
* The function can be an HQL function (`lower`, `upper`, `length`, `substring`, `coalesce`, `year`, `cast`, ...), a function of the database dialect, or one of the application's [named SQL functions](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration#named-sql-functions).
* Property names inside the call are checked like any other path (`lower(nmae)` is an `orm.property.unknown` error with a suggestion).
* An unknown function name is passed to the database, which rejects it when the query runs (`orm.sql`).

## Subqueries

`subquery( entityName, alias )` creates a subquery. Inside it, unqualified paths start at the subquery's entity, and `this.` refers to the outer query's root.

```js
c = entityCriteria( "Manufacturer" );

// manufacturers that make a Honda
c.exists( c.subquery( "Vehicle", "v" ).eqProperty( "v.manufacturer", "this" ).isEq( "make", "Honda" ) );

// manufacturers with no vehicles
c.notExists( c.subquery( "Vehicle", "v" ).eqProperty( "v.manufacturer", "this" ) );

// isIn with the subquery's projection
c.isIn( "id", c.subquery( "Vehicle", "v" ).isEq( "make", "Ford" ).project( ( p ) => p.property( "manufacturer.id" ) ) );
```

The cborm forms are available too: `propertyEq`, `propertyNe`, `propertyGt`, `propertyGe`, `propertyLt`, `propertyLe`, `propertyIn`, `propertyNotIn` compare a property with a subquery, and `subEq`, `subNe`, `subGt`, `subGe`, `subLt`, `subLe`, `subIn`, `subNotIn` compare a value with one:

```js
counted = c.subquery( "Vehicle", "v" ).eqProperty( "v.manufacturer", "this" ).project( ( p ) => p.rowCount() );
c.subLe( 2, counted );   // manufacturers with at least 2 vehicles
```

Quantified forms compare with every row (`All`) or at least one row (`Some`) of the subquery, e.g. `x >= all (select ...)`. The cborm set:

| Compare a property                    | Compare a value               |
| ------------------------------------- | ----------------------------- |
| `propertyEqAll( property, subquery )` | `subEqAll( value, subquery )` |
| `propertyGtAll`, `propertyGtSome`     | `subGtAll`, `subGtSome`       |
| `propertyGeAll`, `propertyGeSome`     | `subGeAll`, `subGeSome`       |
| `propertyLtAll`, `propertyLtSome`     | `subLtAll`, `subLtSome`       |
| `propertyLeAll`, `propertyLeSome`     | `subLeAll`, `subLeSome`       |

```js
prices = c.subquery( "Product", "p" ).isEq( "p.category", "books" ).project( ( p ) => p.property( "price" ) );
c.propertyGeAll( "price", prices );   // at least as expensive as every book
c.subLtSome( 10, prices );            // some book costs more than 10
```

## Results

### Projections

`project()` selects columns instead of entities. Each method takes a property and an optional alias:

```js
entityCriteria( "Vehicle" )
    .project( ( p ) => p.group( "make" ).count( "vin", "total" ).avg( "price" ) )
    .asStruct()
    .list();
// [ { make : "Ford", total : 1, price : ... }, ... ]
```

Methods: `property`, `group` (`groupProperty`), `sum`, `avg`, `min`, `max`, `count`, `countDistinct`, `rowCount( [alias] )`, `id( [alias] )`. An alias defaults to the property name.

The cborm form, `withProjections()`, takes a struct or named arguments whose values are `property[:alias]` lists:

```js
c.withProjections( groupProperty = "make", count = "vin:total", distinct = "model" );
```

With one projection, `list()` returns plain values; with several, one array per row, or one struct per row with `asStruct()`.

### Result shapes

| Method                            | `list()` returns                                                                                           |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| (default)                         | Entities                                                                                                   |
| `asStruct()`                      | One struct per row. Without projections: the id and plain properties. Date values are ISO 8601 strings     |
| `asStruct( includes, [options] )` | Structs built like `entityToStruct()`, read with projection queries instead of loading entities. See below |
| `asQuery()`                       | A query                                                                                                    |
| `asStream()`                      | A Java stream                                                                                              |
| `asDistinct()`                    | Distinct rows                                                                                              |

### Structs with includes

`asStruct( includes, [options] )` returns the structs [`entityToStruct()`](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs) would build, without loading any entity: the criteria's conditions and order select the rows, one projection query reads the plain values and to-one associations, and each to-many association is one more query. The entity's `this.memento`, excludes, mappers, defaults and profiles apply; options are `excludes`, `mappers`, `defaults`, `ignoreDefaults` and `profile`.

```js
users = entityCriteria( "User" )
    .isEq( "active", true )
    .order( "lastName" )
    .asStruct( "id,lastName,role.name,orders", { excludes : "orders.notes" } )
    .paginate( page = 1, maxRows = 25 );
```

It works with `list()`, `get()`, `first()` and `paginate()`. With `each()` or `chunk()` it is an `orm.argument` error. See [Entities as Structs](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs) for the rules.

### Ordering and paging

```js
c.order( "lastName" );                    // asc by default
c.order( "lastName", "desc" );
c.order( "lastName", "asc", true );       // ignore case (text properties)
c.orderBy( "make desc, model asc" );
c.orderByDesc( "createdDate" );
c.firstResult( 20 ).maxResults( 10 );     // aliases: offset, limit
```

Without an `order()`, `list()`, `get()`, `first()` and `paginate()` return entity rows in the entity's [`defaultSort`](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/entities#default-sort-order) order, when it declares one. An explicit `order()` replaces it, and it is not used for counts or projections.

### Options

| Method                     | Effect                                                                                                            |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `cache( [region] )`        | Cache the result in the second-level query cache (needs `secondaryCacheEnabled`); `cache( false )` to turn it off |
| `readOnly()`               | Loaded entities are read-only: their changes are not saved                                                        |
| `timeout( seconds )`       | Query timeout                                                                                                     |
| `fetchSize( n )`           | JDBC fetch size                                                                                                   |
| `comment( text )`          | SQL comment (shown with `logSQL` in the ORM settings)                                                             |
| `queryHint( name, value )` | A Hibernate query hint                                                                                            |

## Terminal methods

| Method                                     | Returns                                                                                                                                   |
| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `list()`                                   | The rows. cborm arguments work too: `list( max, offset, timeout, sortOrder, ignoreCase, asQuery )`                                        |
| `count( [property] )`                      | The number of matching entities, or of distinct values of a property                                                                      |
| `exists()`                                 | Whether any row matches                                                                                                                   |
| `get( [uniqueFirst] )`                     | The single match, or null. More than one match is an `orm.query.nonUnique` error unless `uniqueFirst` is true                             |
| `getOrFail( [uniqueFirst] )`               | Like `get()`, but no match is an `orm.notFound` error                                                                                     |
| `first()`                                  | The first row in order, or null                                                                                                           |
| `firstOrFail()`                            | Like `first()`, but no row is an `orm.notFound` error                                                                                     |
| `paginate( page = 1, maxRows = 25 )`       | `{ results, pagination : { page, maxRows, offset, totalRecords, totalPages } }`                                                           |
| `simplePaginate( page = 1, maxRows = 25 )` | `{ results, pagination : { page, maxRows, hasMore } }`, without counting                                                                  |
| `pluck( property )`                        | One property's values, in order                                                                                                           |
| `sum`, `avg`, `min`, `max( property )`     | An aggregate                                                                                                                              |
| `each( callback, [size] )`                 | Calls the closure once per row; returns the row count                                                                                     |
| `chunk( size, callback )`                  | Calls the closure with each batch of rows; returns the row count                                                                          |
| `updateAll( values )`                      | Sets properties on every matching row with one `UPDATE`; returns the row count. See [Bulk updates and deletes](#bulk-updates-and-deletes) |
| `deleteAll()`                              | Deletes every matching row with one `DELETE`; returns the row count. See [Bulk updates and deletes](#bulk-updates-and-deletes)            |

`each()` and `chunk()` read the rows in batches (100 by default for `each()`). After each batch the session is flushed, so changes made in the callback are saved, and cleared, so memory stays flat. Without an explicit order, batches follow the id (not the entity's `defaultSort`), so deleting or changing rows in the callback never skips any.

```js
entityCriteria( "User" ).isFalse( "verified" ).chunk( 500, ( users ) => {
    users.each( ( u ) => u.setReminderSent( true ) );
} );
```

## Bulk updates and deletes

`updateAll()` and `deleteAll()` change every matching row with a single HQL statement, without loading any entity. Both return the number of rows changed.

```js
// one UPDATE
count = entityCriteria( "Order" )
    .isEq( "status", "pending" )
    .isLt( "createdDate", dateAdd( "d", -30, now() ) )
    .updateAll( { status : "expired", note : null } );

// one DELETE
count = entityCriteria( "Session" ).isLt( "expires", now() ).deleteAll();
```

`updateAll()` takes a struct of property values. It can set plain properties and to-one associations (pass an entity or an id), and `null` values are allowed. Collections cannot be set.

`deleteAll()` on a [`softDelete`](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/entities#soft-delete) entity marks the rows deleted instead of removing them.

Conditions through an association (`isEq( "manufacturer.name", "Ford" )`) are turned into an id subquery, which needs an entity with a single id.

{% hint style="warning" %}
Bulk statements run in the database only:

* No entity events fire.
* No cascades: child rows are not deleted, so foreign keys can reject a `deleteAll()`.
* No version increments and no [`autoTimestamp`](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/properties#automatic-timestamps) values.
* Entities already loaded in the session keep their old values. Reload them (`entityReload()`) or clear the session (`ormClearSession()`) to see the change.

Pending changes in the session are flushed before the statement runs.
{% endhint %}

## Locking rows

`lock( [mode], [options] )` locks the rows that `list()`, `get()` and `first()` return, until the transaction ends. Counts and aggregates are not locked. The mode is `write` (the default, exclusive), `read` (shared) or `force` (exclusive, and increments the version); see [entityLock()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock). Options are `timeout` (seconds to wait; `0` means do not wait) and `skipLocked`.

A queue worker that claims up to 10 new jobs, skipping jobs another worker has already locked:

```js
transaction {
    jobs = entityCriteria( "Job" )
        .isEq( "status", "new" )
        .lock( "write", { skipLocked : true } )
        .maxResults( 10 )
        .list();
    jobs.each( ( job ) => job.setStatus( "running" ) );
}
```

`lock()` must run inside `transaction{}`, otherwise an `orm.argument` error is raised.

## Flow helpers

```js
entityCriteria( "User" )
    .when( len( search ), ( c ) => c.like( "lastName", search & "%" ) )
    .when( role == "admin", ( c ) => c.isTrue( "isAdmin" ), ( c ) => c.isFalse( "isAdmin" ) )
    .unless( showDeleted, ( c ) => c.isFalse( "isDeleted" ) )
    .apply( activeUsers )        // a reusable closure: activeUsers = ( c ) => c.isTrue( "active" )
    .peek( ( c ) => writeLog( c.count() ) )
    .list();
```

## Seeing the query

| Method                                                               | What it does                                                                                                                                                                         |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `getSQL( [executable], [format] )`                                   | The SQL Hibernate would run, without running it. `executable = true` puts the values in (for pasting into a SQL tool); `format = false` keeps it on one line. Paging is not included |
| `peekSQL( callback )`                                                | Calls the closure with the SQL and keeps chaining                                                                                                                                    |
| `logSQL( [label], [executable], [format] )`                          | Appends `{ type : label, sql }` to the SQL log, writes the SQL to the ORM log, and keeps chaining. The label defaults to `Criteria`                                                  |
| `getSqlLog()`                                                        | The SQL log entries, oldest first                                                                                                                                                    |
| `startSqlLog( [returnExecutableSql], [formatSql] )` / `stopSqlLog()` | Turn the SQL log on and off (cborm). `startSqlLog()` also sets how later `logSQL()` calls write the SQL; both default to `false`                                                     |
| `canLogSql()` / `getSqlLoggerActive()`                               | Whether `startSqlLog()` turned the log on                                                                                                                                            |
| `getHQL()`                                                           | The HQL the criteria compiles to                                                                                                                                                     |
| `toString()` / `writeDump()`                                         | The calls you made, the HQL, the parameters and the SQL                                                                                                                              |

```js
writeDump( entityCriteria( "Vehicle" ).isEq( "make", "Honda" ).like( "manufacturer.name", "Honda%" ) );
// entityCriteria( "Vehicle" )
//     .isEq( "make", "Honda" )
//     .like( "manufacturer.name", "Honda%" )
// HQL: select bx_this from Vehicle bx_this inner join bx_this.manufacturer bx_j1 where (bx_this.make = ?1 and bx_j1.name like ?2)
// Params: ["Honda", "Honda%"]
// SQL: select ...
```

```js
c = entityCriteria( "Vehicle" ).startSqlLog( returnExecutableSql = true );
c.isEq( "make", "Honda" ).logSQL( "hondas" );
c.like( "model", "C%" ).logSQL( "civics" );
writeDump( c.getSqlLog() );   // [ { type : "hondas", sql : "..." }, { type : "civics", sql : "..." } ]
```

`copy()` copies the log. Nothing is logged on its own: call `logSQL()` where you want an entry.

`getSQL()` needs bx-orm's Hibernate statement inspector. If your ORM settings configure your own (`hibernate.session_factory.statement_inspector`), `getSQL()` says so.

## Interception points

The cborm criteria events are announced as BoxLang interception points. Each receives `criteriaBuilder`, and the `after` points also receive the result.

| Point                        | Extra data                    |
| ---------------------------- | ----------------------------- |
| `beforeCriteriaBuilderList`  |                               |
| `afterCriteriaBuilderList`   | `results`                     |
| `beforeCriteriaBuilderCount` |                               |
| `afterCriteriaBuilderCount`  | `count`                       |
| `beforeCriteriaBuilderGet`   |                               |
| `afterCriteriaBuilderGet`    | `result`                      |
| `onCriteriaBuilderAddition`  | `type` (the condition method) |

## Errors

| Error                    | When                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `orm.property.unknown`   | A property that does not exist (including in `updateAll()`), or a path through a plain value, with a suggestion                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `orm.property.ambiguous` | A base-entity property that several subclass entities declare with different types, or a path that continues through such a property                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `orm.argument`           | An unknown method or argument, a bad join type, operator or sort direction, a subquery run on its own; a function path argument that is not a path, function, number or quoted string, or unbalanced parentheses; `asStruct( includes )` with `each()` or `chunk()`, with a getter-only include, a value collection or a composite-id entity; `updateAll()` with an empty struct or a collection property; `updateAll()` or `deleteAll()` with `maxResults()` or `firstResult()`, or with association conditions on a composite-id entity; `lock()` with an unknown mode or outside `transaction{}` |
| `orm.query.nonUnique`    | `get()` matched more than one row                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `orm.notFound`           | `getOrFail()` or `firstOrFail()` matched nothing                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `orm.query.parameter`    | `sql()` params do not match its `?` placeholders                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `orm.sql`                | The database rejected the query, for example an unknown function name in a path                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |

See [Errors and Diagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/errors-and-diagnostics) for the full catalog.


# Static Entity Methods

Load, find, count and write entities straight from the entity class, like User::get( 1 )

Every entity class gets static helper methods at ORM startup, so you can work with an entity without a service object or a base class:

```js
user  = User::get( 1 );
admin = User::findWhere( { email : "admin@example.com" } );
total = User::count( { active : true } );
page  = User::list( { max : 20, offset : 40, sort : "lastName" } );
```

Each method calls the matching built-in function with the entity name filled in, so it behaves exactly like that function: same session, events, errors and options.

## Methods

### Loading

| Method               | Returns                                                                                     | Same as                                    |
| -------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------ |
| `get( id )`          | The entity, or `null`                                                                       | `entityLoadByPK( "User", id )`             |
| `getOrFail( id )`    | The entity, or an `orm.notFound` error                                                      | `entityLoadByPKOrFail( "User", id )`       |
| `getAll( [ids] )`    | Every entity when no ids are given; else the entities for an array or list of ids, in order | `entityLoad( "User" )`, `entityLoadByPK()` |
| `read( id )`         | The entity, read-only: changes to it are never saved                                        | `entityLoadByPK( …, { readOnly : true } )` |
| `getReference( id )` | A reference that loads on first use, without a `SELECT`                                     | `entityGetReference( "User", id )`         |

### Finding and counting

| Method                                        | Returns                                                                                                                                                                                          |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `findWhere( filter, [options] )`              | The one entity matching the filter, or `null`. More than one match is an `orm.query.nonUnique` error; pass `{ uniqueFirst : true }` to take the first.                                           |
| `findWhereOrFail( filter, [options] )`        | Like `findWhere()`, but no match is an `orm.notFound` error                                                                                                                                      |
| `findAllWhere( [filter], [sort], [options] )` | An array of the matching entities                                                                                                                                                                |
| `first( [filter], [sort] )`                   | The first matching entity, or `null`. Without a sort, the entity's `defaultSort` applies.                                                                                                        |
| `exists( idOrFilter )`                        | `true` when an entity with that id, or matching that filter, exists                                                                                                                              |
| `count( [filter] )`                           | The number of matching entities                                                                                                                                                                  |
| `list( [options] )`                           | The entities, with `max`, `offset` and `sort`, plus any [`entityLoad()`](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload) option such as `readOnly` or `asStream` |

### Queries

| Method                                     | Returns                                                                                                                |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `executeQuery( hql, [params], [options] )` | The same as [`ormExecuteQuery()`](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery) |
| `criteria()`, `newCriteria()`              | A new [criteria query](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria) for the entity           |

### Creating and writing

| Method                                  | Returns                                                                           |
| --------------------------------------- | --------------------------------------------------------------------------------- |
| `new( [properties] )`                   | A new, unsaved entity (`entityNew()`)                                             |
| `firstOrNew( filter, [properties] )`    | The entity matching the filter, or a new unsaved one (`entityLoadOrNew()`)        |
| `firstOrCreate( filter, [properties] )` | The entity matching the filter, or a new one that is saved (`entityLoadOrSave()`) |
| `updateWhere( filter, values )`         | The number of rows updated, in one statement                                      |
| `deleteWhere( filter )`                 | The number of rows deleted, in one statement                                      |

`updateWhere()` and `deleteWhere()` run one statement: no entity events or cascades fire, and entities already loaded are not refreshed. They refuse an empty filter (`orm.argument`), since it would affect every row. To affect every row on purpose, use `User::criteria().updateAll( values )` or `User::criteria().deleteAll()`.

Arguments can be positional or named:

```js
User::get( id = 1 );
User::findAllWhere( filter = { active : true }, sort = "lastName" );
```

## Examples

```js
// Load or fail with a clear error
order = Order::getOrFail( rc.orderId );

// Find, or create on first use
tag = Tag::firstOrCreate( { name : rc.tag } );

// Page through results
users = User::list( { max : 25, offset : ( rc.page - 1 ) * 25, sort : "lastName, firstName" } );

// Anything more complex: start a criteria query
recent = Order::criteria()
	.isEq( "status", "shipped" )
	.isGt( "shippedDate", dateAdd( "d", -7, now() ) )
	.order( "shippedDate", "desc" )
	.list();

// Bulk changes
transaction {
	archived = Order::updateWhere( { status : "shipped" }, { status : "archived" } );
}
```

## Rules

* **Your methods win.** A static method the entity declares itself is kept, never replaced.
* **Instances can call them too.** BoxLang lets an instance call its class's static methods, so `user.count()` works. An instance method with the same name, declared on the entity or a parent such as cborm's `ActiveEntity`, takes precedence.
* **Methods exist once the ORM has started.** They are added when the application's ORM starts, and again on `ormReload()`.

## Turning them off

The methods are on by default. To leave your entity classes untouched:

```js
this.ormSettings = {
	staticMethods : false
};
```

## In development

When you edit an entity file, BoxLang recompiles the class, and the new class starts without the static methods. bx-orm adds them back:

* at the start of the next request, when the BoxLang runtime's trusted cache is off (the usual development setting);
* as soon as an instance of the edited entity is created, for example by `entityNew()` or a load.

With the trusted cache on (the usual production setting), classes are never recompiled, so this check does not run.


# Entities as Structs

Turn entities into structs for JSON APIs and views, with or without loading them

JSON APIs and views usually need plain structs, not entities. bx-orm builds them three ways, with the same rules and the same output:

| Use                                                                                                                                                               | When                                                                 |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| [entityToStruct( entityOrArray, \[options\] )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)                                | You already have the entities                                        |
| [entityLoadAsStruct( entityName, idOrFilter, \[includes\], \[options\] )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct) | Load by id or filter straight into structs, without loading entities |
| [`asStruct( includes, [options] )`](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria#structs-with-includes) on `entityCriteria()`            | Any criteria query, straight into structs                            |

```js
user  = entityToStruct( entityLoadByPK( "User", 42 ), { includes : "role.name" } );
user  = entityLoadAsStruct( "User", 42, "role.name" );
users = entityCriteria( "User" ).isEq( "active", true ).asStruct( "role.name" ).list();
```

Need a `Query` object instead? See [Entities as Queries](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/queries).

The rules follow [mementifier](https://forgebox.io/view/mementifier), so an entity's existing `this.memento` works as is.

## What goes in the struct

`entityToStruct()` reads each value through the entity's getter when it has one, else from the entity's variables scope. BoxLang gives every persistent property an implicit getter, so a getter you write yourself (for example `getEmail()` returning `lcase( variables.email )`) replaces it and shapes the output.

By default a struct holds the entity's id and its plain properties (columns, version and timestamp properties), not its associations. The options change that:

| Option           | Meaning                                                                                                                                                                                                                                  |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `includes`       | What to add, as a list or an array: property names, getter names (without `get`), or dotted association paths such as `role.name`. `"lastLoginTime:lastLogin"` writes the value under another key. `"*"` stands for every plain property |
| `excludes`       | What to leave out, also with dotted paths: `"passwordHash,orders.notes"`                                                                                                                                                                 |
| `mappers`        | A struct of key to `( value, memento ) => newValue`. See [Mappers](#mappers)                                                                                                                                                             |
| `defaults`       | A struct of key to the value to use when the value is null                                                                                                                                                                               |
| `ignoreDefaults` | Ignore the entity's `this.memento` default includes and excludes                                                                                                                                                                         |
| `profile`        | Use one of the entity's `this.memento.profiles`                                                                                                                                                                                          |

`entityLoadAsStruct()` takes `includes` as its own argument and the rest in its options.

Other rules:

* A null value becomes the matching `defaults` entry, otherwise an empty string. A null collection becomes an empty array.
* Dates are ISO 8601 strings, so every struct serializes the same way: date-times as `yyyy-MM-ddTHH:mm:ss` plus the offset (`2024-03-05T10:20:30Z`), dates as `yyyy-MM-dd` and times as `HH:mm:ss`.
* An include that is neither a property, a getter nor a mapper key is an `orm.property.unknown` error that suggests the right name. (mementifier skips it silently.)

## Associations

An association is written as a struct (to-one) or an array of structs (to-many):

```js
entityToStruct( author, { includes : "posts" } );
// { id : 901, firstName : "Ann", ..., posts : [ { id : 901, title : "First" }, { id : 902, title : "Second" } ] }

entityToStruct( post, { includes : "author.firstName" } );
// { id : 902, title : "Second", author : { firstName : "Ann" } }
```

* An association included on its own (`"posts"`) uses the associated entity's own defaults (its `this.memento`, or its id and plain properties).
* With paths below it (`"author.firstName"`), only those fields are written.
* Paths can go deeper: `"orders.items.product.name"`.
* Excludes work the same way: `"posts.title"` leaves the title out of each post.
* An entity that is already being written higher up the same branch is written as its id, so cycles end: `entityToStruct( author, { includes : "posts.author" } )` writes each post's `author` as `901`.

## Mappers

A mapper is called with the value and the struct being built, and returns the new value. Mappers run last, once every key is filled, on the keys the struct holds:

```js
entityToStruct( user, {
    mappers : {
        email : ( value ) => lcase( value ),
        name  : ( value, memento ) => memento.firstName & " " & memento.lastName
    },
    includes : "name"
} );
```

An include that is neither a property nor a getter, but has a mapper, is a computed key: the mapper builds it (above, `name`).

The caller's `mappers` and `defaults` apply to the top-level entity. Associated entities use their own `this.memento`.

## `this.memento`

An entity describes its default struct with mementifier's `this.memento`:

```js
@persistent
@table( "authors" )
class {
    @fieldtype( "id" )
    @generator( "increment" )
    property id;

    property firstName;
    property lastName;
    property nickName;
    property passwordHash;

    @ormtype( "timestamp" )
    property joined;

    @fieldtype( "one-to-many" )
    @cfc( "Post" )
    @fkcolumn( "author_id" )
    @inverse
    property posts;

    this.memento = {
        defaultIncludes : [ "id", "firstName", "lastName", "nickName", "fullName", "joined", "initials" ],
        defaultExcludes : [],
        neverInclude    : [ "passwordHash" ],
        defaults        : { nickName : "none" },
        mappers         : {
            lastName : ( value, memento ) => ucase( value ),
            initials : ( value, memento ) => left( memento.firstName, 1 ) & left( memento.lastName, 1 )
        },
        profiles        : {
            export : { defaultIncludes : [ "id", "lastName" ], mappers : {} }
        }
    };

    function getFullName() {
        return getFirstName() & " " & getLastName();
    }
}
```

```js
entityToStruct( author );
// { id : 901, firstName : "Ann", lastName : "BAKER", nickName : "none", fullName : "Ann Baker",
//   joined : "2024-03-05T10:20:30Z", initials : "AB" }
```

| Key               | Meaning                                                                                                            |
| ----------------- | ------------------------------------------------------------------------------------------------------------------ |
| `defaultIncludes` | What the struct holds by default. Without it: the id and plain properties, and the caller's `includes` add to them |
| `defaultExcludes` | What is left out by default                                                                                        |
| `neverInclude`    | What is never written, even when the caller includes it                                                            |
| `defaults`        | Values for nulls                                                                                                   |
| `mappers`         | Mappers, as above. The caller's mappers replace one for the same key                                               |
| `profiles`        | Named variations, see below                                                                                        |

The caller's `includes` and `excludes` add to the defaults. `ignoreDefaults : true` drops `defaultIncludes` and `defaultExcludes` (`neverInclude` still applies).

### Profiles

A profile is a named set of `this.memento` keys. With `{ profile : "export" }`, the keys the profile defines replace the base ones, and the other base keys stay. The profile applies down the whole graph, to every associated entity that defines it:

```js
entityToStruct( author, { profile : "export" } );
// { id : 901, lastName : "Baker" }   (the profile's mappers are empty, so lastName is not upper-cased)
```

## Without loading entities

`entityLoadAsStruct()` and criteria `asStruct( includes )` read the structs with projection queries, so no entity is loaded into the session:

* One query reads the plain values of the root entity and of every to-one association in the includes (left joins, so a missing association is written as its default, an empty string).
* Each to-many association is one more query, limited to the ids just read, and its rows are grouped back into their parents. Collections come back in id order.

The output matches `entityToStruct()` for the same includes, getters included: when a property has a getter you wrote (such as `getEmail()` above), the row's plain values are copied into a scratch instance of the entity and the getter is called on it. The getter can read the entity's other plain properties; associations are not loaded there, so a getter that walks an association needs `entityToStruct()`. What cannot be read without an entity:

* **Getter-only includes** (a getter that is not a property, such as `fullName`): one listed in the entity's `this.memento` defaults is left out; one you include yourself is an `orm.argument` error. Compute the key with a mapper instead, or use `entityToStruct()`.
* **Value collections** (`@fieldtype( "collection" )`) and **entities with a composite id** are `orm.argument` errors.

```js
// by id: a struct, or null
user = entityLoadAsStruct( "User", 42, "role.name,orders" );

// by filter: an array of structs
users = entityLoadAsStruct( "User", { active : true }, "", { sortOrder : "lastName", maxResults : 20, offset : 40 } );

// by filter, one struct (several matches: orm.query.nonUnique)
user = entityLoadAsStruct( "User", { email : "ann@example.com" }, "", { unique : true } );

// any criteria query: list(), get(), first() or paginate()
page = entityCriteria( "User" )
    .isEq( "active", true )
    .order( "lastName" )
    .asStruct( "role.name", { profile : "list" } )
    .paginate( page = 2, maxRows = 25 );
```

`asStruct()` without arguments is different: it returns the plain columns of each row (or the projections), with ISO 8601 dates, and does not use `this.memento`.


# Entities as Queries

Turn entities into a BoxLang query for reports, grids and exports

When code expects a BoxLang `Query` object (a report, a data grid, a CSV export, `queryExecute()`-style helpers), convert your entities with [entityToQuery()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery):

```js
vehicles    = entityLoad( "Vehicle", { make : "Ford" } );
qryVehicles = entityToQuery( vehicles );

// one entity gives a one-row query
qryVehicle = entityToQuery( entityLoadByPK( "Vehicle", "1HGCM82633A123456" ) );
```

## What goes in the query

One row per entity, one column per **plain persistent property**:

| Included                                                                  | Not included                                                              |
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| The id property                                                           | Relationships: `one-to-one`, `one-to-many`, `many-to-one`, `many-to-many` |
| Column properties                                                         | Non-persistent properties (`@persistent( false )`)                        |
| Version and timestamp properties                                          |                                                                           |
| Properties inherited from a persistent parent entity or mapped superclass |                                                                           |

{% hint style="warning" %}
**The result query will not contain any relation data.** Relationship properties do not appear as columns at all, not even as empty ones, and no association is loaded. This matches Adobe ColdFusion and Lucee.
{% endhint %}

Given this entity:

```js
@persistent
@entityName( "Vehicle" )
class {
    @fieldtype( "id" )
    @generator( "assigned" )
    property vin;

    property make;
    property model;

    @fieldtype( "many-to-one" )
    @cfc( "Manufacturer" )
    @fkcolumn( "FK_manufacturer" )
    property manufacturer;

    @fieldtype( "many-to-many" )
    @cfc( "Feature" )
    @linktable( "vehicle_features" )
    property features;
}
```

`entityToQuery( vehicles )` returns the columns `vin`, `make` and `model`. There is no `manufacturer` or `features` column.

## Arrays and the entity name

* An array becomes one row per entity. All entities in the array must be of the same type.
* The entity name is read from the first entity. Pass it as the second argument to skip that lookup, or to pick the entity whose columns you want with inheritance mappings.
* An empty array with an entity name gives an empty query with that entity's columns. Without a name it gives an empty query with a single `id` column.

```js
qry = entityToQuery( entityLoad( "Vehicle", { make : "Honda" } ), "Vehicle" );
qry = entityToQuery( [], "Vehicle" ); // 0 rows, columns vin, make, model
```

## Need related data?

Use a projection query instead, and select the related values as columns. [entityCriteria()](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria) joins dotted paths for you and returns a query with `asQuery()`:

```js
qry = entityCriteria( "Vehicle" )
    .isEq( "make", "Ford" )
    .project( ( p ) => p.property( "vin" ).property( "model" ).property( "manufacturer.name", "manufacturer" ) )
    .asQuery()
    .list();
```

For JSON and views that need nested relationships, use [Entities as Structs](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs): `entityToStruct()` and `entityLoadAsStruct()` take `includes` such as `"manufacturer.name,features"`.

## Related

* [entityToQuery()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [Entities as Structs](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs)
* [Criteria Queries](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria)
* [Querying](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/querying)


# Transactions

How ORM work shares the BoxLang transaction: commit, rollback, locking and read-only loads

A transaction is any discrete unit of work used to pool database queries and statements to execute at once. This helps us to prevent a failed update from leaving the database in a broken state.

To denote a transaction, we wrap it in the `transaction{}` tag:

```js
transaction{
    // queries go here
}
```

The transaction will automatically commit (persist) at the end of the transaction block.

{% hint style="info" %}
**One transaction for ORM and SQL:** ORM work inside `transaction{}` uses that transaction's JDBC connection. ORM writes and `queryExecute()` calls on the same datasource commit together and roll back together. BoxLang does the real commit or rollback.

ORM sessions on other datasources are flushed on commit and cleared on rollback, but their SQL is not part of the transaction.
{% endhint %}

## Transaction Rollback

A transaction rollback undoes all changes made within the transaction block and prevents them from being persisted to the database. This is useful when an error occurs or business rules are violated.

### Automatic Rollback on Error

If an exception occurs within a transaction block, the transaction is automatically rolled back:

```js
try {
    transaction {
        var user = entityNew( "User" );
        user.setUsername( "johndoe" );
        entitySave( user );
        
        // This will throw an exception and trigger automatic rollback
        var invalid = entityLoadByPK( "NonExistentEntity", 1 );
    }
} catch ( any e ) {
    // Transaction has been rolled back, user was not saved
    writeOutput( "Error: #e.message#" );
}
```

### Manual Rollback

You can manually trigger a rollback using `transactionRollback()`:

```js
transaction {
    var account = entityLoadByPK( "Account", 1 );
    var newBalance = account.getBalance() - 100;
    
    // Business rule: account balance cannot go negative
    if ( newBalance < 0 ) {
        transactionRollback();
        writeOutput( "Insufficient funds - transaction rolled back" );
    } else {
        account.setBalance( newBalance );
        entitySave( account );
        // Transaction commits automatically at end of block
    }
}
```

The alternative syntax `action="rollback"` is also supported.

## Transaction Commit

A transaction commit persists all changes made within the transaction block to the database. By default, transactions automatically commit when the transaction block completes successfully.

### Automatic Commit

When a transaction block completes without errors or explicit rollback, it will be automatically committed:

```js
transaction {
    // Create a new user
    var user = entityNew( "User" );
    user.setUsername( "janedoe" );
    user.setEmail( "jane@example.com" );
    entitySave( user );
    
    // Create a profile for the user
    var profile = entityNew( "Profile" );
    profile.setUser( user );
    profile.setBio( "Software developer" );
    entitySave( profile );
    
    // Both saves commit together at the end of this block
}
```

### Manual Commit

You can manually commit a transaction using `transactionCommit()` when you need to persist changes before the end of the block:

```js
transaction {
    // First batch of operations
    var batch1 = entityNew( "Batch" );
    batch1.setName( "Batch 1" );
    entitySave( batch1 );
    transactionCommit();
    writeOutput( "Batch 1 committed successfully" );
    
    // Second batch of operations
    var batch2 = entityNew( "Batch" );
    batch2.setName( "Batch 2" );
    entitySave( batch2 );
    transactionCommit();
    writeOutput( "Batch 2 committed successfully" );
}
```

The alternative syntax `action="commit"` is also supported.

{% hint style="warning" %}
**Important:** When you manually commit a transaction using `transactionCommit()`, it effectively closes the current transaction and immediately begins a new one. This means that any subsequent operations within the transaction block will be part of a new transaction context.
{% endhint %}

### Named Transactions

Nested transactions are handled by BoxLang. With BoxLang's default setting (`enableNestedTransactions=false`), a nested `transaction{}` is part of the outer transaction. A commit inside the nested block commits the outer transaction too:

```js
transaction name="outer" {
    var customer = entityNew( "Customer" );
    customer.setName( "Acme Corp" );
    entitySave( customer );

    transaction name="inner" {
        var invoice = entityNew( "Invoice" );
        invoice.setCustomer( customer );
        invoice.setAmount( 1000.00 );
        entitySave( invoice );

        // With the default setting, this also commits the customer
        transactionCommit();
    }
}
```

A commit or rollback scoped to the nested block (with savepoints) needs BoxLang's experimental `enableNestedTransactions` runtime setting. bx-orm follows whatever BoxLang commits or rolls back.

## After the commit

To run code only once ORM writes are committed (and never for rolled-back ones), use the [`postCommit`](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/events#postcommit-after-the-commit) event. Inside `transaction{}` it fires for each written entity after BoxLang commits the transaction, when the transaction ends, in write order.

```js
@persistent
class {
	function postCommit( entity, action ) {
		// insert, update or delete: the row is committed
	}
}
```

## Locking

A database lock stops other transactions from changing the locked rows until your transaction ends (a `write` lock also stops them from locking the rows). Locks need a transaction: taking one outside `transaction{}` raises an `orm.argument` error, and every lock is released when the transaction commits or rolls back.

```js
transaction {
    var account = entityLoadByPK( "Account", 1, { lock : "write" } );
    account.setBalance( account.getBalance() - 100 );
}
```

| To lock                          | Use                                                                                                                           |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| An entity you already loaded     | [entityLock( entity, \[mode\], \[options\] )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock) |
| An entity while loading it by id | The `lock` option of [entityLoadByPK()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)   |
| The rows of a criteria query     | [`lock()`](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria#locking-rows) on `entityCriteria()`          |
| The rows of an HQL query         | The `lock` option of [ORMExecuteQuery()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery) |

The modes are `write` (exclusive, the default), `read` (shared) and `force` (exclusive, and increments the version of a versioned entity). Each also takes a lock timeout in seconds (`timeout`, or `lockTimeout` for `ormExecuteQuery()`; `0` means do not wait) and `skipLocked`.

### Read-only loads

When you only read entities (reports, exports), load them read-only. They are not dirty-checked, so flushes are cheaper, and changes made to them by mistake are never saved:

* [ormReadOnly( callback )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly) makes every entity loaded inside the closure read-only.
* [entityLoadReadOnly()](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly) is `entityLoad()` with read-only results.
* The `readOnly` option of `entityLoad()`, `entityLoadByPK()` and `ormExecuteQuery()`, and `readOnly()` on `entityCriteria()`.

## Transaction Savepoint

ORM work rides the BoxLang transaction, so savepoints are BoxLang's. They only exist when BoxLang's experimental `enableNestedTransactions` runtime setting is on. With the default setting, you cannot roll back part of a transaction.

When a nested `transaction` block ends, bx-orm flushes the ORM session for each datasource, so the nested block's changes reach the database before the outer transaction continues.

{% hint style="info" %}
Looking for full ORM savepoint support? [Contact our Support team to consider sponsoring this feature](https://boxlang.io/plans).
{% endhint %}


# Events

React to entity inserts, updates, deletes and commits with entity and global event handlers

Hibernate ORM allows reacting to various events in the session lifecycle such as `onPreInsert`, `onPostUpdate`, `onFlush`, etc. You can enable event handling in bx-orm by setting `eventHandling` to `true` in your `this.ormSettings` struct:

```js
this.ormSettings = {
    eventHandling: true
};
```

{% hint style="warning" %}
`eventHandling: true` is required. It defaults to `false`, and with `false` no ORM event fires: not the event methods on your entities, not the global `eventHandler` (even when it is set), and not `postNew`. Earlier bx-orm versions fired events regardless of this setting, so an application that relied on events without setting `eventHandling: true` must now set it. Adobe ColdFusion and Lucee also require it.
{% endhint %}

This will enable two different event listener types for listening to Hibernate events:

* Listen to all events across all entities via the [global event handler](#global-event-handler)
* Listen to specific events on a specific entity via [entity event handler](#entity-event-handler) methods

## Global Event Handler

To use a global event handler, you must set a path to the global event handler using the `eventHandler` setting:

```js
this.ormSettings = {
    eventHandling: true,
    eventHandler : "path/to/global/EventHandler.bx"
};
```

The `EventHandler.bx` must then contain function definitions matching the ORM events you wish to listen for.

Currently, the available event names are:

* `postNew`
* `onFlush`
* `preLoad`
* `postLoad`
* `preInsert`
* `postInsert`
* `preUpdate`
* `postUpdate`
* `preDelete`
* `onDelete`
* `postDelete`
* `postCommit` (see [postCommit](#postcommit-after-the-commit))
* `onEvict`
* `onClear`
* `onDirtyCheck`
* `onAutoFlush`

Here's an example of an EventHandler configured for all events:

```js
class {

	public class function init(){
		return this;
	}

	function onFlush( entity ) {
		// Do something upon function call
	}

	function preLoad( entity ){
		// Do something upon function call
	}
	function postLoad( entity ){
		// Do something upon function call
	}

	function preInsert( entity ){
		// Do something upon function call
	}
	function postInsert( entity ){
		// Do something upon function call
	}

	function preUpdate( entity, Struct oldData  ){
		// Do something upon function call
	}
	function postUpdate( entity ){
		// Do something upon function call
	}

	function preDelete( entity ){
		// Do something upon function call
	}	
	function onDelete( entity ) {
		// Do something upon function call
	}
	function postDelete( entity ) {
		// Do something upon function call
	}
	function postCommit( entity, entityName, action ) {
		// Do something once the write is committed
	}

	function onEvict() {
		// Do something upon function call
	}
	function onClear( entity ) {
		// Do something upon function call
	}
	function onDirtyCheck( entity ) {
		// Do something upon function call
	}
	function onAutoFlush( entity ) {
		// Do something upon function call
	}
}
```

## Entity Event Handler

You can also listen to events on a specific entity at the entity level by adding methods to the entity (class) itself:

```js
@persistent
class {
	function preInsert( entity ){
		setDateCreated( now() );
	}
	function preUpdate( entity ){
		setDateModified( now() );
	}
}
```

{% hint style="info" %}
Note that only events related to a specific entity will fire upon that entity. For example, you cannot listen to `onFlush` in an entity event handler because a flush is not tied to any one entity.
{% endhint %}

Here is the full list of event types which can be listened to in entity event listeners:

* `postNew`
* `preLoad`
* `postLoad`
* `preInsert`
* `postInsert`
* `preUpdate`
* `postUpdate`
* `preDelete`
* `postDelete`
* `postCommit`

{% hint style="info" %}
`postNew` is not a Hibernate event: it fires when `entityNew()` creates an entity (and when `entityLoadOrNew()` or `entityLoadOrSave()` create one), not when an entity is loaded. Use `postLoad` for loads.
{% endhint %}

{% hint style="info" %}
`onDelete` is only available in the [global event handler](#global-event-handler), not as an entity-level method - it fires once per delete operation, before Hibernate has resolved which entity persister to use.
{% endhint %}

{% hint style="info" %}
Changes you make to the entity inside `preInsert` or `preUpdate` (either globally or at the entity level) are written back into the values Hibernate persists - these are the two events where mutating the entity actually affects what gets saved.
{% endhint %}

## Vetoing an operation

A `preInsert`, `preUpdate` or `preDelete` handler cancels the operation by returning `false`. This works in the entity's own method and in the global event handler. Both handlers are always called, and either one can veto.

```js
@persistent
class {
	@fieldtype( "id" )
	@generator( "increment" )
	property id;

	property status;

	function preDelete( entity ) {
		// published posts are never deleted
		return getStatus() != "published";
	}
}
```

Only an explicit `false` vetoes. A handler that returns nothing, or any other value, lets the operation continue, so existing handlers are not affected.

What happens after a veto:

| Event       | Result                                                                                                                                                                                                                                                                                            |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `preInsert` | No row is written. The entity stays in the session: remove it with [entityEvict( entity )](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict) or `ormClearSession()` before changing it, or the next flush tries to update a row that does not exist (`orm.stale`). |
| `preUpdate` | Nothing is written and the entity keeps its changes. It stays dirty, so the update, and your `preUpdate`, run again on every flush. Call `entityReload( entity )` to discard the change.                                                                                                          |
| `preDelete` | The row stays. The entity leaves the session.                                                                                                                                                                                                                                                     |

{% hint style="warning" %}
An entity whose id is generated by the database (`@generator( "identity" )`) cannot veto its insert: Hibernate needs the `INSERT` to get the id. Returning `false` from `preInsert` there raises an `orm.event.veto` error. Decide before calling `entitySave()`, or throw an error from `preInsert`.
{% endhint %}

## postCommit: after the commit

`postCommit` fires once a write is committed to the database, so it is the place for side effects that must only happen for data that is really saved: sending an email, clearing a cache, publishing a message. It is never fired for a write that is rolled back.

It is called on the entity's `postCommit()` method and on the global event handler's, with these arguments:

| Argument     | Value                          |
| ------------ | ------------------------------ |
| `entity`     | The entity that was written    |
| `entityName` | The entity name                |
| `action`     | `insert`, `update` or `delete` |

```js
// On the entity
@persistent
class {
	function postCommit( entity, action ) {
		if ( action == "insert" ) {
			mailService.sendWelcome( this );
		}
	}
}

// In the global event handler
function postCommit( entity, entityName, action ) {
	cacheRemove( "#entityName#-#entityGetId( entity )#" );
}
```

When it fires:

* **Inside `transaction{}`**: after BoxLang commits the transaction, when the transaction ends, in the order the writes happened. Writes that are rolled back (an error, or `transactionRollback()`) get no event.
* **Outside a transaction**: each statement commits on its own, so the event fires when the flush that wrote the row ends (`ormFlush()`, for example), or at once for a write made outside a flush, such as the insert of an entity whose id comes from the database (`@generator( "identity" )`).

Like every ORM event, `postCommit` needs `eventHandling: true`. See also [Transactions](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions#after-the-commit).


# Observability

Listen to ORM queries, flushes and failures from interceptors, and read Hibernate statistics

bx-orm announces events for SQL, flushes and failures so tools (debuggers, monitors, profilers) can listen instead of reaching into Hibernate. Register a normal BoxLang interceptor for the event names below.

There is no cost when nothing is listening. JDBC objects are only wrapped when a listener exists at the moment a connection is acquired, and payloads are built lazily.

## Events

| Event            | Fires                                                                                               | Payload                                                                  |
| ---------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `onORMQuery`     | After each JDBC statement. Selects fire when the result set is closed, once the row count is known. | See below                                                                |
| `onORMFlush`     | After each Hibernate session flush.                                                                 | `inserts`, `updates`, `deletes`, `elapsedNanos`, `datasource`, `appName` |
| `onORMException` | When a statement fails.                                                                             | `error`, `sql`, `datasource`, `appName`                                  |

### `onORMQuery` payload

| Key            | Description                                                                                                   |
| -------------- | ------------------------------------------------------------------------------------------------------------- |
| `sql`          | The SQL text sent to the driver.                                                                              |
| `kind`         | `select`, `insert`, `update`, `delete`, `ddl` or `other`.                                                     |
| `elapsedNanos` | Execution time in nanoseconds. Excludes time spent reading rows.                                              |
| `rows`         | Rows returned for selects, rows affected for DML, `-1` when unknown (for example DDL).                        |
| `datasource`   | The datasource name.                                                                                          |
| `appName`      | The unique ORM application name, as used by `ORMService.getORMApp()`.                                         |
| `hql`          | The HQL being run, when the statement came from `ormExecuteQuery()`. Otherwise `null`.                        |
| `entityName`   | The entity being loaded, when the statement came from `entityLoad()` or `entityLoadByPK()`. Otherwise `null`. |
| `error`        | The `Throwable` when the statement failed, otherwise `null`.                                                  |
| `params`       | Ordered array of bound parameter values. Only present when `announceQueryParams` is `true`.                   |

A failed statement announces `onORMQuery` with `error` set, and `onORMException`. This includes SQL the database rejects while the statement is being prepared.

Startup DDL (for example `dbcreate="dropcreate"`) is announced too, as long as the listener is registered before the application starts.

### `onORMFlush` counts

`inserts`, `updates` and `deletes` count the statements run during the flush, not entities. JDBC batching can make them differ from the number of entities changed.

### Example

```javascript
// OrmWatcher.bx
class {

    function onORMQuery( data ) {
        // 100 ms
        if ( data.elapsedNanos > 100000000 ) {
            writeLog( text="Slow ORM #data.kind#: #data.sql#", type="warning" );
        }
    }

    function onORMException( data ) {
        writeLog( text="ORM failure on #data.datasource#: #data.error.getMessage()#", type="error" );
    }

}
```

Register it with `boxRegisterInterceptor()`, naming the events it listens to:

```javascript
boxRegisterInterceptor(
    interceptor : new OrmWatcher(),
    points      : [ "onORMQuery", "onORMException" ]
);
```

## Settings

Set these in `this.ormSettings`. Both default to `false`.

| Setting               | Description                                                                                                          |
| --------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `announceQueryParams` | Include bound parameter values in `onORMQuery`. Values can be sensitive, so they are never announced unless you ask. |
| `generateStatistics`  | Collect Hibernate statistics at startup, for `ORMService.getStatistics()`. Collection has a small cost.              |

## Statistics

`ORMService.getStatistics( appName )` returns a struct of `appName` and a `datasources` struct with one entry per datasource. When statistics are not collected, each entry is just `{ enabled: false }`.

Statistics can also be switched on and off at runtime with `ORMService.setStatisticsEnabled( appName, enabled )`. Counters start from zero when switched on.

Enabled entries contain: `enabled`, `startTime`, `sessionOpenCount`, `sessionCloseCount`, `flushCount`, `connectCount`, `prepareStatementCount`, `transactionCount`, `successfulTransactionCount`, `queryExecutionCount`, `queryExecutionMaxTime`, `queryExecutionMaxTimeQueryString`, `entityLoadCount`, `entityFetchCount`, `entityInsertCount`, `entityUpdateCount`, `entityDeleteCount`, `collectionLoadCount`, `collectionFetchCount`, `secondLevelCacheHitCount`, `secondLevelCacheMissCount`, `secondLevelCachePutCount`, `queryCacheHitCount` and `queryCacheMissCount`.

## Other ORM events

| Event               | When                                                | Payload                           |
| ------------------- | --------------------------------------------------- | --------------------------------- |
| `ORMPreConfigLoad`  | Before bx-orm reads an application's `ormSettings`. | `properties`, `context`           |
| `ORMPostConfigLoad` | After bx-orm reads an application's `ormSettings`.  | `properties`, `context`           |
| `post_new`          | When `entityNew()` creates an entity.               | `entityName`, `entity`, `context` |

`properties` is the `ormSettings` struct of the application.


# Session Management

How bx-orm manages Hibernate Sessions and SessionFactories behind the scenes

bx-orm manages Hibernate state across four layers. Understanding them helps explain behavior you'll run into in practice: why entities loaded in one request aren't visible in another, why a background thread needs its own session, and what actually happens when you call `ormReload()`.

```mermaid
flowchart TD
    subgraph runtime["Lives for the BoxRuntime"]
        Service["ORMService<br/>(one singleton)"]
    end

    subgraph app["Lives for the BoxLang Application"]
        App["ORMApp<br/>(one per Application name)"]
        SF1["Hibernate SessionFactory<br/>(datasource A)"]
        SF2["Hibernate SessionFactory<br/>(datasource B)"]
        App --> SF1
        App --> SF2
    end

    subgraph req["Lives for one request or thread"]
        Ctx["ORMContext"]
        S1["Hibernate Session<br/>(datasource A)"]
        S2["Hibernate Session<br/>(datasource B)"]
        Ctx -->|opened lazily| S1
        Ctx -->|opened lazily| S2
    end

    Service -->|tracks| App
    Ctx -->|looks up| App
    S1 -.built from.-> SF1
    S2 -.built from.-> SF2
```

## ORMService

`ORMService` is a single BoxRuntime-wide service. It keeps a map of every running `ORMApp`, keyed by the BoxLang Application's name, and is responsible for:

* Starting up an `ORMApp` the first time an ORM-enabled application runs (`startupApp()`)
* Looking up the running `ORMApp` for a given context (`getORMAppByContext()`)
* Reloading an application's ORM state (`reloadApp()`, backing the `ormReload()` BIF)
* Shutting down one application (`shutdownApp()`) or all of them when the runtime itself shuts down

## ORMApp

An `ORMApp` represents one BoxLang Application's ORM state, and is built once and reused for the life of that application (until reload or shutdown). On startup it:

1. Discovers entities via `MappingGenerator`, grouped by the datasource each entity belongs to
2. Builds one Hibernate `SessionFactory` per datasource, via `SessionFactoryBuilder`
3. Tracks which datasource is the default (from `this.ormSettings.datasource`)

Everything expensive - entity discovery, XML mapping generation, and Hibernate bootstrapping - happens here, once per application, not per request. This is why `ormSettings.entityPaths`, `generateMappings=false` and the boot cache matter so much for startup performance. The boot cache (`ormManifest : "trust"`) skips entity discovery, parsing and code generation, and boots from the `.bxorm/` folder. See [Boot Cache](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/performance#boot-cache) and [Performance](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/performance).

## ORMContext and Hibernate Sessions

Where `ORMApp` is application-scoped, `ORMContext` is scoped to a single request or thread context. It holds the actual Hibernate `Session` objects your code reads and writes through, one per datasource, opened lazily the first time that datasource is touched.

{% hint style="warning" %}
Because a Hibernate `Session` is tied to a single request or thread context, spawning parallel threads (e.g. `array.each(..., true)`) gives each thread its **own** `ORMContext` and its own Hibernate sessions. An entity created with `entityNew()` inside a parallel thread is attached to that thread's session, not the request's - loading, saving, or querying it from the parent request won't see it until it's been persisted and reloaded through the request's own session.
{% endhint %}

When a session is opened, its flush mode depends on `autoManageSession`:

* `autoManageSession = false` (the default): the session is opened in `FlushMode.MANUAL`. Nothing is written to the database until you explicitly call `ormFlush()` or commit a `transaction` block. See [Transactions](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions).
* `autoManageSession = true`: Hibernate manages flushing automatically (e.g. before query execution), which is generally discouraged - see the `autoManageSession` setting in [Configuration](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration).

At the end of the request or thread (or explicitly via `ormCloseSession()`/`ormCloseAllSessions()`), the `ORMContext` is torn down: any active transaction on each open session is committed, then the session is closed. If `flushAtRequestEnd` and `autoManageSession` are both enabled, sessions are flushed first.

## Reloading the ORM (`ormReload()`)

Calling `ormReload()` rebuilds the current application's `ORMApp` - re-discovering entities and re-building every `SessionFactory` - without restarting the BoxLang application itself. The rebuild is ordered carefully to stay safe under concurrent requests:

1. Any open Hibernate sessions for the reloading request are closed first, so they can't hold a reference to a `SessionFactory` that's about to be replaced.
2. The new `ORMApp` (with fresh session factories) is fully built *before* it replaces the old one in the running application map.
3. The old `ORMApp` is swapped out and only then shut down, closing its old `SessionFactory` instances.

This ordering means other requests keep using a valid `ORMApp` throughout the reload, with only a small window where both the old and new session factories briefly coexist.

## Relevant Built-in Functions

| Function                                                                                                                                                                                                                | Purpose                                                                       |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)                                                                                                                      | Get the raw Hibernate `Session` for the current context and datasource        |
| [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)                                                                                                        | Get the Hibernate `SessionFactory` for a datasource                           |
| [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush) / [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)                               | Flush one or all open sessions                                                |
| [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)                                                                                                                  | Detach all entities from the session without flushing                         |
| [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)                                                                                                                          | Detach one entity (or an array of entities) from the session without flushing |
| [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)                                                                                                                          | Run a closure with every entity it loads read-only                            |
| [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession) / [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions) | Close one or all open sessions for the current context                        |
| [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)                                                                                                                              | Rebuild the ORM application's session factories                               |
| [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)                                                                                                              | Whether a flush would write something                                         |
| [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)                                                                                                  | Which entities and collections the session holds                              |

## Inspecting entities and the session

These functions answer "what is this entity, and what changed" without touching the Hibernate API. They take an entity instance (or, where it makes sense, an entity name) and never load a lazy reference just to answer.

```js
user = entityLoadByPK( "User", 1 );

entityGetName( user );             // "User"
entityGetDatasource( user );       // "app"
entityGetId( user );               // 1 (a struct for composite ids)
entityGetMetadata( "User" ).tableName; // "users"

user.setEmail( "new@example.com" );
entityIsDirty( user );             // true
entityGetDirtyProperties( user );  // [ "email" ]
ormIsSessionDirty();               // true
ormGetSessionStatistics().entityKeys; // [ "User#1" ]
```

An entity in the session is compared with the values it was loaded with, with no SQL. An entity outside the session is compared with a fresh read of its row. An entity that was never saved is not dirty.

| Function                                                                                                                 | Purpose                                                |
| ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ |
| [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)                       | The entity name of an instance, lazy reference or name |
| [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)           | The entity's datasource                                |
| [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)                           | The entity's id                                        |
| [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)               | Table, ids, properties and associations                |
| [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)                       | Whether the entity has unsaved changes                 |
| [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties) | Which properties changed                               |


# Caching

Cache entities, collections and queries in BoxLang's BoxCache with Hibernate's second-level cache.

Every Hibernate session already caches the entities it loads (the first-level cache), but only until the session ends. The **second-level cache** keeps entities, collections and query results across sessions and requests, so repeated reads skip the database.

In bx-orm 2 the second-level cache is **BoxLang's own BoxCache**. Each cache region Hibernate uses is a normal BoxLang cache. There is no EHCache or other cache library to install, and you can tune, inspect and replace those caches like any other BoxLang cache.

## Quick Start

1. Turn the second-level cache on (it is off by default):

   ```js
   this.ormSettings = {
       secondaryCacheEnabled : true
   };
   ```
2. Mark the entities to cache with `cacheUse`, and give each one a region name with `cacheName`:

   ```js
   @persistent
   @cacheuse( "read-write" )
   @cachename( "users" )
   class {
       @fieldtype( "id" )
       @generator( "native" )
       property id;

       property name;
   }
   ```

That's it. `entityLoadByPK( "User", 1 )` now reads from the `users` cache after the first load, in any request.

## How It Works

Hibernate splits the second-level cache into **regions**: one per cached entity, one per cached collection, and regions for query results. bx-orm stores each region in a BoxLang cache with the same name, found or created the first time the region is used:

1. **Your own cache:** if a BoxLang cache with the region's name already exists, for example one you defined in `boxlang.json`, bx-orm uses it as is, with its own provider and settings.
2. **Created for you:** otherwise bx-orm creates the cache with the `cacheProvider` setting (BoxCache by default) and the properties `cacheConfig` gives that region.

```
entityLoadByPK( "User", 1 )
  -> Hibernate region "users" (from cacheName="users")
     -> BoxLang cache "users": your own cache if it exists, else a new BoxCache tuned by cacheConfig
```

## Cache Strategies

`cacheUse` picks how Hibernate keeps the cache consistent with the database:

| `cacheUse`             | Use it for                                                                                 |
| ---------------------- | ------------------------------------------------------------------------------------------ |
| `read-only`            | Data that never changes after it is inserted (lookups, countries). Fastest. Updates throw. |
| `nonstrict-read-write` | Data that changes rarely, where a short window of stale reads is fine.                     |
| `read-write`           | Data that changes and must not be read stale. Uses soft locks around updates.              |
| `transactional`        | Not supported: the regions bx-orm builds reject it at startup. Use `read-write`.           |

`cacheInclude` decides whether lazy properties are cached with the entity: `all` (the default) or `non-lazy`.

## What You Can Cache

### Entities

Add `cacheUse`, and preferably `cacheName`, to the entity class:

```js
@persistent
@table( "countries" )
@cacheuse( "read-only" )
@cachename( "countries" )
class {
    @fieldtype( "id" )
    @generator( "assigned" )
    property code;

    property name;
}
```

Without `cacheName`, the region is named after the entity's internal Hibernate class name, which is long and application-specific. Set `cacheName` so the region is easy to tune and find.

### Collections

Put `cacheUse` (and optionally `cacheName`) on a `one-to-many`, `many-to-many` or `collection` property to cache the ids of its elements:

```js
@persistent
@cacheuse( "read-write" )
@cachename( "users" )
class {
    @fieldtype( "id" )
    @generator( "native" )
    property id;

    @fieldtype( "many-to-many" )
    @cfc( "Role" )
    @linktable( "user_roles" )
    @cacheuse( "read-write" )
    @cachename( "userRoles" )
    property roles;
}
```

A cached collection stores element ids, so cache the element entity too (here `Role`), or each element is still loaded from the database.

### Queries

Cache the results of a query with the `cacheable` and `cacheName` options:

```js
// default query region
active = ormExecuteQuery( "from User where active = true", [], false, { cacheable : true } );

// a named query region; a cacheName alone also turns caching on
active = ormExecuteQuery( "from User where active = true", [], false, { cacheName : "activeUsers" } );
users  = entityLoad( "User", { active : true }, "name", { cacheName : "activeUsers" } );

// criteria
users = entityCriteria( "User" ).isTrue( "active" ).cacheable( true ).list();
```

The query cache stores the ids of the results, so it works best together with entity caching. Hibernate drops a cached query's results when any table it reads is changed through the ORM.

## Tuning the Caches with `cacheConfig`

`cacheConfig` sets the BoxCache properties of the caches bx-orm creates. Keys at the top level apply to every region; the `regions` struct overrides them for specific regions:

```js
this.ormSettings = {
    secondaryCacheEnabled : true,
    cacheConfig           : {
        // every region
        maxObjects     : 1000,
        defaultTimeout : 3600,
        // per region, by name
        regions        : {
            "countries" : { maxObjects : 300, defaultTimeout : 0 },
            "users"     : { maxObjects : 10000, defaultLastAccessTimeout : 600 }
        }
    }
};
```

A region's final properties are BoxCache's defaults, then the top-level keys, then its `regions` entry. Region names are matched without regard to case. A configured name also matches a region whose name ends with `.` plus that name, so `"User"` matches the default region of the `User` entity even without a `cacheName`; when several match, the longest wins.

The BoxCache properties you will use most (times are in seconds):

| Property                   | Default           | Meaning                                                                  |
| -------------------------- | ----------------- | ------------------------------------------------------------------------ |
| `maxObjects`               | `1000`            | The most entries the cache holds before it evicts.                       |
| `defaultTimeout`           | `3600`            | How long an entry lives. `0` means it never expires.                     |
| `defaultLastAccessTimeout` | `1800`            | How long an entry lives without being read. `0` means no idle timeout.   |
| `evictionPolicy`           | `LRU`             | Which entries go first when the cache is full: `LRU`, `LFU`, `FIFO`, ... |
| `objectStore`              | `ConcurrentStore` | Where entries are kept.                                                  |
| `reapFrequency`            | `120`             | How often expired entries are removed.                                   |

See the BoxLang caching documentation for every BoxCache property.

### From a File

`cacheConfig` can also be the path of a file. A path that does not exist as written is expanded like `expandPath()`.

**A JSON file** has the same shape as the struct:

```json
{
    "maxObjects" : 1000,
    "regions" : {
        "countries" : { "maxObjects" : 300, "defaultTimeout" : 0 }
    }
}
```

**An `ehcache.xml`** from an Adobe ColdFusion or Lucee application keeps working: bx-orm reads it and maps its settings to BoxCache properties. EHCache itself is not used.

| EHCache 2 (`<defaultCache>`, `<cache name>`)        | EHCache 3 (`<cache alias>`, `<cache-template>`) | BoxCache property          |
| --------------------------------------------------- | ----------------------------------------------- | -------------------------- |
| `maxEntriesLocalHeap` or `maxElementsInMemory`      | `<heap unit="entries">`                         | `maxObjects`               |
| `timeToLiveSeconds`                                 | `<expiry><ttl unit="...">`                      | `defaultTimeout`           |
| `timeToIdleSeconds`                                 | `<expiry><tti unit="...">`                      | `defaultLastAccessTimeout` |
| `eternal="true"`                                    | `<expiry><none/>`                               | both timeouts `0`          |
| `memoryStoreEvictionPolicy` (`CLOCK` becomes `LRU`) |                                                 | `evictionPolicy`           |

In EHCache 2 files `<defaultCache>` becomes the top-level properties and each `<cache name="...">` a region. In EHCache 3 files each `<cache alias="...">` is a region, with `uses-template` values applied first. Disk stores, listeners and clustering settings are ignored.

```js
this.ormSettings = {
    secondaryCacheEnabled : true,
    cacheConfig           : "config/ehcache.xml"
};
```

## Using Your Own BoxLang Caches

Because every region is a BoxLang cache, you can put a region on any cache you define, with any provider. Name the cache after the region (the entity's `cacheName`) in `boxlang.json`:

```json
{
    "caches" : {
        "users" : {
            "provider"   : "BoxCacheProvider",
            "properties" : { "maxObjects" : 20000, "defaultTimeout" : 7200 }
        }
    }
}
```

bx-orm finds the `users` cache and uses it for the `users` region, ignoring `cacheConfig` for it. This is also how you share a region with other code, or put it on a distributed cache.

To put **every** region bx-orm creates on another BoxLang provider, for example one added by a Redis or Couchbase module, set `cacheProvider` to that provider's registered name. `cacheConfig` then holds that provider's properties:

```js
this.ormSettings = {
    secondaryCacheEnabled : true,
    cacheProvider         : "MyRedisProvider",
    cacheConfig           : { /* properties of that provider */ }
};
```

`BoxCacheProvider` is the default. `ConcurrentHashMap`, `HashTable` and `ehcache` are accepted as aliases for it, for compatibility with older applications. An unknown provider name raises an error the first time a region is used.

{% hint style="info" %}
Regions are BoxLang caches, and BoxLang caches are shared by the whole runtime. If several applications in one server cache the same entity names, give their `cacheName`s an application prefix so they do not share regions.
{% endhint %}

## Evicting

Hibernate keeps the cache in step with changes made through the ORM. When data changes outside the ORM (another application, `queryExecute()`), evict what is stale:

| Function                                                                                                                                 | Evicts                                  |
| ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
| [`ormEvictEntity( "User" [, id] )`](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)                  | One entity, or every cached `User`.     |
| [`ormEvictCollection( "User", "roles" [, id] )`](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection) | One owner's collection, or all of them. |
| [`ormEvictQueries( [cacheName] )`](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)                  | A query region, or the default one.     |

You can also clear a region's BoxLang cache directly, for example `cache( "users" ).clearAll()`.


# Performance

Speed up ORM startup with the boot cache, and tune queries and fetching at runtime

bx-orm is designed to be as fast as possible, but there are some factors that can affect performance. Let's look at a few key areas where you can optimize performance in your application.

## ORM Startup

You want the short answer?

* Turn on the [boot cache](#boot-cache): `ormManifest : "auto"` in development and `ormManifest : "trust"` in production. A trusted boot skips entity discovery, parsing, mapping generation and facade code generation.
* Or commit your XML mapping files to disk and set `this.ormSettings.generateMappings = false` (with `savemapping = true`) to eliminate the XML mapping generation time on startup.
* Fine-tune `this.ormSettings.entityPaths` to minimize the number of candidate files that need to be parsed for entity discovery.

See also [Startup Metrics Logs](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration/logging#startup-metrics) for consolidated examples of the debug log output for ORM startup performance metrics.

### Entity Discovery

The initial step in ORM startup is to discover ORM entities and parse the entity metadata into internal structures. The time will be proportional to the number of entities found and the number of candidate files that need to be parsed to find those entities. By default, bx-orm will scan all `.bx` and `.cfc` files in the specified entity paths, which can lead to a large number of candidate files and increased startup time.

This can be minimized by fine-tuning `this.ormSettings.entityPaths` [in your orm configuration](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration).

Enable debug logging to see the time taken for entity discovery and metadata parsing in the logs:

```bash
ORM startup metric - entity file discovery: 42ms (187 candidate files found)
ORM startup metric - entity metadata parsing: 310ms (23 persistent entities found, sequential mode)
```

After the mapping step (below), a summary line gives the total time spent before Hibernate starts:

```bash
ORM startup metric - total entity discovery, parsing and meta collection: 455ms
```

### XML Mapping Generation

Once persistent entities are located and metadata is collected, bx-orm generates XML mapping files for each entity. This process can be time-consuming, especially if you have a large number of entities.

This startup penalty can be mostly eliminated by committing your `.orm.xml` mappings to disk (write them with `savemapping : true`) and setting `this.ormSettings.generateMappings = false`.

Note that for any ORM entity changes, you will need to regenerate the XML mapping files by setting `this.ormSettings.generateMappings = true` and running `ormReload()` or restarting your application. This will regenerate the XML mappings to pick up any changes.

You can also pre-generate `.orm.xml` files from the command line, without booting a full application, using the [GenerateMappings CLI tool](https://bxorm.ortusbooks.com/bxorm-2.x/reference/cli-tools).

Enable debug mode to see the time taken for XML mapping generation in the logs:

```bash
ORM startup metric - XML mapping generation: 88ms (23 mapping files generated)
```

### Boot Cache

The boot cache stores everything bx-orm works out at startup in a `.bxorm/` folder: the resolved entity metadata, the generated Hibernate mappings (`manifest-{app}.json`) and the generated entity facade classes (`facades-{app}.jar`). The `ormManifest` setting picks the mode:

| Mode            | What happens at startup                                                                                                                      | Use it for                     |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
| `off` (default) | Discover, parse and map every entity on every boot.                                                                                          | Anything, the classic behavior |
| `auto`          | Boot normally, then write the `.bxorm/` cache. bx-orm also watches the entity paths: edit an entity and the ORM reloads on the next request. | Development                    |
| `trust`         | Boot straight from the `.bxorm/` cache: no discovery, parsing, mapping generation or facade code generation.                                 | Production                     |

```js
this.ormSettings = {
    entityPaths : [ "models" ],
    // "auto" on your machine and in CI, "trust" in production
    ormManifest : getSystemSetting( "ORM_MANIFEST", "auto" )
};
```

A `trust` boot fails closed. It refuses to start, naming what changed, when:

* The application's cache files are missing, or the checksum does not match (the manifest was edited or corrupted).
* The manifest belongs to another application (for example one copied or renamed by hand).
* A key ORM setting changed since the cache was written: dialect, datasource, naming strategy, application name, `dbcreate`, `quoteIdentifiers` or `entityPaths`.
* The bx-orm version changed.
* An entity source file changed since the cache was written. Sources are recorded as BoxLang paths (`/models/Task.cfc`), so this check works wherever the application is deployed, not only where the cache was built.

A `trust` boot gives your application the same entities as an `off` or `auto` boot. Discovery adds normalized values to each entity class's metadata (`entityName`, `table`, default `fieldtype` and `ormType`, and so on), and code reads them back, such as ColdBox's `populate()` when it resolves a relationship. So a `trust` boot loads each entity class and writes the cached metadata onto it: `getClassMetadata()` and `getMetadata()` return the same values in every mode. In a fresh container this compiles the entity classes at startup, which otherwise happens on each entity's first use: about 2 ms per entity (0.35 seconds for 150 entities, loaded in parallel with `enableThreadedMapping`).

`trust` mode does no discovery, so a newly added entity file is not picked up. Refresh the cache after changing entities, then deploy the `.bxorm/` folder with your application.

#### Building the Cache at Build Time

You do not need to boot the application to build the cache. [`module:orm generate`](https://bxorm.ortusbooks.com/bxorm-2.x/reference/cli-tools#generate) writes it from the command line, with no server, no database and no application start, so a Docker build or a CI step can produce a `trust`-ready image:

```bash
boxlang --bx-config runtime/boxlang.json module:orm generate
```

It reads your `Application.bx` settings the way the server does (pass the server's `boxlang.json` so its mappings and datasources are loaded) and writes the manifest and the facade jar. Then run the application with `ormManifest : "trust"`.

By default the `.bxorm/` folder lives in the application root. `ormManifestLocation` moves it: a relative path resolves against the application root, an absolute path is used as is, and the folder is always named `.bxorm`.

#### Several Applications in One Folder

Sub-applications deployed under the same root can share one `.bxorm/` folder. Each application's files carry its name, so they never overwrite each other:

```
.bxorm/
  manifest-shop.json
  manifest-shop.sha256
  facades-shop.jar
  manifest-admin.json
  manifest-admin.sha256
  facades-admin.jar
```

The `{app}` part is the application's `this.name` run through BoxLang's [`slugify()`](https://boxlang.ortusbooks.com/boxlang-language/reference/built-in-functions/string/slugify): `this.name = "My Shop"` writes `manifest-my-shop.json`. Deploy the whole folder; each application boots from its own files.

The gain grows with the number of entities: the work `trust` removes scales with your entity count. Hibernate's own `SessionFactory` build (below) still runs in every mode.

Use the [`bxorm` CLI](https://bxorm.ortusbooks.com/bxorm-2.x/reference/cli-tools#bxorm-boot-cache-cli) to build, inspect, validate or clear the cache.

### SessionFactory Build

Building the Hibernate `SessionFactory` is the largest remaining cost of a boot, in every mode. It grows with the number of entities. The boot cache cannot skip it.

Enable debug mode to see the time taken for SessionFactory building in the logs:

```bash
ORM startup metric - Hibernate SessionFactory build time [myDatasource]: 1243ms
```

### Measured Boot Times

These are median boot times in seconds, measured on synthetic models (entities with associations) against a local MariaDB database. Your numbers will differ with your hardware, database and model.

| Entities | `off` | `auto` | `trust` | bx-orm 1.7.1 |
| -------- | ----- | ------ | ------- | ------------ |
| 25       | 5.23  | 5.10   | 3.86    | 3.13         |
| 250      | 13.48 | 14.14  | 7.12    | 8.46         |

The `trust` times were measured before a `trust` boot loaded the entity classes (see [Boot Cache](#boot-cache)). On a cold class cache that adds about 2 ms per entity.

* On a large model, `trust` cuts boot time by about a third to a half. At 250 entities a `trust` boot is faster than a bx-orm 1.7.1 boot.
* Small applications (10 to 25 entities) boot about 1.5 to 2 seconds slower than 1.7.1, in every mode. This is a fixed cost per JVM: Hibernate 7 and its libraries load more Java classes. The boot cache cannot remove it.

### Automatic Speedups

bx-orm 2.0 also does less work at startup, without any setting:

* Generated ids (`native`, `identity`, `increment`, `uuid`, `sequence` and the like) tell Hibernate that a `null` id means "not saved yet". Hibernate no longer creates a throwaway instance of every entity at startup to find out. Use the `unsavedValue` annotation for other cases, such as an assigned numeric id.
* The per-entity mappings are joined in memory and handed to Hibernate without a temporary file.
* With `enableThreadedMapping` on (the default) and more than 20 entities, the static entity methods are added on parallel threads.

## Runtime Performance

Most ORM performance problems happen after startup. Measure the SQL generated by Hibernate and the time spent in the database before changing fetch strategies or caching. A faster application usually comes from loading fewer rows, issuing fewer queries, and keeping transactions short.

### Use Lazy Loading Deliberately

Keep large to-many relationships lazy so loading a parent entity does not also load its entire object graph. This is usually the right default for `one-to-many` and `many-to-many` relationships. See [Modeling Relationships](https://bxorm.ortusbooks.com/bxorm-2.x/modeling/relationships#lazy-loading) for the available `lazy` values.

Lazy loading is not a request to load data for free. Accessing a lazy relationship triggers another SQL query while the entity is attached to an ORM session. Access lazy properties inside the transaction or session boundary, and avoid returning entities to code that will access unloaded relationships after the session has closed.

Do not make every relationship eager to avoid lazy-loading errors. Eager to-many relationships can load a large amount of data and can multiply rows when several collections are joined. Choose the fetch plan for each use case instead.

### Prevent N+1 Queries

An N+1 query occurs when one query loads a list of parent entities and then one additional query runs for each parent's relationship. It is easy to create accidentally:

```js
var users = entityLoad( "User", {}, "name asc", { maxResults: 50 } );

for ( var user in users ) {
	// Accessing posts here can issue one query per user.
	println( user.getPosts().size() );
}
```

When a screen or operation needs a relationship for every result, fetch it intentionally with an HQL join:

```js
var users = ORMExecuteQuery(
	hql    : "SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.posts WHERE u.active = true",
	params : {},
	options: { maxResults: 50 }
);
```

Use fetch joins for the specific use case that needs the related data. Do not fetch-join multiple to-many collections in one query, and be cautious with pagination over a collection fetch join because the database paginates joined rows rather than distinct parent entities. For larger result sets, prefer batch fetching or separate queries.

### Batch Fetching

Batch fetching lets Hibernate initialize several lazy associations with fewer `SELECT` statements. Configure a moderate default batch size through `hibernateProperties`, then tune it using query logs and database metrics:

```js
this.ormSettings.hibernateProperties = {
	"hibernate.default_batch_fetch_size": 25
};
```

Batch fetching is useful when a request loads many entities and then accesses the same lazy relationship on several of them. It does not replace a good fetch plan: a fetch join is often better when the relationship is always required, while batching is useful when access is conditional.

### Batch Writes

For large insert or update jobs, use one transaction and enable JDBC batching. Hibernate can group compatible statements into fewer database round trips:

```js
this.ormSettings.hibernateProperties = {
	"hibernate.jdbc.batch_size": 25,
	"hibernate.order_inserts": true,
	"hibernate.order_updates": true
};
```

Use a batch size appropriate for the database and driver, and commit in bounded chunks for very large jobs. Keep an eye on memory because the session retains managed entities until they are flushed and cleared. Bulk HQL `UPDATE` and `DELETE` statements can be more efficient than loading and changing thousands of entities, but they bypass entity lifecycle events and require careful cache handling.

### Select Only What You Need

For reports, exports, and list screens, avoid loading a complete entity graph when a few columns are sufficient. Use an HQL projection or a purpose-built query, apply `maxResults` and `offset` for pagination, and return read-only results when the data will not be changed:

```js
var rows = ORMExecuteQuery(
	hql    : "SELECT u.id, u.name, u.email FROM User u WHERE u.active = true ORDER BY u.name",
	params : {},
	options: {
		maxResults: 100,
		offset    : 0,
		readOnly  : true
	}
);
```

For deep pagination, large offsets can become expensive because the database still has to find and discard preceding rows. Prefer keyset pagination, such as `WHERE u.id > :lastId ORDER BY u.id`, when the workflow supports it.

### Keep Transactions and Sessions Focused

Open the transaction as late as practical, perform the required work, and commit promptly. Do not hold a transaction open while rendering a response, calling a remote service, or waiting for user input. Long sessions also increase dirty-checking work and memory usage.

For read-heavy code, use `readOnly: true` on queries where supported so Hibernate does not need to track changes for those results. Do not use read-only mode for entities that the operation intends to modify.

### Index the Queries You Actually Run

Hibernate cannot compensate for missing database indexes. Add indexes for columns used frequently in `WHERE`, `JOIN`, and `ORDER BY` clauses, especially foreign keys used by relationships. Validate index choices with the database's execution plan; an index that helps one query can hurt write performance or be ignored when selectivity is poor.

### Inspect Before Optimizing

Enable SQL logging temporarily and inspect:

* the number of SQL statements for one request;
* repeated queries that differ only by an identifier, which often indicates N+1 loading;
* large result sets caused by eager relationships or fetch joins;
* slow statements in the database execution plan;
* flushes or unexpected updates before a query.

See [Querying](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/querying), [Session Management](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/session-management), and [Caching](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/caching) for bx-orm-specific behavior. For the underlying fetch and batching rules, see Hibernate's [Fetching](https://docs.hibernate.org/orm/7.4/userguide/html_single/Hibernate_User_Guide.html#fetching), [Batching](https://docs.hibernate.org/orm/7.4/userguide/html_single/Hibernate_User_Guide.html#batch), and [Querying](https://docs.hibernate.org/orm/7.4/userguide/html_single/Hibernate_User_Guide.html#hql) chapters.


# Errors and Diagnostics

What bx-orm errors look like, how to catch them, what each one means, and how to inspect the ORM with ormDiagnostics().

Every error bx-orm raises is written for BoxLang developers:

* **`message`** says what went wrong, using your entity and property names.
* **`detail`** says how to fix it.
* **`extendedInfo`** is a struct with the context: the entity, property, HQL, parameters, generated SQL, constraint name and the original Hibernate message.
* Misspelled entity, property, field type and ORM type names get a suggestion: `Did you mean [name]?`

```
[orm.property.unknown] Manufacturer has no property [nmae]. Did you mean [name]?
                       HQL: from Manufacturer where nmae = 'x'
detail: Properties: id, name, address, vehicles
```

## Catching ORM errors

Every error has a `type` that starts with `orm`. BoxLang matches `catch` types on a dotted prefix, so you can catch all ORM errors, one family, or one exact type:

```js
try {
    entitySave( user );
    ormFlush();
} catch ( "orm.constraint.unique" e ) {
    // the email is already taken
    flash.put( "error", "That email address is already registered." );
} catch ( "orm.constraint" e ) {
    // any other constraint (not null, foreign key, check)
    log.error( e.message, e.extendedInfo );
} catch ( "orm" e ) {
    // any other ORM error
    rethrow;
}
```

The context is in `e.extendedInfo`:

```js
catch ( "orm.query" e ) {
    writeDump( e.extendedInfo.hql );      // the HQL that failed
    writeDump( e.extendedInfo.params );   // the parameters you passed
}
```

## Error catalog

| Type                        | When it happens                                                                                                                                                                                                                                                                                                                                                                  | How to fix it                                                                                                                                                             |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `orm.notEnabled`            | An ORM function runs in an application without `this.ormEnabled = true`.                                                                                                                                                                                                                                                                                                         | Enable the ORM in `Application.bx`.                                                                                                                                       |
| `orm.notReady`              | The ORM failed to start (the message repeats the startup error) or has not started.                                                                                                                                                                                                                                                                                              | Fix the startup error, then call `ormReload()` or restart the app.                                                                                                        |
| `orm.config`                | Invalid ORM settings or entities found at startup: missing entity folder, unknown `fieldtype` or `ormtype`, relationship to a missing `cfc`, unknown datasource, two entities with the same name, an unknown `softDelete` or `autoTimestamp` value, `softDelete` on a subclass entity, a `defaultSort` with an unknown property or direction, an invalid `sqlFunctions` setting. | Follow the message; it names the entity, property or setting.                                                                                                             |
| `orm.boot`                  | Hibernate refused the generated mapping.                                                                                                                                                                                                                                                                                                                                         | The message names the entity; check its mapping annotations.                                                                                                              |
| `orm.entity.notFound`       | An entity name that does not exist, in a BIF or in HQL.                                                                                                                                                                                                                                                                                                                          | Use the suggested name; `detail` lists the known entities.                                                                                                                |
| `orm.property.unknown`      | A property that does not exist, in HQL, an `entityLoad()` filter or its sort order, or an `entityToStruct()` / `entityLoadAsStruct()` include.                                                                                                                                                                                                                                   | Use the suggested name; `detail` lists the entity's properties.                                                                                                           |
| `orm.property.ambiguous`    | A criteria path on a base entity names a property that several subclass entities declare (e.g. `costRate` on both `Employee` and `Contractor`) with different types, or continues through it.                                                                                                                                                                                    | Query the subclass entity (`entityCriteria( "Employee" )`), or declare the property once on the base entity.                                                              |
| `orm.property.type`         | A property holds a value that cannot be stored in its column (e.g. `"abc"` in an integer), or an association was set to something that is not an entity.                                                                                                                                                                                                                         | Set values that fit each property's `ormtype`; set associations to entity instances.                                                                                      |
| `orm.argument`              | A BIF received the wrong kind of value, e.g. a struct instead of an entity, or an id of the wrong type. Also a lock taken outside `transaction{}`, an unknown lock mode, or lock mode `force` on an entity without a version property.                                                                                                                                           | Pass what the message asks for.                                                                                                                                           |
| `orm.query.syntax`          | HQL that cannot be parsed. The message gives the line, column and token; `detail` lists what was expected.                                                                                                                                                                                                                                                                       | Fix the HQL at that position.                                                                                                                                             |
| `orm.query.semantic`        | HQL that parses but is not valid (bad function or path).                                                                                                                                                                                                                                                                                                                         | Check the HQL against your entities.                                                                                                                                      |
| `orm.query.parameter`       | A named parameter without a value, too few positional values, named vs positional mixed up, a value of the wrong type, or an empty string for a non-text value.                                                                                                                                                                                                                  | Pass one value per parameter, of the right type. Pass `null` (not `""`) for "no value".                                                                                   |
| `orm.query.nonUnique`       | A `unique` query or `entityLoad()` matched more than one row.                                                                                                                                                                                                                                                                                                                    | Narrow the query, or pass `{ uniqueFirst : true }` to take the first row.                                                                                                 |
| `orm.notFound`              | `getOrFail()` or `firstOrFail()` of [entityCriteria()](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria), `entityLoadOrFail()` or `entityLoadByPKOrFail()` matched no row.                                                                                                                                                                                  | Use `get()`, `first()`, `entityLoad()` or `entityLoadByPK()` to receive null instead, or check the id or conditions.                                                      |
| `orm.lazy.noSession`        | A lazy association was read after the session that loaded it was closed or cleared (`ormClearSession()`, `ormCloseSession()`, a finished request).                                                                                                                                                                                                                               | Reload the entity in the current session (`entityLoadByPK()`, `entityReload()`), or map the association with `@lazy( false )`.                                            |
| `orm.transient`             | A saved entity points to an entity that was never saved, or `entityLock()` received an entity that is not in the session.                                                                                                                                                                                                                                                        | Save the other entity first, or add `@cascade( "save-update" )` (or `"all"`) to the association. For `entityLock()`, load the entity first.                               |
| `orm.id.missing`            | An entity with an assigned id (`@generator( "assigned" )`) was saved without one.                                                                                                                                                                                                                                                                                                | Set the id before `entitySave()`, or give the id a generator.                                                                                                             |
| `orm.session.duplicate`     | Two different objects for the same row are in one session.                                                                                                                                                                                                                                                                                                                       | Use `entityMerge()`, or keep working with the instance you loaded.                                                                                                        |
| `orm.stale`                 | Optimistic locking: the row changed or was deleted after you loaded it.                                                                                                                                                                                                                                                                                                          | Reload the entity and apply your change again.                                                                                                                            |
| `orm.event.veto`            | A `preInsert` handler returned `false` for an entity whose id comes from the database (`@generator( "identity" )`); that insert cannot be skipped.                                                                                                                                                                                                                               | Decide before `entitySave()`, or throw an error from `preInsert`. See [Events](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/events#vetoing-an-operation). |
| `orm.constraint.unique`     | A unique constraint rejected the change.                                                                                                                                                                                                                                                                                                                                         | Another row already has this value.                                                                                                                                       |
| `orm.constraint.notNull`    | A required property (`@notNull`) or column has no value.                                                                                                                                                                                                                                                                                                                         | Set it before saving.                                                                                                                                                     |
| `orm.constraint.foreignKey` | A foreign key rejected the change: it points to a missing row, or deletes a row still referenced.                                                                                                                                                                                                                                                                                | Save or keep the referenced row, or add a cascade.                                                                                                                        |
| `orm.constraint.check`      | A check constraint rejected the change.                                                                                                                                                                                                                                                                                                                                          | See the database message in `detail`.                                                                                                                                     |
| `orm.sql`                   | The database rejected the SQL for another reason.                                                                                                                                                                                                                                                                                                                                | `extendedInfo.sql` has the generated SQL.                                                                                                                                 |
| `orm`                       | Anything else ORM-related.                                                                                                                                                                                                                                                                                                                                                       | The message has Hibernate's explanation, with your entity names.                                                                                                          |

Errors that are not caused by the ORM, such as an exception thrown by your own event handler, are passed through unchanged.

## Unique results

`unique=true` means exactly one result. If more than one row matches, bx-orm raises `orm.query.nonUnique` instead of silently dropping the others:

```js
// Error if several users share the email
user = ormExecuteQuery( "from User where email = :email", { email : rc.email }, true );

// Take the first row on purpose
latest = ormExecuteQuery( "from Post order by publishedDate desc", {}, true, { uniqueFirst : true } );
post   = entityLoad( "Post", { status : "draft" }, true, { uniqueFirst : true } );
```

## Inspecting the ORM with `ormDiagnostics()`

`ormDiagnostics()` returns a snapshot of the ORM for the current application. It never throws, so it is the first thing to call when something looks wrong.

```js
writeDump( ormDiagnostics() );
```

| Key                                   | What it holds                                                                                                                     |
| ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `status`                              | `running`, `failed` (startup failed), `notStarted` or `notEnabled`                                                                |
| `applicationName`, `hibernateVersion` | The application and the Hibernate version                                                                                         |
| `startupError`                        | `{ at, type, message, detail }` of the last failed startup or `ormReload()`                                                       |
| `defaultDatasource`, `datasources`    | Entity names per datasource                                                                                                       |
| `entityCount`, `warnings`             | How many entities, and warnings such as unknown `ormtype` values                                                                  |
| `settings`                            | The settings that most often explain surprises: `dbcreate`, `dialect`, `entityPaths`, `flushAtRequestEnd`, `autoManageSession`, … |
| `sessions`                            | This request's open sessions per datasource: `open`, `entityCount`, `collectionCount`, `dirty` (unsaved changes)                  |

When `ormReload()` fails, the application keeps running on the ORM it had, and `ormDiagnostics().startupError` shows why the reload failed.

## Startup checks

Before Hibernate starts, bx-orm checks your entities and reports every problem it finds in one error:

* Two entities with the same name on one datasource (both classes are named).
* An entity folder in `entityPaths` that does not exist.
* An unknown `fieldtype`, with the valid list and a suggestion.
* A relationship `cfc` that does not exist.
* An `ormtype` bx-orm does not recognize is logged as a warning, and named as the likely cause (with a suggestion) if Hibernate then fails to start.


# Built-in Functions

Every bx-orm built-in function, grouped by what you want to do

bx-orm ships 47 built-in functions (BIFs) for working with entities, queries and the ORM session. They are grouped below by task; the navigation lists them alphabetically.

## Create and Save

Make new entities and write them to the database. See [Working with Entities](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/working-with-entities).

| Function                                                                                       | Description                                                                         |
| ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)     | Instantiate a new entity, optionally with a struct of properties.                   |
| [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)   | Save an entity, or an array of entities, to the persistence context.                |
| [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge) | Merge the state of the given entity into the current persistence context (session). |

## Load

Read entities by id, by filter or by example.

| Function                                                                                                         | Description                                                                              |
| ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)                     | Load an entity or array of entities from the database.                                   |
| [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)             | Load an entity, or an array of entities, by primary key, optionally locked or read-only. |
| [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail) | Load an entity by its primary key, or throw `orm.notFound`.                              |
| [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)         | Load one entity by id or filter, or throw `orm.notFound`.                                |
| [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)           | Load an entity by id or filter, or return a new, unsaved one.                            |
| [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)         | Load an entity by id or filter, or create and save a new one.                            |
| [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)   | Load entities matching an example entity.                                                |
| [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)     | Load entities like `entityLoad()`, read-only.                                            |
| [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)     | Get a lazy reference to an entity by id without loading it from the database.            |
| [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)                 | Reload an entity from the database.                                                      |

## Delete

| Function                                                                                         | Description                                                   |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- |
| [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete) | Delete an entity, or an array of entities, from the database. |

## Query

Query with the fluent builder or HQL. See [Criteria Queries](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria) and [Queries and HQL](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/querying).

| Function                                                                                                     | Description                                                                                        |
| ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- |
| [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)         | Start a fluent query on an entity: conditions, joins, projections, paging, bulk updates and locks. |
| [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)       | Execute an HQL query with (optional) parameters and specific query options.                        |
| [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions) | Retrieve the named SQL functions registered with the `sqlFunctions` setting.                       |

## Convert

Turn entities into structs or queries. See [Entities as Structs](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs).

| Function                                                                                                     | Description                                                             |
| ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- |
| [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)         | Convert an entity or array of entities to a struct or array of structs. |
| [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct) | Load entities straight into structs, without loading the entities.      |
| [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)           | Convert an entity or array of entities to a Query object.               |

## Inspect

Ask about an entity or the entity model.

| Function                                                                                                                 | Description                                                                                                 |
| ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
| [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)                       | The entity name of an entity instance, lazy reference or name (a name comes back with its declared casing). |
| [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)                           | The primary key of an entity (a struct for composite keys).                                                 |
| [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)           | The name of the datasource an entity is stored in.                                                          |
| [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)               | The mapping metadata of an entity, as a struct.                                                             |
| [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)                       | Whether an entity has changes that are not saved yet.                                                       |
| [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties) | The names of an entity's properties whose values differ from the stored ones.                               |
| [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)                 | Check whether an entity is attached to the current ORM session.                                             |
| [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)                   | Retrieve an array of entity names for this ORM application.                                                 |
| [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)                     | Retrieve a list of entity names for this ORM application.                                                   |

## Session and Transactions

Work with the ORM session and database locks. See [Session Management](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/session-management) and [Transactions](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/transactions).

| Function                                                                                                               | Description                                                                                            |
| ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)                         | Remove an entity, or an array of entities, from the ORM session without deleting it.                   |
| [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)                           | Lock an entity's row in the database until the current transaction ends.                               |
| [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)                         | Run a closure with every entity it loads read-only.                                                    |
| [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)                               | Flush the Hibernate session, synchronizing the in-memory state with the database.                      |
| [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)                         | Flush all open Hibernate sessions in the current request.                                              |
| [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)                 | Clear the Hibernate session for the current context and provided (or default) datasource.              |
| [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)                 | Close the Hibernate session for the current context and provided (or default) datasource.              |
| [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)         | Close all Hibernate sessions for the current context on all datasources.                               |
| [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)             | Whether the ORM session for a datasource has changes that are not flushed to the database yet.         |
| [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics) | Statistics of the ORM session for a datasource: how many entities and collections it holds, and which. |
| [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)                     | Retrieve the Hibernate Session configured for this datasource or default datasource.                   |
| [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)       | Retrieve the Hibernate SessionFactory configured for this datasource or default datasource.            |

## Second-Level Cache

Evict data from the secondary cache. See [Caching](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/caching).

| Function                                                                                                     | Description                                                                                      |
| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)         | Evict all entity data for this entity name from the second-level cache.                          |
| [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection) | Evict all entity data for a given collection on a given entity type from the second-level cache. |
| [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)       | Evict all queries from the named or default cache on the named or default datasource.            |

## ORM Application

Reload and diagnose the ORM. See [Errors and Diagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/advanced/errors-and-diagnostics).

| Function                                                                                                             | Description                                                                                                    |
| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)                           | Reload the ORM application.                                                                                    |
| [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)                 | A snapshot of the ORM for this application: the first thing to check when something is wrong. It never throws. |
| [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion) | Retrieve the installed Hibernate version.                                                                      |


# EntityCriteria

Start a fluent criteria query on an entity

Start a fluent query on an entity. Chain conditions, joins, projections, ordering and options, then run it with a terminal method such as list(), count(), get(), first(), paginate() or each(). The updateAll() and deleteAll() terminals change every matching row with one statement, and lock() locks the rows a query returns.

## Method Signature

```
EntityCriteria(entityName=[String])
```

### Arguments

| Argument     | Type     | Required | Description          | Default |
| ------------ | -------- | -------- | -------------------- | ------- |
| `entityName` | `String` | `true`   | The entity to query. |         |

Returns a criteria builder. See [Criteria Queries](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria) for every method.

## Examples

Active users whose last name starts with "Sm", ordered:

```java
users = entityCriteria( "User" )
    .isEq( "active", true )
    .like( "lastName", "Sm%" )
    .order( "lastName" )
    .list();
```

Or-groups and association paths (joined automatically):

```java
admins = entityCriteria( "User" )
    .anyOf( ( c ) => c.isEq( "role.name", "admin" ).isTrue( "isSuperUser" ) )
    .count();
```

A page of results with its paging numbers:

```java
page = entityCriteria( "Order" )
    .isGe( "createdDate", dateAdd( "d", -30, now() ) )
    .orderByDesc( "createdDate" )
    .paginate( page = 2, maxRows = 25 );
// { results : [...], pagination : { page : 2, maxRows : 25, offset : 25, totalRecords : 130, totalPages : 6 } }
```

Grouped totals as structs:

```java
totals = entityCriteria( "Order" )
    .project( ( p ) => p.group( "status" ).count( "id", "orders" ).sum( "total", "revenue" ) )
    .asStruct()
    .list();
```

Structs built like `entityToStruct()`, read with projection queries instead of loading entities (see [Entities as Structs](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs)):

```java
users = entityCriteria( "User" )
    .isEq( "active", true )
    .asStruct( "id,name,role.name,orders" )
    .list();
```

A property argument can be a function call, including the application's named [`sqlFunctions`](https://bxorm.ortusbooks.com/bxorm-2.x/getting-started/configuration#named-sql-functions):

```java
thisYear = entityCriteria( "Order" ).isEq( "year(createdDate)", 2025 ).order( "lower(customer.name)" ).list();
```

Change or delete every matching row with one statement (no entity events or cascades, see [Bulk updates and deletes](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/criteria#bulk-updates-and-deletes)):

```java
archived = entityCriteria( "Order" ).isLt( "createdDate", cutoff ).updateAll( { status : "archived" } );
removed  = entityCriteria( "Session" ).isLt( "expires", now() ).deleteAll();
```

Lock the rows a query returns until the transaction ends:

```java
transaction {
    jobs = entityCriteria( "Job" ).isEq( "status", "new" ).lock( "write", { skipLocked : true } ).maxResults( 10 ).list();
}
```

See the SQL without running the query:

```java
writeOutput( entityCriteria( "User" ).isEq( "active", true ).getSQL( true ) );
```

## Related

* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityDelete

Delete one entity, or an array of entities, from the database

Delete one entity, or an array of entities, from the database.

Delete operations will cascade to related entities if `cascade` is enabled on the relationship property. The rows are deleted when the session flushes (at the end of the `transaction{}`); pass `{ flush : true }` to flush right away.

An array item that is not an entity raises an `orm.argument` error.

## Method Signature

```
EntityDelete(entity=[Any], options=[Struct])
```

### Arguments

| Argument  | Type     | Required | Description                                                      | Default |
| --------- | -------- | -------- | ---------------------------------------------------------------- | ------- |
| `entity`  | `Any`    | `true`   | The entity to delete, or an array of entities.                   |         |
| `options` | `Struct` | `false`  | Options: `flush` (boolean) flushes the session after the delete. |         |

## Examples

Delete an entity by passing the entity object to `entityDelete()`:

```java
entityDelete( entityLoadByPK( "Vehicle", "1HGCM82633A123456" ) );
```

Delete several entities and flush at once, so the rows are gone before the next statement runs:

```java
transaction {
    entityDelete( [ order1, order2 ], { flush : true } );
    remaining = queryExecute( "SELECT count(*) AS total FROM orders" ).total;
}
```

Note that this operation will also remove associated child entities depending on the `cascade` configuration in the entity property mapping. In this case, we wish a deletion of a blog post to also delete all associated comments:

```java
@cfc( "Comment" )
@fieldtype( "one-to-many" )
@inverse
@cascade( "delete" )
property comments;
...
entityDelete( entityLoadByPK( "blogPost", "779ccbb8-a444-11eb-ab6f-0290cc502ae3" ) );
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityEvict

Remove one entity, or an array of entities, from the ORM session

Remove one entity, or an array of entities, from the ORM session. The session stops tracking them: later changes to an evicted entity are not saved, and loading it again reads it fresh from the database. Nothing is deleted.

Unsaved changes to an evicted entity are dropped, so flush first (`ormFlush()`) if you want to keep them. Evicting an entity that is not in the session does nothing.

This is not the same as [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity), which removes cached data from the second-level cache and leaves the session alone.

## Method Signature

```
EntityEvict(entity=[Any])
```

### Arguments

| Argument | Type  | Required | Description                                                     | Default |
| -------- | ----- | -------- | --------------------------------------------------------------- | ------- |
| `entity` | `Any` | `true`   | An entity, or an array of entities, to remove from the session. |         |

Returns `null`.

## Examples

```java
entityEvict( user );
entityEvict( [ user, order ] );
```

Changes made after the eviction are not saved:

```java
user = entityLoadByPK( "User", 1 );
entityEvict( user );
user.setEmail( "new@example.com" );
ormFlush();                            // no UPDATE: the session no longer tracks the user
entityIsAttached( user );              // false
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityGetDatasource

The name of the datasource an entity is stored in

The name of the datasource an entity is stored in.

## Method Signature

```
EntityGetDatasource(entity=[Any])
```

### Arguments

| Argument | Type  | Required | Description                                                             | Default |
| -------- | ----- | -------- | ----------------------------------------------------------------------- | ------- |
| `entity` | `Any` | `true`   | An entity instance (loaded, new or a lazy reference) or an entity name. |         |

## Examples

```java
entityGetDatasource( "AuditLog" );                   // "audit"
entityGetDatasource( entityLoadByPK( "User", 1 ) );  // "app"
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityGetDirtyProperties

The names of an entity's properties whose values differ from the stored ones

The names of an entity's properties whose values differ from the stored ones.

## Method Signature

```
EntityGetDirtyProperties(entity=[Any])
```

### Arguments

| Argument | Type  | Required | Description                                      | Default |
| -------- | ----- | -------- | ------------------------------------------------ | ------- |
| `entity` | `Any` | `true`   | An entity instance (loaded or a lazy reference). |         |

Uses the same rules as [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty). Returns the names in mapping order; associations and collections are reported by their property name.

## Examples

```java
user = entityLoadByPK( "User", 1 );
user.setEmail( "new@example.com" );
user.setRole( entityLoadByPK( "Role", 2 ) );
entityGetDirtyProperties( user );   // [ "email", "role" ]
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityGetId

The primary key of an entity

The primary key of an entity. A lazy reference answers without being loaded. When given an entity name, there is no instance to read, so an `orm.argument` error is raised.

## Method Signature

```
EntityGetId(entity=[Any])
```

### Arguments

| Argument | Type  | Required | Description                                           | Default |
| -------- | ----- | -------- | ----------------------------------------------------- | ------- |
| `entity` | `Any` | `true`   | An entity instance (loaded, new or a lazy reference). |         |

Returns the id value; a struct of `{ property : value }` for a composite id; `null` when the entity has no id yet.

## Examples

```java
entityGetId( entityLoadByPK( "User", 5 ) );   // 5
entityGetId( entityNew( "User" ) );           // null
entityGetId( order.getCustomer() );           // the customer id, without loading the customer
entityGetId( playingField );                  // { fieldID : 1, fieldName : "North" }
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityGetMetadata

The mapping metadata of an entity, as a struct

The mapping metadata of an entity, as a struct. Built once per entity and cached for the life of the ORM application; each call returns a copy you may change.

## Method Signature

```
EntityGetMetadata(entity=[Any])
```

### Arguments

| Argument | Type  | Required | Description                                                             | Default |
| -------- | ----- | -------- | ----------------------------------------------------------------------- | ------- |
| `entity` | `Any` | `true`   | An entity instance (loaded, new or a lazy reference) or an entity name. |         |

### Returned keys

| Key                              | Description                                                                                                                                                                                        |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `entityName`                     | The entity name.                                                                                                                                                                                   |
| `className`                      | The BoxLang class path.                                                                                                                                                                            |
| `datasource`                     | The datasource name.                                                                                                                                                                               |
| `tableName`, `schema`, `catalog` | Where the entity is stored.                                                                                                                                                                        |
| `parent`                         | The parent entity name for inheritance, or empty.                                                                                                                                                  |
| `readOnly`                       | True for an immutable entity.                                                                                                                                                                      |
| `discriminator`                  | `{ column, value }` for single-table inheritance.                                                                                                                                                  |
| `idProperties`                   | The id property names (more than one for a composite id).                                                                                                                                          |
| `idType`                         | The id ormtype, or `composite`.                                                                                                                                                                    |
| `version`                        | The version property name, or empty.                                                                                                                                                               |
| `properties`                     | One struct per column-backed property: `name`, `column` (empty for a formula), `ormtype`, `fieldtype`, `nullable`, `unique`, `length`, `precision`, `scale`, `formula`, `insertable`, `updatable`. |
| `associations`                   | One struct per association: `name`, `kind` (`many-to-one`, `one-to-many`, ...), `target` (entity name), `cascade`, `lazy`, `inverse`, `fkcolumn`, `mappedBy`, `linkTable`, `orderBy`.              |
| `propertyNames`                  | Every non-id property name.                                                                                                                                                                        |

## Examples

```java
meta = entityGetMetadata( "User" );
meta.tableName;                              // "users"
meta.idProperties;                           // [ "id" ]
meta.associations.map( a => a.name );        // [ "role", "orders" ]
meta.properties.filter( p => !p.nullable );  // required columns
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityGetName

The entity name of an entity instance, lazy reference or name

The entity name of an entity instance, lazy reference or name (a name comes back with its declared casing).

## Method Signature

```
EntityGetName(entity=[Any])
```

### Arguments

| Argument | Type  | Required | Description                                                             | Default |
| -------- | ----- | -------- | ----------------------------------------------------------------------- | ------- |
| `entity` | `Any` | `true`   | An entity instance (loaded, new or a lazy reference) or an entity name. |         |

Returns a string, e.g. `"User"`. A lazy reference answers without being loaded, even after its session closed.

## Examples

```java
user = entityLoadByPK( "User", 1 );
entityGetName( user );        // "User"
entityGetName( "uSeR" );      // "User" (declared casing)
entityGetName( user.getRole() ); // "Role", without loading the role
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityGetReference

Get a reference to an entity by id without loading it from the database

Get a reference to an entity by id without loading it from the database.

Use it to set an association when all you have is the id: no `SELECT` runs.

The reference is a lazy proxy. Reading any of its properties or calling its methods loads the row then, and fails at that point if no row has that id. When the session already holds the entity, that entity is returned.

## Method Signature

```
EntityGetReference(entityName=[String], id=[Any])
```

### Arguments

| Argument     | Type     | Required | Description                                                               | Default |
| ------------ | -------- | -------- | ------------------------------------------------------------------------- | ------- |
| `entityName` | `String` | `true`   | The name of the entity.                                                   |         |
| `id`         | `Any`    | `true`   | The primary key value, or a struct of key/value pairs for composite keys. |         |

Returns the reference: an unloaded proxy, or the entity when the session already holds it.

## Examples

Set an association from a form value, without loading the customer:

```java
order.setCustomer( entityGetReference( "Customer", form.customerId ) );
entitySave( order );
```

Composite keys take a struct:

```java
vehicleType = entityGetReference( "VehicleType", { make : "Ford", model : "Fusion" } );
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityIsAttached

Check whether an entity is attached to the current ORM session

Check whether an entity is attached to the current ORM session.

## Method Signature

```
EntityIsAttached(entity=[class])
```

### Arguments

| Argument | Type    | Required | Description                   | Default |
| -------- | ------- | -------- | ----------------------------- | ------- |
| `entity` | `class` | `true`   | The entity instance to check. |         |

## Examples

Check whether a loaded entity is still attached to its datasource's session:

```java
manufacturer = entityLoadByPK( "Manufacturer", 1 );
isAttached   = entityIsAttached( manufacturer );

entityEvict( manufacturer );
isAttached   = entityIsAttached( manufacturer ); // false
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityIsDirty

Whether an entity has changes that are not saved yet

Whether an entity has changes that are not saved yet.

## Method Signature

```
EntityIsDirty(entity=[Any])
```

### Arguments

| Argument | Type  | Required | Description                                      | Default |
| -------- | ----- | -------- | ------------------------------------------------ | ------- |
| `entity` | `Any` | `true`   | An entity instance (loaded or a lazy reference). |         |

An entity in the current session is compared with the values it was loaded with (no SQL). An entity outside the session is compared with a fresh read of its row. An entity that was never saved, or a lazy reference that was never loaded, is not dirty. An entity name raises `orm.argument`.

## Examples

```java
user = entityLoadByPK( "User", 1 );
entityIsDirty( user );          // false
user.setEmail( "new@example.com" );
entityIsDirty( user );          // true
ormFlush();
entityIsDirty( user );          // false
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityLoad

Load an entity or an array of entities by id or filter

Load an entity or array of entities from the database.

You can pass a struct of query options, including pagination, caching, and sort options.

## Options

* **`unique`** - Boolean. Specifies whether to retrieve a single, unique item. Default is `false`. If more than one entity matches the filter, an `orm.query.nonUnique` error is raised.
* **`uniqueFirst`** - Boolean. Return the first match even when several entities match (implies `unique`). Default is `false`.
* **`ignorecase`** - Boolean. Sorts text properties without regard to case. Number and date properties are sorted as-is. Use it with a sort string in `uniqueOrOrder`. Defaults to `false`.
* **`offset`** - Number. Specifies the pagination offset. Defaults to 0.
* **`maxresults`** - Number. Specifies the maximum number of objects to be retrieved.
* **`cacheable`** - Boolean. Whether the result has to be cached in the second-level query cache (needs `secondaryCacheEnabled`). Default is `false`.
* **`cachename`** - String. The query cache region to use. Implies `cacheable` unless `cacheable` is given.
* **`timeout`** - Number. Specifies the timeout value (in seconds) for the query. No timeout by default.
* **`readOnly`** - Boolean. Load the entities read-only: they are not dirty-checked and changes to them are never saved. Works for filter loads and loads by id. Default is `false`. See also `entityLoadReadOnly()`.
* **`asStream`** - Boolean. Return a Java `Stream` that reads the entities from the database as it is consumed, instead of an array. Consume it in the same request. Not allowed with `unique` (`orm.argument`). Default is `false`.

For a load by id, only `readOnly` and `asStream` apply. The other options are for filter loads.

## Method Signature

```
EntityLoad(entityName=[string], idOrFilter=[any], uniqueOrOrder=[any], options=[struct])
```

### Arguments

| Argument        | Type     | Required | Description                                                                                                                                  | Default |
| --------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `entityName`    | `string` | `true`   | The name of the entity to load.                                                                                                              |         |
| `idOrFilter`    | `any`    | `false`  | Either the ID of the entity to load, or a struct of filter criteria.                                                                         |         |
| `uniqueOrOrder` | `any`    | `false`  | A boolean (return one entity), or a comma-separated sort string such as `"lastName desc, firstName"`. A struct here is treated as `options`. |         |
| `options`       | `struct` | `false`  | A struct of options to modify the load operation. See below for supported options.                                                           |         |

## Examples

## Loading an Entity Array

To load an array of Autos from the database where the `Make` is `Ford`, you would do the following:

```java
var allFords = entityLoad( "Auto", { Make = "Ford" } );
```

By default, all matching records are returned. If you want to paginate the result set, you can pass a struct with query options as the fourth argument:

```java
var firstTenFords = entityLoad(
    "Auto",                         // first arg: entity name
    { Make = "Ford" },              // second arg: criteria struct
    false,                          // third arg: false for "not unique"
    { maxResults = 10, offset = 0 } // fourth arg: option struct
);
```

### Loading Unique Entities

We can also load single, unique entity results by passing `true` in the third argument to indicate that we want a single, unique result. For example, to load an entity named `Auto` with an ID of `123`, you would do the following:

```java
var myEntity = entityLoad( "Auto", 123, true );
```

This will retrieve the entity from the database and populate the `myEntity` variable with its data. If the entity is not found, `null` is returned.

You can also use the `entityLoad()` function to load an entity by its unique properties, even if they are not the primary key. For example, to load an `Auto` entity with a specific `VIN`, you could do the following:

```java
var myEntity = entityLoad( "Auto", { VIN = "1HGCM82633A123456" }, true );
```

This will search for the `Auto` entity with the specified `VIN` and return it if found.

### When Nothing Matches

`entityLoad()` does not throw when nothing is found. A unique load returns `null`, and any other load returns an empty array. Use [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail) to get an `orm.notFound` error instead.

### Sorting

Pass a comma-separated sort string as the third argument:

```java
var people = entityLoad( "Person", { active = true }, "lastName desc, firstName" );
```

### Loading Read-Only Entities

Pass `readOnly : true` to load entities that are not dirty-checked. Changes made to them are never saved, which keeps large reads light:

```java
var shipped = entityLoad( "Order", { status = "shipped" }, "createdDate desc", { readOnly = true } );
```

[EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly) does the same without the option.

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityLoadAsStruct

Load entities straight into structs with projection queries

Load entities straight into structs, without loading the entities: one projection query for the plain values and to-one associations (left joins), plus one query per to-many association, limited to the ids just read. The structs match what `entityToStruct()` builds for the same includes: the entity's `this.memento`, includes, excludes, mappers, defaults, profiles and ISO 8601 dates.

* An id returns a struct, or `null` when no row matches.
* A filter struct (property values to match, `null` for `is null`) returns an array of structs, or one struct (or `null`) with the `unique` option. Several matching rows with `unique` raise `orm.query.nonUnique`.
* Collections come back in id order.

A property whose getter you wrote is read through that getter, as in `entityToStruct()`: the row's plain values are copied into a scratch instance and the getter is called on it (associations are not loaded there). Includes that are only getters, not properties, need a loaded entity: one listed in the entity's `this.memento` defaults is left out, and one you ask for in `includes` raises `orm.argument` (use `entityToStruct()`, or compute the key with a mapper). Value collections (`@fieldtype( "collection" )`) and entities with a composite id raise `orm.argument` too. An unknown include raises `orm.property.unknown`.

See [Entities as Structs](https://bxorm.ortusbooks.com/bxorm-2.x/working-with-entities/structs).

## Method Signature

```
EntityLoadAsStruct(entityName=[String], idOrFilter=[Any], includes=[Any], options=[Struct])
```

### Arguments

| Argument     | Type     | Required | Description                                                                                                                                                  | Default |
| ------------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
| `entityName` | `String` | `true`   | The name of the entity.                                                                                                                                      |         |
| `idOrFilter` | `Any`    | `true`   | The primary key value, or a struct of property values to match.                                                                                              |         |
| `includes`   | `Any`    | `false`  | Properties and dotted association paths to add to the entity's defaults, as a list or array. Empty for the defaults only.                                    |         |
| `options`    | `Struct` | `false`  | `sortOrder`, `maxResults`, `offset`, `unique`, and the struct options of `entityToStruct()`: `excludes`, `mappers`, `defaults`, `ignoreDefaults`, `profile`. |         |

Returns a struct or `null` for an id (or a filter with `unique`), else an array of structs.

## Examples

By id, with the entity's defaults and one association field:

```java
user = entityLoadAsStruct( "User", 42, "role.name" );
// { id : 42, firstName : "Ann", ..., role : { name : "admin" } }
```

By filter, with a collection, sorted and limited:

```java
users = entityLoadAsStruct( "User", { active : true }, "orders", { sortOrder : "lastName", maxResults : 20 } );
```

A profile and no extra includes:

```java
rows = entityLoadAsStruct( "User", { active : true }, "", { profile : "list" } );
```

One struct from a filter:

```java
user = entityLoadAsStruct( "User", { email : "ann@example.com" }, "", { unique : true } );
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityLoadByExample

Load entities matching an example entity

Load entities matching an example entity.

Every property of the example that has a value becomes an equality match. These are left out of the match:

* the id properties
* the version property
* associations
* properties that are `null`

With `unique=true`, the first match is returned (or `null`). Several matches do not raise a non-unique error.

## Method Signature

```
EntityLoadByExample(sampleEntity=[any], unique=[boolean])
```

### Arguments

| Argument       | Type      | Required | Description                                                       | Default |
| -------------- | --------- | -------- | ----------------------------------------------------------------- | ------- |
| `sampleEntity` | `any`     | `true`   | Instance of an ORM entity to use as an example for the query.     |         |
| `unique`       | `boolean` | `false`  | Return the first match (true) or an array of all matches (false). | `false` |

## Examples

Load all matching entities using a sample entity as the filter.

```java
sample = entityNew( "Manufacturer", { name: "Honda" } );
matches = entityLoadByExample( sample );
```

Pass `unique=true` to return a single matching entity:

```java
sample = entityNew( "Manufacturer", { name: "Honda" } );
singleMatch = entityLoadByExample( sample, true );
```

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByPK](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypk)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)


# EntityLoadByPK

Load an entity, or several entities, by primary key

Load an entity by its primary key.

```js
var myAuto = entityLoadByPK( "Automobile", "1HGCM82633A123456" );
```

In Lucee, by default, an array of entities is returned and you must pass a third `unique=true` argument to return only a single entity. In BoxLang, only a single entity is returned - matching the Adobe ColdFusion behavior. A boolean third argument (Lucee's `unique`) is accepted and ignored. To return an array of entities, use the `entityLoad` BIF, or pass an array of ids.

Pass an array of ids to load several entities in one query. The result is an array in the order of the ids, with null where no row has that id:

```js
users = entityLoadByPK( "User", [ 3, 1, 99 ] ); // [ user3, user1, null ]
```

Composite keys are also supported:

```js
entityLoadByPK( "VehicleType", { make : "Ford", model: "Fusion" } );
```

## Options

The third argument is a struct of load options. They apply to every entity of an array of ids too:

| Option       | Description                                                                                                                                                                                                                       |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `lock`       | Lock the row while loading it: `read`, `write` or `force` (see [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)). Needs `transaction{}`, otherwise an `orm.argument` error is raised. |
| `timeout`    | Seconds to wait for the lock. `0` means do not wait. Only applies together with `lock`.                                                                                                                                           |
| `skipLocked` | Return `null` instead of waiting when the row is locked by someone else. Only applies together with `lock`.                                                                                                                       |
| `readOnly`   | Load the entity read-only, so changes to it are never saved.                                                                                                                                                                      |

## Method Signature

```
EntityLoadByPK(entity=[String], id=[Any], options=[Any])
```

### Arguments

| Argument  | Type     | Required | Description                                                                                                                  | Default |
| --------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------- | ------- |
| `entity`  | `String` | `true`   | The name of the entity to load.                                                                                              |         |
| `id`      | `Any`    | `true`   | The primary key value, a struct of key/value pairs for composite keys, or an array of either.                                |         |
| `options` | `Any`    | `false`  | A struct of load options: `lock`, `timeout`, `skipLocked`, `readOnly`. A boolean (Lucee's `unique`) is accepted and ignored. |         |

## Examples

### Load by Primary Key

Load entity by primary key:

```java
vehicle = entityLoadByPK( "Vehicle", "1HGCM82633A123456" );
```

### Load by Composite Key

Pass a struct when the entity key is composite.

```java
vehicleType = entityLoadByPK( "VehicleType", { make: "Ford", model: "Fusion" } );
```

### Load Several by Primary Key

Pass an array of ids to load them all with one batched query. The array keeps the order you asked for, with `null` where no row has that id. An id asked for twice returns the same instance twice:

```java
users = entityLoadByPK( "User", [ 3, 1, 99 ] );
// [ user3, user1, null ]

types = entityLoadByPK( "VehicleType", [ { make: "Honda", model: "Civic" }, { make: "Ford", model: "Fusion" } ] );

reports = entityLoadByPK( "Report", ids, { readOnly : true } );
```

An empty array returns an empty array.

### Load and Lock

Lock the row until the transaction ends, so no one else can change it in the meantime:

```java
transaction {
    account = entityLoadByPK( "Account", id, { lock : "write" } );
    account.setBalance( account.getBalance() - amount );
}
```

Skip a row another transaction has locked instead of waiting for it:

```java
transaction {
    job = entityLoadByPK( "Job", id, { lock : "write", skipLocked : true } );
    if ( isNull( job ) ) {
        // someone else is working on it
    }
}
```

### Load Read-Only

```java
report = entityLoadByPK( "Report", id, { readOnly : true } );
```

To throw an `orm.notFound` error instead of returning `null`, use [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail).

## Related

* [EntityCriteria](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitycriteria)
* [EntityDelete](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitydelete)
* [EntityEvict](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityevict)
* [EntityGetDatasource](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdatasource)
* [EntityGetDirtyProperties](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetdirtyproperties)
* [EntityGetId](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetid)
* [EntityGetMetadata](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetmetadata)
* [EntityGetName](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetname)
* [EntityGetReference](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitygetreference)
* [EntityIsAttached](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisattached)
* [EntityIsDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityisdirty)
* [EntityLoad](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityload)
* [EntityLoadAsStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadasstruct)
* [EntityLoadByExample](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbyexample)
* [EntityLoadByPKOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadbypkorfail)
* [EntityLoadOrFail](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorfail)
* [EntityLoadOrNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadornew)
* [EntityLoadOrSave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadorsave)
* [EntityLoadReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityloadreadonly)
* [EntityLock](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitylock)
* [EntityMerge](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitymerge)
* [EntityNameArray](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamearray)
* [EntityNameList](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynamelist)
* [EntityNew](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitynew)
* [EntityReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entityreload)
* [EntitySave](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitysave)
* [EntityToQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytoquery)
* [EntityToStruct](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/entitytostruct)
* [ORMClearSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclearsession)
* [ORMCloseAllSessions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormcloseallsessions)
* [ORMCloseSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormclosesession)
* [ORMDiagnostics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormdiagnostics)
* [ORMEvictCollection](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictcollection)
* [ORMEvictEntity](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictentity)
* [ORMEvictQueries](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormevictqueries)
* [ORMExecuteQuery](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormexecutequery)
* [ORMFlush](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflush)
* [ORMFlushAll](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormflushall)
* [ORMGetHibernateVersion](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgethibernateversion)
* [ORMGetSQLFunctions](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsqlfunctions)
* [ORMGetSession](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsession)
* [ORMGetSessionFactory](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionfactory)
* [ORMGetSessionStatistics](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormgetsessionstatistics)
* [ORMIsSessionDirty](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormissessiondirty)
* [ORMReadOnly](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreadonly)
* [ORMReload](https://bxorm.ortusbooks.com/bxorm-2.x/reference/built-in-functions/ormreload)




---

[Next Page](https://bxorm.ortusbooks.com/llms-full.txt/1)

