Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
ormService.clear();component persistent="true" table="your_table" extends="cborm.models.ActiveEntity"{
}// ORM services, injection, etc
orm = {
// entity injection
injection = {
// enable it
enabled = true,
// the include list for injection
include = "",
// the exclude list for injection
exclude = ""
}
};user = entityNew( "User" ).findByLastName( "Majano", { ignoreCase=true, timeout=20 } );
users = entityNew( "User" ).findAllByLastNameLike( "Ma%", { ignoreCase=false, max=20, offset=15 } );// get a new User entity
user = entityNew("User");
// Count all the users in the database
usersFound = user.count();
// create a new user entity and pre-populate it with data
coolUser = user.new( {firstName="Luis",lastName="Majano",Awesome=true} );
// save the user object
coolUser.save();
// Retrieve a user with an ID of 123
luis = user.get("123");import coldbox.system.orm.hibernate.*
userService = new VirtualEntityService(entityName="User");
userService = new VirtualEntityService(entityName="User",useQueryCaching=true);
usersFound = userService.count();
user = userService.new({firstName="Luis",lastName="Majano",Awesome=true});
userService.save( user );
user = userService.get("123");
var users = userService.newCriteria()
.like("lastName", "%maj%")
.isTrue("isActive")
.list(sortOrder="lastName");this.ormSettings = {
cfclocation="model",
dbcreate = "update",
dialect = "MySQLwithInnoDB",
logSQL = true,
// Enable event handling
eventhandling = true,
// Set the event handler to use, which will be inside our application.
eventhandler = "model.ORMEventHandler"
};// Enable event handling
eventhandling = true,
// Set the event handler to use, which will be inside our application.
eventhandler = "model.ORMEventHandler"// From base ORM service
var restrictions = getRestrictions()
// Manually Created
var restrictions = new coldbox.system.orm.hibernate.criterion.Restrictions();
// From Criteria Builder
newCriteria().restrictionscriteria.eq( "id", javaCast( "int", arguments.id ) );// Coverts a value to the correct javaType for the property passed in The method returns the value in the proper Java Type
any convertValueToJavaType( any propertyName, any value )
// Coverts an ID, list of ID's, or array of ID's values to the proper java type The method returns a coverted array of ID's
any convertIDValueToJavaType( any id )criteria.eq( "id", criteria.convertIDValueToJavaType( arguments.id ) );// Restrictions used with criteria queries
var r = ormService.getRestrictions();
var users = ormService.newCriteria("User")
.or( r.eq("lastName","majano"), r.gt("createDate", now()) )
.list();c.convertIDValueToJavaType( id = 123 );
c.convertIDValueToJavaType( id = ["1","2","3"] );
c.convertValueToJavaType(propertyName="id", value=arguments.testUserID)ormService.evict(entityName="Account",account.getID());
ormService.evict(entityName="Account");
ormService.evict(entityName="Account", collectionName="MyAccounts");User.findBy{property}[Conditional=equal][Operator]?{property}[Conditional][Operator]
User.findAllBy{property}[Conditional=equal][Operator]?{property}[Conditional][Operator]
User.countBy{property}[Conditional=equal][Operator]?{property}[Conditional][Operator]// evict one entity
ORMService.evictEntity( entity );
// evict an array of entities
entities = [ user1, user2 ];
ORMService.evictEntity( entities );this.mappings[ "/cborm" ] = COLDBOX_APP_ROOT_PATH & "modules/cborm";orm = {
injection = {
enabled = true, include = "", exclude = ""
}
}{ fieldName : { validator: "UniqueValidator@cborm" } }<major>.<minor>.<patch>cbvalidation to v1.1.0component persistent="true" name="User" extends="cborm.models.ActiveEntity"{
property name="id" column="user_id" fieldType="id" generator="uuid";
property name="lastName";
property name="userName";
property name="password";
property name="lastLogin" ormtype="date";
}user = entityNew( "User" ).findByLastName( "Majano" );
users = entityNew( "User" ).findAllByLastNameLike( "Ma%" );
users = entityNew( "User" ).findAllByLastLoginBetween( "01/01/2010", "01/01/2012" );
users = entityNew( "User" ).findAllByLastLoginBetweeninGreaterThan( "01/01/2010" );
users = entityNew( "User" ).findAllByLastLoginGreaterThanAndLastNameLike( "01/01/2010", "jo%" );
count = entityNew( "User" ).countByLastLoginGreaterThan( "01/01/2010" );
count = entityNew( "User" ).countByLastLoginGreaterThanAndLastNameLike( "01/01/2010", "jo%" );// Get
var results = c.idEq( 4 ).get();
// Listing
var results = c.like("name", "lui%")
.list();
// Count via projections of all users that start with the letter 'L'
var count = c.ilike("name","L%").count();// delete all blog posts
ormService.deleteByQuery("from Post");
// delete query with positional parameters
ormService.deleteByQuery("from Post as b where b.author=? and b.isActive = :active",['Luis Majano',false]);
// Use query options
var query = "from User as u where u.isActive=false order by u.creationDate desc";
// first 20 stale inactive users
ormService.deleteByQuery(query=query,max=20);
// 20 posts starting from my 15th entry
ormService.deleteByQuery(query=query,max=20,offset=15,flush=true);
// examples with named parameters
ormService.deleteByQuery("from Post as p where p.author=:author", {author='Luis Majano'})userService = ormService.createService("User");
userService = ormService.createService("User",true);
userService = ormService.createService("User",true,"MyFunkyUserCache");
// Remember you can use virtual entity services by autowiring them in via our DSL
component{
property name="userService" inject="entityService:User";
property name="postService" inject="entityService:Post";
}// Find a category according to the named value pairs I pass into this method
var category = ormService.findWhere(entityName="Category", criteria={isActive=true, label="Training"});
var user = ormService.findWhere(entityName="User", criteria={isActive=true, username=rc.username,password=rc.password});var post = ormService.get(1);
ormService.delete( post );
// Delete a flush immediately
ormService.delete( post, true );currentUser = ormService.findByExample( session.user, true );// Get a virtual entity service via DI, there are many ways to get a virtual entity service
// Look at virtual entity service docs for retrieval
property name="userService" inject="entityservice:userService";
user = userService.findByLastName( "Majano" );
users = userService.findAllByLastNameLike( "Ma%" );
users = userService.findAllByLastLoginBetween( "01/01/2010", "01/01/2012" );
users = userService.findAllByLastLoginGreaterThan( "01/01/2010" );
users = userService.findAllByLastLoginGreaterThanAndLastNameLike( "01/01/2010", "jo%" );
count = userService.countByLastLoginGreaterThan( "01/01/2010" );
count = userService.countByLastLoginGreaterThanAndLastNameLike( "01/01/2010", "jo%" );// Get a virtual entity service via DI, there are many ways to get a base entity service
// Look at base entity service docs for retrieval
property name="userService" inject="entityservice";
user = userService.findByLastName( "User", "Majano" );component extends="cborm.models.BaseORMService"{
public UserService function init(){
super.init( useQueryCaching=true, eventHandling=false );
return this;
}
}// return empty post entity
var post = ormService.new("Post");
var user = ormService.new(entityName="User",properties={firstName="Luis", lastName="Majano", age="32", awesome=true});
var user = ormService.new("User",{fname="Luis",lname="Majano",cool=false,awesome=true});var pkField = ormService.getKey( "User" );ormService.deleteAll("Tags");// merge a single entity back
ormService.merge( userEntity );
// merge an array of entities
collection = [entity1,entity2,entity3];
ormService.merge( collection );// Let's get the session statistics
stats = ormService.getSessionStatistics;
// Lets output it
<cfoutput>
collection count: #stats.collectionCount# <br/>
collection keys: #stats.collectionKeys# <br/>
entity count: #stats.entityCount# <br/>
entity keys: #stats.entityKeys#
</cfoutput>// Check if by this point we have a dirty session, then flush it
if( ormService.isSessionDirty() ){
ORMFlush();
}ormService.deleteWhere(entityName="User", isActive=true, age=10);
ormService.deleteWhere(entityName="Account", id="40");
ormService.deleteWhere(entityName="Book", isReleased=true, author="Luis Majano");var persistedTable = ormService.getTableName( "Category" );var properties = ormService.getPropertyNames("User");c.timeout( 5000 )
c.readOnly(true)
c.firstResult(20).maxResults(50).fetchSize(10).cacheRegsion('my.awesome.region')
c.cache(true,'my.region')
c.order('lastName','desc',true);function checkSomething( any User ){
// check if User is already in session
if( NOT ormService.sessionContains( arguments.User ) ){
// Not in hibernate session, so merge it in.
ormService.merge( arguments.User );
}
}// Get the count of instances for all books
ormService.count("Book");
// Get the count for users with age above 40 and named Bob
ormService.count("User","age > 40 AND name='Bob'");
// Get the count for users with passed in positional parameters
ormService.count("User","age > ? AND name=?",[40,'Bob']);
// Get the count for users with passed in named parameters
ormService.count("Post","title like :title and year = :year",{title="coldbox",year="2007"});var account = ormService.get("Account",1);
var account = ormService.get("Account",4);
var newAccount = ormService.get("Account",0);var users = ORMService.newCriteria(entityName="User",useQueryCaching=true)
.gt("age", javaCast("int", 30) )
.isTrue("isActive")
.list(max=30,offset=10,sortOrder="lname");// My First Post
ormService.findIt("from Post as p where p.author='Luis Majano'");
// With positional parameters
ormService.findIt("from Post as p where p.author=?", ["Luis Majano"]);
// with a named parameter (since 0.5)
ormService.findIt("from Post as p where p.author=:author and p.isActive=:active", { author="Luis Majano",active=true} );
// By Example
book = ormService.new(entityName="Book", author="Luis Majano");
ormService.findIt( example=book );// just delete
count = ormService.deleteByID("User",1);
// delete and flush
count = ormService.deleteByID("User",4,true);
// Delete several records, or at least try
count = ormService.deleteByID("User",[1,2,3,4]);if( ormService.exists("Account",123) ){
// do something
} component extends="cborm.models.EventHandler"{
}var user = ormService.new("User");
populateModel(user);
ormService.save(user);
// Save with immediate flush
var user = ormService.new(entityName="User", lastName="Majano");
ormService.save(entity=user, flush=true);// Inject
inject name="ORMService" inject="BaseORMService@cborm";
// Retrieve
wireBox.getInstance( "BaseORMService@cborm" );
getModel( "BaseORMService@cborm" );component{
inject name="ORMService" inject="entityService";
function saveUser( event, rc, prc ){
// retrieve and populate a new user object
var user = populateModel( ORMService.new( "User" ) );
// save the entity using hibernate transactions
ORMService.save( user );
setNextEvent( "user.list" );
}
function list( event, rc, prc ){
//get a listing of all users with paging
prc.users = ORMService.list(
entityName= "User",
sortOrder = "fname",
offset = event.getValue("startrow",1),
max = 20
);
event.setView( "user/list" );
}
}
function index( event, rc, prc ){
prc.data = ORMService.findAll( "Permission" );
}
var c = newCriteria("User");
var users = c.like("name","lui%")
.createCriteria("admins")
.like("name","fra%")
.list();var c = newCriteria("User");
var users = c.like("name","lui%")
.withAdmins().like("name","fra%")
.list();var c = newCriteria("User");
var users = c.like("name","lui%")
.createAlias("admins","a")
.eq("a.name","Vero")
.list();c = newCriteria();
c.add(
c.createSubcriteria( ‘Car’, ‘CarSub’ )
// result of subquery will be CarIDs
.withProjections( property=’CarID’ )
.isEq( ‘Make’, ‘Ford’ )
.propertyIn( ‘CarID’ )
).list();var c = newCriteria();
oReviews = c.withProjections(
property="status,ID,rating,isComplete"
);
c.isTrue( "this.isComplete" );
c.gt( "this.rating", JavaCast( "float", 0 ) );
oReviews = c.resultTransformer( c.ALIAS_TO_ENTITY_MAP ).list();// Enable ORM
this.ormEnabled = true;
// ORM Datasource
this.datasource = "contacts";
// ORM configuration settings
this.ormSettings = {
// Location of your entities, default is your convention model folder
cfclocation = ["models"],
// Choose if you want ORM to create the database for you or not?
dbcreate = "none",
// Log SQL or not
logSQL = true,
// Don't flush at end of requests, let Active Entity manage it for you
flushAtRequestEnd = false,
// Don't manage session, let Active Entity manage it for you
autoManageSession = false,
// Active ORM events
eventHandling = true,
// Use the ColdBox WireBox Handler for events
eventHandler = "cborm.models.EventHandler"
};var user = ormService.populateFromQuery( ormService.new("User"), list("User",{id=4}) );var user = ormService.populateFromJSON( ormService.new("User"), jsonString );posts = ormService.findAllWhere(entityName="Post", criteria={author="Luis Majano"});
users = ormService.findAllWhere(entityName="User", criteria={isActive=true});
artists = ormService.findAllWhere(entityName="Artist", criteria={isActive=true, artist="Monet"});component persistent="true" table="your_table" extends="coldbox.system.orm.hibernate.ActiveEntity"{
function init(){
setCreatedDate( now() );
super.init(useQueryCaching=true);
return this;
}
}createCriteria(required string associationName,numeric joinType)
createAlias(required string associationName, required string alias, numeric joinType)
with{AssociationName}( joinType )component extends="cborm.models.BaseORMService"{
public UserService function init(){
super.init( useQueryCaching=true, eventHandling=false );
return this;
}
}// Base ORM Service
c = newCriteria( 'entityName' );
// Virtual
c = newCriteria();
// Examples
var results = c.like("firstName","Lui%")
.maxResults( 50 )
.order("balance","desc")
.and(
c.restrictions.between( "balance", 200, 300),
c.restrictions.eq("department", "development")
)
.list();
// with pagination
var results = c.like("firstName","Lui%")
.order("balance","desc")
.and(
c.restrictions.between( "balance", 200, 300),
c.restrictions.eq("department", "development")
)
.list(max=50,offset=20);
// more complex
var results = c.in("name","luis,fred,joe")
.OR( c.restrictions.isNull("age"), c.restrictions.eq("age",20) )
.list(); component extends="cborm.models.VirtualEntityService" singleton{
// DI
property name="mailService" inject="coldbox:plugin:MailService";
property name="renderer" inject="coldbox:plugin:Renderer";
property name="settingService" inject="id:settingService@cb";
property name="CBHelper" inject="id:CBHelper@cb";
property name="log" inject="logbox:logger:{this}";
/**
* Constructor
*/
public CommentService function init(){
super.init(entityName="cbComment",useQueryCaching="true");
return this;
}
/**
* Get the total number of approved comments in the system
*/
numeric function getApprovedCommentCount(){
var args = { "isApproved" = true };
return countWhere(argumentCollection=args);
}
/**
* Get the total number of unapproved comments in the system
*/
numeric function getUnApprovedCommentCount(){
var args = { "isApproved" = false };
return countWhere(argumentCollection=args);
}
/**
* Comment listing for UI of approved comments, returns struct of results=[comments,count]
* @contentID.hint The content ID to filter on
* @contentType.hint The content type discriminator to filter on
* @max.hint The maximum number of records to return, 0 means all
* @offset.hint The offset in the paging, 0 means 0
* @sortOrder.hint Sort the comments asc or desc, by default it is desc
*/
function findApprovedComments(contentID,contentType,max=0,offset=0,sortOrder="desc"){
var results = {};
var c = newCriteria();
// only approved comments
c.isTrue("isApproved");
// By Content?
if( structKeyExists(arguments,"contentID") AND len(arguments.contentID) ){
c.eq("relatedContent.contentID",javaCast("int", arguments.contentID));
}
// By Content Type Discriminator: class is a special hibernate deal
if( structKeyExists(arguments,"contentType") AND len(arguments.contentType) ){
c.createCriteria("relatedContent")
.isEq("class", arguments.contentType);
}
// run criteria query and projections count
results.count = c.count();
results.comments = c.list(offset=arguments.offset,max=arguments.max,sortOrder="createdDate #arguments.sortOrder#",asQuery=false);
return results;
}
}/**
* Service to handle author operations.
*/
component extends="cborm.models.VirtualEntityService" accessors="true" singleton{
// User hashing type
property name="hashType";
AuthorService function init(){
// init it via virtual service layer
super.init(entityName="bbAuthor", useQueryCaching=true);
setHashType( "SHA-256" );
return this;
}
function search(criteria){
var params = {criteria="%#arguments.criteria#%"};
var r = executeQuery(query="from bbAuthor where firstName like :criteria OR lastName like :criteria OR email like :criteria",params=params,asQuery=false);
return r;
}
function saveAuthor(author,passwordChange=false){
// hash password if new author
if( !arguments.author.isLoaded() OR arguments.passwordChange ){
arguments.author.setPassword( hash(arguments.author.getPassword(), getHashType()) );
}
// save the author
save( author );
}
boolean function usernameFound(required username){
var args = {"username" = arguments.username};
return ( countWhere(argumentCollection=args) GT 0 );
}
}// find all blog posts
ormService.findAll("Post");
// with a positional parameters
ormService.findAll("from Post as p where p.author=?",['Luis Majano']);
// 10 posts from Luis Majano staring from 5th post ordered by release date
ormService.findAll("from Post as p where p.author=? order by p.releaseDate",['Luis majano'],offset=5,max=10);
// Using paging params
var query = "from Post as p where p.author='Luis Majano' order by p.releaseDate"
// first 20 posts
ormService.findAll(query=query,max=20)
// 20 posts starting from my 15th entry
ormService.findAll(query=query,max=20,offset=15);
// examples with named parameters
ormService.findAll("from Post as p where p.author=:author", {author='Luis Majano'})
ormService.findAll("from Post as p where p.author=:author", {author='Luis Majano'}, max=20, offset=5);
// query by example
user = ormService.new(entityName="User",firstName="Luis");
ormService.findAll( example=user );// Get all user entities
users = ORMService.getAll(entityName="User", sortOrder="email desc");
// Get all the following users by id's
users = ORMService.getAll("User","1,2,3");
// Get all the following users by id's as array
users = ORMService.getAll("User",[1,2,3,4,5]);var user = ormService.new("User");
populateModel(user);
var user2 = ormService.new("User");
populateModel(user);
ormService.saveAll( [user1,user2] );users = ormService.list(entityName="User",max=20,offset=10,asQuery=false);
users = ormService.list(entityName="Art",timeout=10);
users = ormService.list("User",{isActive=false},"lastName, firstName");
users = ormService.list("Comment",{postID=rc.postID},"createdDate desc");// Inject
inject name="ORMService" inject="BaseORMService@cborm";
// Retrieve
wireBox.getInstance( "BaseORMService@cborm" );
getModel( "BaseORMService@cborm" );component{
inject name="ORMService" inject="entityService";
function saveUser( event, rc, prc ){
// retrieve and populate a new user object
var user = populateModel( ORMService.new( "User" ) );
// save the entity using hibernate transactions
ORMService.save( user );
setNextEvent( "user.list" );
}
function list( event, rc, prc ){
//get a listing of all users with paging
prc.users = ORMService.list(
entityName= "User",
sortOrder = "fname",
offset = event.getValue("startrow",1),
max = 20
);
event.setView( "user/list" );
}
}
function index( event, rc, prc ){
prc.data = ORMService.findAll( "Permission" );
}component{
// Concrete ORM service layer
property name="authorService" inject="security.AuthorService";
// Aliased
property name="authorService" inject="id:AuthorService";
function index( event, rc, prc ){
// Get all authors or search
if( len(event.getValue( "searchAuthor", "" )) ){
prc.authors = authorService.search( rc.searchAuthor );
prc.authorCount = arrayLen( prc.authors );
} else {
prc.authors = authorService.list( sortOrder="lastName desc", asQuery=false );
prc.authorCount = authorService.count();
}
// View
event.setView("authors/index");
}
}
var c = newCriteria("User");
var users = c.like("name","lui%")
.createCriteria("admins")
.like("name","fra%")
.list();var c = newCriteria("User");
var users = c.like("name","lui%")
.withAdmins().like("name","fra%")
.list();var c = newCriteria("User");
var users = c.like("name","lui%")
.createAlias("admins","a")
.eq("a.name","Vero")
.list();component{
// Virtual service layer based on the User entity
property name="userService" inject="entityService:User";
}c = newCriteria();
c.withProjections(
detachedSQLProjection=
c.createSubcriteria( "Car", "Car2" )
.withProjections( count="Car2.Year" )
.isLT( "Year", javaCast( "int", 2006 ) )
.isEQ( "CarID", "{alias}.CarID" ),
groupProperty="Make"
).list();var user = ormService.populateFromXML( ormService.new("User"), xml, "User");// simple query
ormService.executeQuery( "select distinct a.accountID from Account a" );
// using with list of parameters
ormService.executeQuery( "select distinct e.employeeID from Employee e where e.department = ? and e.created > ?", ['IS','01/01/2010'] );
// same query but with paging
ormService.executeQuery( "select distinct e.employeeID from Employee e where e.department = ? and e.created > ?", ['IS','01/01/2010'],1,30);
// same query but with named params and paging
ormService.executeQuery( "select distinct e.employeeID from Employee e where e.department = :dep and e.created > :created", {dep='Accounting',created='01/01/2010'],10,20);
// GET FUNKY!!// The following is handler code which has been wired with a virtual entity service
property name="authorService" inject="entityService:Author";
function showAuthors(event){
var rc = event.getCollection();
// Get the hibernate restrictions proxy object
var restrictions = authorService.getRestrictions();
// build criteria
var criteria = [];
// Apply a "greater than" constraint to the named property
ArrayAppend(criteria, restrictions.ge("firstName","M"));
// Get the criteria query first
prc.example1 = authorService.criteriaQuery(criteria=criteria, offset=(prc.boundaries.STARTROW-1), max=getSetting("PagingMaxRows"), sortOrder="firstName ASC");
// get the total records found via projections
prc.foundcount = authorService.criteriaCount(criteria=criteria);
}var name = ORMService.getEntityGivenName( entity );createCriteria(required string associationName,numeric joinType)
createAlias(required string associationName, required string alias, numeric joinType)
with{AssociationName}( joinType )// Get a reference to a criteria builder from an ORM base or virtual service
c = ormservice.newCriteria();
// detached criteria builder
c.createSubcriteria( entityName='Car', alias='CarSub' );c.newCriteria( entityName=‘Car’ );
// all-in-one criteria subquery
c.add(
c.createSubcriteria( ‘Car’, ‘CarSub’ )
.withProjections( property=’CarID’ )
.isEq( ‘Make’, ‘Ford’ )
.propertyIn( ‘CarID’ )
).list();
// detached criteria builder separately, then add as criteria
var dc = c.createSubcriteria( ‘Car’, ‘CarSub’ )
.withProjections( property=’CarID’ )
.isEq( ‘Make’, ‘Ford’ );
// add criteria subquery
c.add( dc.propertyIn( ‘CarID’ ) );// criteria builder
c = newCriteria();
// detached criteria builder
c.createSubcriteria( 'Car', 'CarSub' );var user = storage.getVar("UserSession");
ormService.refresh( user );
var users = [user1,user2,user3];
ormService.refresh( users );var user = ormService.populate( ormService.new("User"), data );
// populate with includes only
var user = ormService.populate( ormService.new("User"), data, "fname,lname,email" );
//populate with excludes
var user = ormService.populate(target=ormService.new("User"),memento=data,exclude="id,setup,total" );
// populate with null values when value is empty string
var user = ormService.populate(target=ormService.new("User"),memento=data,nullEmptyInclude="lastName,dateOfBirth" );
// populate many-to-one relationship
var data = {
firstName = "Luis",
role = 1 // "role" is the name of the many-to-one relational property, and one is the key value
};
var user = ormService.populate( target=ormService.new("User"), memento=data, composeRelationships=true );
// the role relationship will be composed, and the value will be set to the appropriate instance of the Role model
// populate one-to-many relationship
var data = {
firstName = "Luis",
favColors = "1,2,3" ( or [1,2,3] ) // favColors is the name of the one-to-many relational property, and 1, 2 and 3 are key values of favColor models
};
var user = ormService.populate( target=ormService.new("User"), memento=data, composeRelationships=true );
// the favColors property will be set to an array of favColor entities
// only compose some relationships
var data = {
firstName = "Luis",
role = 1,
favColors = [ 1, 3, 19 ]
};
var user = ormService.populate( target=ormService.new("User"), memento=data, composeRelationships=true, exclude="favColors" );
// in this example, "role" will be composed, but "favColors" will be excluded// evict queries that are in the default hibernate cache
ormService.evictQueries();
// evict queries for this service
ormService.evictQueries( ormService.getQueryCacheRegion() );
// evict queries for my artists
ormService.evictQueries( "MyArtits" );

