Overview
The cborm module will enhance your ORM Entities and ColdBox application by providing you with features in the following areas:
    Active Record Pattern
      You can extend your entities from our ActiveEntity class and take advantage of both Active Record and Hibernate ORM
    Entity Population
      Easily populate entities from json, structs, xml, queries and build up even the entity relationships from flat data.
    Entity Marshalling to raw data types (mementifier)
      Easily extract the data from entities and their relationships so you can marshall them to json, xml, etc.
    Automatic CRUD Resource Handler
      If you extend our cborm.models.resources.BaseHandler it will generate the full CRUD for a specific entity based on ColdBox Resources
    ORM Events
      Easily listen to multiple ORM events via ColdBox Interceptors
    Service Layers
      Enhance the ability to list, query, find entities, work with native hibernate constructs and more.
    Validation
      We provide you with a unique validator to validate against unique columns
Just write your entities and their relationships and we will take care of the rest!

Base ORM Service

Let's begin our adventure with the BaseORMService model. This model can be injected or requested via WireBox and will be used to interact with any entity in our system or with Hibernate directly:
1
// inject via dsl
2
property name="ormService" inject="entityService";
3
// inject via alias
4
property name="ormService" inject="[email protected]";
5
6
// use via alias
7
getInstance( "[email protected]" );
8
// use via dsl
9
getInstance( dsl="entityService" );
Copied!
This service object acts as an abstraction layer to the ColdFusion ORM (Hibernate) and can work with any entity in your system as all methods most likely receive the entityName argument. You will be able to do the following category of actions from this service class:
    Hibernate Session utility methods
    Entity metadata methods
    Querying methods
    Criteria Queries or fluent SQL
    Getters
    Finders
    Dynamic Finders
    Counters
    Dynamic Counters
    Persistence (save,update,delete) and bulk persistence with transactions
    Eviction Methods
    Population Methods
This means that you don't need to create a service layer CFC in order to work with ORM entities, you can leverage this abstraction to work with your ORM needs. You can also specifically bind (root) the service to a specific entity, which we lovingly call a VirtualEntityService. This way you don't have to be passing the entity names left and right, the virtual entity service will be constructed with the name and all operations will be done upon that entity.

Example

Once you have access to the injected base ORM service, you can use it in all of its glory.
Important Please check out the latest API Docs for the latest methods and functionality: https://apidocs.ortussolutions.com/#/coldbox-modules/cborm/
1
component{
2
3
inject name="ormService" inject="entityService";
4
5
function saveUser( event, rc, prc ){
6
// retrieve and populate a new user object
7
var user = populateModel( ormService.new( "User" ) );
8
9
// save the entity using hibernate transactions
10
ormService.save( user );
11
12
relocate( "user.list" );
13
}
14
15
function list( event, rc, prc ){
16
17
// get a listing of all users with pagination and filtering
18
prc.users = ormService.list(
19
entityName = "User",
20
criteria = { isActive : true },
21
sortOrder = "fname",
22
offset = event.getValue( "startrow", 1 ),
23
max = 20
24
);
25
26
event.setView( "user/list" );
27
}
28
29
// Dynamic Finders
30
function findUsers( event, rc, prc ){
31
prc.data = ormService.findByRoleAndIsActive( "User", "Admin", true );
32
}
33
34
// Fluent Criteria Queries
35
function searchContent( event, rc, prc ){
36
prc.dataStream = ormService
37
.newCriteria( "Content" )
38
.isEq( "published", rc.isPublished )
39
.isLt( "publishedDate", now() )
40
.or(
41
ormService.getRestrictions().isNull( "expireDate" ),
42
ormService.getRestrictions().isGT( "expireDate", now() )
43
)
44
.isEq( "passwordProtection", "" )
45
.joinTo( "activeContent", "ac" )
46
.like( "title", "%#rc.searchTerm#%" )
47
.asStream()
48
.list( offset=rc.offset, max=50 );
49
50
event.setView( "content/search")
51
}
52
53
}
Copied!
What is this asStream() call? What are Streams?
A stream is an abstraction, it’s not a data structure. It’s not a collection where you can store elements. The most important difference between a stream and a structure is that a stream doesn’t hold the data. For example you cannot point to a location in the stream where a certain element exists. You can only specify the functions that operate on that data. A stream is an abstraction of a non-mutable collection of functions applied in some order to the data.
More information can be found here: https://forgebox.io/view/cbstreams

Virtual Services

We also have a virtual service layer that can be mapped to specific entities and create entity driven service layers virtually. Meaning you don't have to be passing any entity names to the API methods to save you precious typing time. This is achieved via the VirtualEntityService model which inherits from the BaseORMService class.
You can achieve this in several manners:
    Injection
      entityService:{EntityName}
    Request via WireBox using the DSL argument of getInstance()
      getInstance( dsl = entityService:{EntityName} );
    Request via a Base ORM Service
      createService()
1
// Injection
2
property name="userService" inject="entityService:User"
3
4
// Request it
5
contentService = getInstance( dsl = "entityService:Content" );
6
7
// Via ORM Service
8
ormService.createService( entityName="Content", useQueryCaching=true );
Copied!
That's it! You can use it just like the BaseORMService except no more passing the entity name.

Example

