Basic Crud - Services
A basic example of CRUD (Create-Read-Update-Delete) using ColdBox ORM services.
Let's do a basic example of CRUD (Create-Read-Update-Delete). We will generate a ColdBox App, connect it to a database and leverage a virtual service layer for a nice quick CRUD App.
The source code for this full example can be found in Github: https://github.com/coldbox-samples/cborm-crud-demo or in ForgeBox: https://forgebox.io/view/cborm-crud-demo
ColdBox App
Let's start by creating a ColdBox app and preparing it for usage with ORM:
# Create folder
mkdir myapp --cd
# Scaffold App
coldbox create app
# Install cborm, dotenv, and cfconfig so we can get the CFML engine talking to the DB fast.
install cborm,commandbox-dotenv,commandbox-cfconfig
# Update the .env file
cp .env.example .envSetup Environment
Season the environment file (.env) with your database credentials and make sure that database exists:
# ColdBox Environment
APPNAME=ColdBox
ENVIRONMENT=development
# Database Information
DB_CONNECTIONSTRING=jdbc:mysql://127.0.0.1:3306/cborm?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useLegacyDatetimeCode=true
DB_CLASS=com.mysql.jdbc.Driver
DB_DRIVER=MySQL
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cborm
DB_USER=root
DB_PASSWORD=cborm
# S3 Information
S3_ACCESS_KEY=
S3_SECRET_KEY=
S3_REGION=us-east-1
S3_DOMAIN=amazonaws.comSetup ORM
Now open the Application.cfc and let's configure the ORM by adding the following in the pseudo constructor and adding two lines of code to the request start so when we reinit the APP we can also reinit the ORM.
To change the datasource name to something you like then update it here and in the .cfconfig.json file. Once done, issue a server restart and enjoy your new datasource name.
Start Server
Let's start a server and start enjoying the fruits of our labor:
If you get a Could not instantiate connection provider: org.lucee.extension.orm.hibernate.jdbc.ConnectionProviderImpl error on startup here. It means that you hit the stupid Lucee bug where on first server start the ORM is not fully deployed. Just issue a server restart to resolve this.
Create Entity - Person.cfc
Let's start by creating a Person object with a few properties, let's use CommandBox for this and our super duper coldbox create orm-entity command:
This will generate the models/Person.cfc as an ActiveEntity object and even create the unit test for it.
Setup for BDD
Since we love to promote tests at Ortus, let's configure our test harness for ORM testing. Open the /tests/Application.cfc and add the following code to setup the ORM and some functions for helping us test.
Now that we have prepared the test harness for ORM testing, let's test out our Person with a simple unit test. We don't over test here because our integration test will be more pragmatic and cover our use cases:
Basic CRUD
We will now generate a handler and do CRUD actions for this Person:
This creates the handlers/persons.cfc with the CRUD actions and a nice index action we will use to present all persons just for fun!
Please note that this also generates the integrations tests as well under /tests/specs/integration/personsTest.cfc
Inject Service
Open the handlers/persons.cfc and in the pseudo-constructor let's inject a virtual ORM service layer based on the Person entity:
The cborm module gives you the entityService:{entityName} DSL which allows you to inject virtual service layers according to entityName. With our code above we will have a personService in our variables scope injected for us.
Create
We will get an instance of a Person, populate it with data and save it. We will then return it as a json memento. The new() method will allow you to pass a struct of properties and/or relationships to populate the new Person instance with. Then just call the save() operation on the returned object.
You might be asking yourself: Where does this magic getMemento() method come from? Well, it comes from the mementifier module which inspects ORM entities and injects them with this function to allow you to produce raw state from entities. (Please see: https://forgebox.io/view/mementifier)
Read
We will get an instance according to ID and show it's memento in json. There are many ways in the ORM service and Active Entity to get objects by criteria,
In this example, we use the get() method which retrieves a single entity by identifier. Also note the default value of 0 used as well. This means that if the incoming id is null then pass a 0. The ORM services will detect the 0 and by default give you a new Person object, the call will not fail. If you want your call to fail so you can show a nice exception for invalid identifiers you can use getOrFail() instead.
Update
Now let's retrieve an entity by Id, update it and save it again!
Delete
Now let's delete an incoming entity identifier
Note that you have two choices when deleting by identifier:
Get the entity by the ID and then send it to be deleted
Use the
deleteById()and pass in the identifier
The latter allows you to bypass any entity loading, and do a pure HQL delete of the entity via it's identifier. The first option is more resource intensive as it has to do a 1+ SQL calls to load the entity and then a final SQL call to delete it.
List All
For extra credit, we will get all instances of Person and render their memento's
That's it! We are now rolling with basic CRUD cborm style!
BDD Tests
Here are the full completed BDD tests as well
Last updated
Was this helpful?