/**
* Validate the ActiveEntity with the coded constraints -> this.constraints, or passed in shared or implicit constraints
* The entity must have been populated with data before the validation
* @fields.hint One or more fields to validate on, by default it validates all fields in the constraints. This can be a simple list or an array.
* @constraints.hint An optional shared constraints name or an actual structure of constraints to validate on.
* @locale.hint An optional locale to use for i18n messages
* @excludeFields.hint An optional list of fields to exclude from the validation.
*/
boolean function isValid(string fields="*", any constraints="", string locale="", string excludeFields="");
/**
* Get the validation results object. This will be an empty validation object if isValid() has not being called yet.
*/
coldbox.system.validation.result.IValidationResult function getValidationResults();Ex: avg="balance", avg="balance:myBalance", avg="balance, total", avg=["balance","total"]// Using native approach for one projection only
var results = c.like("firstName","Lui%")
.and(
c.restrictions.between( "balance", 200, 300),
c.restrictions.eq("department", "development")
)
.setProjection( c.projections.rowCount() )
.get();
// Using the withProjections() method, which enables you to do more than 1 projection
var results = c.like("firstName","Lui%")
.and(
c.restrictions.between( "balance", 200, 300),
c.restrictions.eq("department", "development")
)
.withProjections(rowCount=1)
.get();
var results = c.like("firstName","Lui%")
.and(
c.restrictions.between( "balance", 200, 5000),
c.restrictions.eq("department", "development")
)
.withProjections(avg="balance,total",max="total:maxTotal")
.gt("maxTotal",500)
.list();import coldbox.system.orm.hibernate.*;
component persistent="true" extends="ActiveEntity"{
// Properties
property name="firstName";
property name="lastName";
property name="email";
property name="username";
property name="password";
// Validation Constraints
this.constraints = {
"firstName" = {required=true},
"lastName" = {required=true},
"email" = {required=true,type="email"},
"username" = {required=true, size="5..10"},
"password" = {required=true, size="5..10"}
};
}component{
property name="Messagebox" inject="id:messagebox@cbmessagebox";
function index(event,rc,prc){
prc.users = entityNew("User").list(sortOrder="lastName asc");
event.setView("users/list");
}
function save(event,rc,prc){
event.paramValue("id","");
var user = populateModel( entityNew("User").get( rc.id ) );
if( user.isValid() {
user.save();
flash.put("notice","User Saved!");
setNextEvent("users.index");
}
else{
Messagebox.error(messageArray=user.getValidationResults().getAllErrors());
editor(event,rc,prc);
}
}
function editor(event,rc,prc){
event.paramValue("id","");
prc.user = entityNew("User").get( rc.id );
event.setView("users/editor");
}
function delete(event,rc,prc){
event.paramValue("id","");
entityNew("User").deleteById( rc.id );
flash.put("notice","User Removed!");
setNextEvent("users.index");
}
}// Assuming the following code has a dependency on a virtual entity service:
property name="authorService" inject="entityService:Author";
var restrictions = authorService.getRestrictions();
var criteria = [];
ArrayAppend(criteria, Restrictions.eq("firstName","Emily"));
ArrayAppend(criteria, Restrictions.eq("firstName","Paul"));
ArrayAppend(criteria, Restrictions.eq("firstName","Amy"));
example1 = authorService.criteriaQuery([Restrictions.disjunction(criteria)]);
var disjunction = ArrayNew(1);
ArrayAppend(disjunction, Restrictions.eq("firstName","Emily"));
ArrayAppend(disjunction, Restrictions.eq("firstName","Paul"));
ArrayAppend(disjunction, Restrictions.eq("firstName","Amy"));
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.gt("id",JavaCast("int",7)));
ArrayAppend(criteria, Restrictions.disjunction(disjunction));
example2 = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.eq("firstName","Michael"));
prc.example1 = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.ne("firstName","Michael"));
prc.example2 = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.in("firstName",["Ian","Emily","Paul"]));
prc.example3a = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.in("id",JavaCast("java.lang.Integer[]",[2,5,9])));
prc.example3b = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.like("lastName","M%"));
prc.example4 = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.ilike("lastName","s%"));
prc.example5 = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.isEmpty("books"));
prc.example6 = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.isNotEmpty("books"));
prc.example7 = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.isNull("bio"));
prc.example8 = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.isNotNull("bio"));
prc.example9 = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.between("lastName","A","M"));
prc.example10a = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.between("id",JavaCast("int",3),JavaCast("int",7)));
prc.example10b = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.gt("id",JavaCast("int",8)));
prc.example11 = authorService.criteriaQuery(criteria);
var criteria = ArrayNew(1);
ArrayAppend(criteria, Restrictions.ge("id",JavaCast("int",13)));
prc.example12 = authorService.criteriaQuery(criteria);



// wrong way...will fail because the subquery method “propertyIn()” is not what is added
c.add(
c.createSubcriteria( ‘Car’, ‘CarSub’ )
.withProjections( property=’CarID’ )
.propertyIn( ‘CarID’ )
.isEq( ‘Make’, ‘Ford’ )
).list();
// right way...since propertyIn() is last in the chain, it’s value will be what is ultimately added as a criteria
c.add(
c.createSubcriteria( ‘Car’, ‘CarSub’ )
.withProjections( property=’CarID’ )
.isEq( ‘Make’, ‘Ford’ )
.propertyIn( ‘CarID’ )
).list();
// right way--split up
dc = c.createSubcriteria( ‘Car’, ‘CarSub’ )
.withProjections( property=’CarID’ )
.isEq( ‘Make’, ‘Ford’ );
c.add( dc.propertyIn( ‘CarID’ ) ).list();
c.isEq("userID", JavaCast( "int", 3 ));c.add( c.restrictions.eq("name","luis") )c.isEq("userID", JavaCast( "int", 3 ));c.add( c.restrictions.eq("name","luis") )