1
component{
2
3
inject name="userService" inject="entityService:User";
4
5
function saveUser( event, rc, prc ){
6
// retrieve and populate a new user object
7
var user = populateModel( userService.new() );
8
9
// save the entity using hibernate transactions
10
userService.save( user );
11
12
relocate( "user.list" );
13
}
14
15
function list( event, rc, prc ){
16
17
// get a listing of all users with pagination and filtering
18
prc.users = userService.list(
19
criteria = { isActive : true },
20
sortOrder = "fname",
21
offset = event.getValue( "startrow", 1 ),
22
max = 20
23
);
24
25
event.setView( "user/list" );
26
}
27
28
// Dynamic Finders
29
function findUsers( event, rc, prc ){
30
prc.data = userService.findByRoleAndIsActive( "Admin", true );
31
}
32
33
// Criteria Queries
34
function searchContent( event, rc, prc ){
35
prc.dataStream = userService
36
.newCriteria()
37
.isEq( "published", rc.isPublished )
38
.isLt( "publishedDate", now() )
39
.or(
40
ormService.getRestrictions().isNull( "expireDate" ),
41
ormService.getRestrictions().isGT( "expireDate", now() )
42
)
43
.isEq( "passwordProtection", "" )
44
.joinTo( "activeContent", "ac" )
45
.like( "title", "%#rc.searchTerm#%" )
46
.asStream()
47
.list( offset=rc.offset, max=50 );
48
49
event.setView( "content/search")
50
}
51
52
}
Copied!

Concrete Services

This is where you create your own CFC that inherits from our VirtualEntityService and either adds or overrides methods. The virtual and base services takes you about 90% of the way. With you concrete services, you can complete the functionality to your liking.
All you need to do is inherit from the cborm.models.VirtualEntityService and call the parent class constructor with the available arguments:
    entityname - The name of the entity to root this service with (REQUIRED)
    queryCacheRegion - The name of the query cache region if using caching, defaults to #arguments.entityName#.defaultVSCache
    useQueryCaching - Activate query caching, defaults to false
    eventHandling - Activate event handling, defaults to true
    useTransactions - Activate transaction blocks on calls, defaults to true
    defaultAsQuery - Return query or array of objects on list(), executeQuery(), criteriaQuery(), defaults to true
    datasource - The datasource name to be used for the rooted entity, if not we use the default datasource
models/ContentService.cfc
1
component extends="cborm.models.VirtualEntityService" singleton{
2
3
/**
4
* Constructor
5
* @entityName The content entity name to bind this service to.
6
*/
7
ContentService function init( entityName="cbContent" ){
8
// init it
9
super.init( entityName=arguments.entityName, useQueryCaching=true );
10
11
return this;
12
}
13
14
}
Copied!

Active Entity

If you want to apply an Active Record and fluent feel to your entities then ActiveEntity is just for you. Just inherit from cborm.models.ActiveEntity and you are on your way to Active Record bliss.
ActiveEntity inherits from the VirtualEntityService class which inherits from the BaseORMService class. So you have the full gamut of usage plus the ability for the active entity to validate itself. It has the isValid() and getValidationResults() methods to help you with the validation of a populated entity.

Example Entity

models/User.cfc
1
component persistent="true" table="users" extends="cborm.models.ActiveEntity"{
2
3
property name="id" column="user_id" fieldType="id" generator="uuid";
4
5
/**
6
* @display First Name
7
* @message Please provide firstname
8
* @NotEmpty
9
*/
10
property name="firstName";
11
12
/**
13
* @display Last Name
14
* @message Please provide lastname
15
* @NotEmpty
16
*/
17
property name="lastName";
18
property name="userName";
19
property name="password";
20
property name="lastLogin" ormtype="date";
21
22
// M20 -> Role
23
property name="role" cfc="Role" fieldtype="many-to-one" fkcolumn="FKRoleID" lazy="true" notnull="false";
24
25
// DI Test
26
property name="wirebox" inject="wirebox" persistent="false";
27
28
// Constraints
29
this.constraints = {
30
firstName = { required=true },
31
lastName = { required=true },
32
username = { required=true, min=5, validator="[email protected]" },
33
password = { required=true, min=6 }
34
};
35
36
}
Copied!

Example Usage

1
user = entityNew( "User" ).get( 2 );
2
var isValid = entityNew( "User" )
3
.populate( memento=rc, composeRelationships=true )
4
.isValid();
5
6
user = entityNew( "User" ).findAllByIsActive( true );
7
user = entityNew( "User" )
8
.get( 4 )
9
.setName( "Awesome" )
10
.save();
11
12
entityNew( "User" )
13
.getOrFail( 4 )
14
.delete();
15
16
prc.users = entityNew( "User" )
17
.findAllWhere(
18
criteria = { isActive:true, role:entityNew( "Role" ).findByName( "Admin" ) },
19
stream = true
20
);
Copied!

Automatic ORM Resource Handler

If you are creating RESTful services, you can leverage our new Base ORM Handler that will give you a full CRUD service for your entities. All you have to do is the following:
    1.
    Create your entities
      1.
    2.
    Register the resource in your application router or module router
      1.
      resources( "users" )
    3.
    Create the handler that will manage that resource and extend our base handler, spice up as needed and you are done:
handlers/users.cfc
1
/**
2
* My awesome cb6 resources handler
3
*/
4
component extends="cborm.models.resources.BaseHandler"{
5
6
// Inject the correct service as the `ormService` for the resource Handler
7
property name="ormService" inject="entityService:Role";
8
9
// The default sorting order string: permission, name, data desc, etc.
10
variables.sortOrder = "name";
11
// The name of the entity this resource handler controls. Singular name please.
12
variables.entity = "Role";
13
14
}
Copied!
That's it! This handler will now manage ALL the CRUD operations in REST format for your entity including relationships, validations, pagination and data marshalling.
ColdBox Resources
Last modified 1yr ago