CF Camp 2018: Madness in Munich Part Four- ORM-Love it or Hate it?

CF Camp 2018: Madness in Munich Part Four- ORM-Love it or Hate it?

Hello and welcome back once again to our series, CF Camp 2018: Madness in Munich! Throughout the series, we have been discussing hot ticket items that will be discussed at this year’s upcoming CF Camp, the only CF conference in Europe. Today, we will be talking about ORM–or Object Relational Mapping. Often dubbed as the “Vietnam of Computer Science” due to its seemingly endless complexities, ORM can be a topic of debate among CF’ers. ORM is not devoid of benefit, however. There are some features that still make ORM relevant and useful. This article is inspired by Wil de Bruin’s upcoming Munich session titled ORM Love and Hate. There, he will discuss ORM as it has pertained to ColdFusion throughout the years. He will also demonstrate ways to make your ORM easier through the use of the ColdBox ORM Module.

“For ColdFusion developers, what new ColdFusion technology or library you’re going to have a chance to dip into, are you going to learn? I think that will help make ColdFusion better, make ColdFusion more alive and it will make the developers doing ColdFusion more proud of what they do. When you talk to another developer that’s not a ColdFusion developer, you could more proudly talk to them about the modern practices that you’re doing and not have to be ashamed of the legacy ColdFusion app that you managed that was written like it’s 1999, right?”

-Brad Wood, Software Architect and Platform Evangelist Ortus Solutions

From CF Alive episode, “028 Design Patterns for amazing app architecture (16 patterns), with Brad Wood

Like any other topic, you must first have a firm grasp on what it is before you can make any educated assessment on it. So, the big question is…

What is ORM?

ORM means Object Relational Mapping. ORM as defined by wikipedia is a programming technique for converting data between incompatible type systems using object-oriented programming languages. This creates, in effect, a “virtual object database” that can be used from within the programming language.

Many of today’s programming languages are object-oriented, including ColdFusion. However, all of the most widely used of today’s databases are considered relational rather than object databases. Eg SQL Server, MySQL and Oracle.This creates a need for there to be a mechanism to translate between the two.

Enter ORM.

The explanation stated above is probably also one of the largest benefits for CIOs. As CIO, your business or team may need access to many of these external databases or an internally created relational database. Without the use of ORM, access to such information would be complicated at best.

But… ORM can become extremely complicated itself. Yet, it is a necessary evil for many CIOs and CF developers out there. Yet, Luis Majano–creator of ColdBox, CommandBox, ContentBox, and President of Ortus Solutions–believes firmly in the power of ORM while accepting some faults it may have.

“I mean we can honestly attest to at least increasing from 30 to 40 percent our productivity due to using ORM. It really explodes in productivity. But it is a tool. It’s not meant to be used for everything, and that’s why sometimes people fall from the wagon because they feel that they have to use it for everything. And that’s when they fail. The other failure is the defaults. There is many knobs and turns in performance and a lot of people say ‘Oh the ORM is just horrible at performance.’ The reality is that we run it on all our systems and our average JDBC times are in the 30 millisecond range. So it can be extremely fast and distributive.”

So what are some clear benefits to using ORM?

  • They offer an object oriented model of databases.
  • Developers of Object Oriented Languages do not have to shift paradigms when entering a database.
  • Most mature ORMs come equipped with an SQL query builder.
  • They help manage the database creation process.
  • They help manage database schema changes.
  • Database Vendor Independence
  • Caching
  • Concurrency
  • Performance Optimization

What about ORM constraints?

Unfortunately, no system is perfect, and for ORM that rings true. There are some limitations that ORM does maintain such as:

  • Only Value Objects and Entities may be persisted in them.
  • There is a set standard to establishing outward references from Value Objects and Entities when thawed from the data store.
  • Data structures that were previously unlimited in size while in memory must be given a maximum size value for performance reasons. (i.e. varchar(255) instead of longtext)
  • Objects modelling machine resources cannot be persisted. This is because they cannot be synchronized with the machine that is freeing them.
  • A way must be established to build an object from state other than its public API.

ORM Patterns

ORM comes in multiple patterns with two being the most common.

  1. Active Record
  2. Each table generated is now represented as a class. Each row of those tables is then translated to the object of the corresponding class. At this time, the objects know how to persist themselves in a database.
  3. Data Access Object
  4. In this pattern, database access is delegated to dedicated Data Access Objects. Data Access Objects (or DAOs) can persist each object and know how to construct objects from the database.

As CIO, you must weigh out the option of using ORM or not. ORM can be an exceptional tool when used properly. It can also prove to be a necessary evil for those unfamiliar with its processes. Either way, a general understanding of ORM should be established prior to any use. For more information on the basis of ORM, check out Tom van den Broek bachelor thesis, Object Relational Mappings: First Step to a Formal Approach.

From a purely operational standpoint, ORM allows you to manipulate objects and save them to a database. In ColdFusion, Adobe uses the industry standard Hibernate for all of its ORM needs. This can greatly simplify your CRUD (Create-Read-Update-Delete) processes and produce more object-oriented code.

Along with Hibernate, Ortus Solutions provides the ColdBox ORM module. This module greatly extends the capabilities of Hibernate and allows you to use ORM much more easily and efficiently. The ColdBox ORM module is equipped with many features such as:

  • Virtual Service Layers
  • Active Record Patterns
  • Criteria and Detached Criteria Queries
  • Entity Compositions
  • Populations
  • And Much More!

According to Ortus Solutions, the concept behind the ColdBox ORM Module is as follows:

“The idea behind this support class is to provide a very good base or parent service layer that can interact with ColdFusion ORM via hibernate and entities inspired by Spring’s Hibernate Template support. This means that you don’t need to create a service layer CFC in order to work with ORM entities.”

This makes the ColdBox ORM Module a critical application to use when handling ORM inside of your ColdFusion.

However, for those not using the ColdBox module, let’s take a look at starting your ORM with ColdFusion based Hibernate.

“Having done development in other languages, you just don’t have the same convenience of all of those built in methods and then you add ColdBox on top of it and you’ve got all these other conventions and super tight methods you can leverage. With other languages, you find yourself reinventing the wheel over and over and over again to solve problems that were already solved in CFML many many years ago.

For me it’s let’s find a language that gives me the best toolkit to start out with, the biggest tool box to work with, and if I have all of those tools and I have them readily available and conveniently assembled, then it makes it so much easier for me to quickly build and deploy powerful and bug free applications. So that’s why I’m excited about CFML and I really continue to be because I think a lot of times the CFML development community can be it’s own worst enemy, because we don’t’ spend enough time honing and looking at how we’ve done it this way for so many years, how can we do things differently.”- Jon Clausen, President, Silo Web

From CF Alive episode, “011 Portable CFML with Cloud deployments, Microservices and REST with Jon Clausen

Config

Application.cfc

Two settings must be in order to make an application.cfc file use ORM.

  1. A data source
  2. ORM Enabled set to TRUE

Although ORM will work with any modern database, the default datasource and database for ColdFusion are cfartgallery and Derby DB respectively.

More settings for ORM can be found under in structure called –that’s right, you guessed it.– ormsettings.

LearnCFinaWeek.com provides a great example when starting with ColdFusion ORM.

component { this.datasource = "cfartgallery"; this.ormEnabled = true; this.ormSettings = { logsql : true }; this.invokeImplicitAccessor = true;

In this example, the logsql has been set to true. This allows the SQL created by Hibernate to display the ColdFusion debugging information. Use cfclocation to determine where the persistent cfc’s will be placed. When this is done, dbcreate will automatically save changes made to both the database and model.

Entities

An entity is class that is specifically marked to a single database table. This follows the same principle as the Active Record pattern described above in the previous section for CIOs. Properties can be mapped to each column of the table. Each property will have getters and setters, both of which may be automatically generated. These can also be overwritten.

Relationships

Relationships in ORM are very similar to foreign-key relations between two tables except that they are now objects. These relationships normally fall under one of three relationship types:

  1. One to One
  2. One to Many
  3. Many to Many

It is normally recommended to use multiple “one to many” relationships vice a “many to many” in most circumstances. This helps to avoid later confusion. ColdFusion will automatically add functions to objects for controlling relationships.

Retrieving Data

When retrieving data, you will use two primary functions.

  1. entityLoad
  2. ormExecuteQuery

For more complicated data retrievals, you can use HQL. This is Hibernate’s Query Language. It is very similar to SQL in its design. However, in HQL ormExecuteQuery will return results just as entityLoad would.

You also have the ability to serialize via JSON. The serializeJSON function can serialize all your entities for you into JavaScript Object Notation.

Working with Data

Adding Records

It is simple to add a record with ORM. Use the entityNew function as follows:

  • Use entityNew function.
  • First Argument- entity name
  • Second Argument (optional)- a structure of data
  • Use entitySave function

Check out this example from Learn CF in a Week, as they create a relationship between art and artist.

transaction { art = entityNew( "art", { name : "Painting of TV", price : 200, isSold : false } ); entitySave( art ); artist = entityNew( "artist", { firstname : "John", lastname : "Doe" } ); artist.addArt( art ); entitySave( artist ); }

Updating and Deleting Records

Updating and deleting records is relatively easy as well. The process for updating records is as follows:

  • Retrieve the object by using a different signature with the third argument as a boolean which need to be set as true.
  • Change values with the implicit setters.
  • All values changed will be saved upon completion of the transaction.
  • Changes may be rolled back by using the transitionRollback() function.

To delete a record, just retrieve the single record and use the entityDelete function.

Key Tips and Tricks to ColdFusion ORM

Dumping Objects

Sometimes when using the function writedump, CF will try to display relationship information. This can often lead to the display of way more intended information. To prevent this, just provide some additional attributes.

Null Values

Sometimes, ColdFusion cannot retrieve an entity when called upon. When this happens, the assigned value will be null.

For example, if the ID for a particular entity is very high, an error may be produced. Instead of erroring, the art variable is set to null. Using the isNull variable can test for this.

ormReload

This function is exceptionally useful. Whenever any changes are made to entity configuration, you must use the ormReload function for any changes to take effect. This is very similar to reloading a UI when making interface changes.

ORM is one of the facets of computer science that can really get under your skin. Yet, we can’t just get rid of it. It is exceptionally useful when applied properly. Perhaps, we should all take the time to understand exactly what ORM does for us. It helps our CF stay alive and more vibrant, so maybe we should show our appreciation a little more for this poor misunderstood creature of programming.

About the Speaker:

Wil graduated in Environmental Sciences and started off his career as a research microbiologist. It took him almost 10 years before he continued fulltime as an IT specialist. In 1994 he founded Site4U BV, at that time a company specializing in software development and web design. One of his first application was to find Dutch ISPs at local area rates written in PHP/Mini SQL, but soon he discovered this kind of interactive websites could easier be built with DBML using Cold Fusion by Allaire.

And to continue learning how to make your ColdFusion apps more modern and alive, I encourage you to download our free ColdFusion Alive Best Practices Checklist.

Because… perhaps you are responsible for a mission-critical or revenue-generating CF application that you don’t trust 100%, where implementing new features is a painful ad-hoc process with slow turnaround even for simple requests.

What if you have no contingency plan for a sudden developer departure or a server outage? Perhaps every time a new freelancer works on your site, something breaks. Or your application availability, security, and reliability are poor.

And if you are depending on ColdFusion for your job, then you can’t afford to let your CF development methods die on the vine.

You’re making a high-stakes bet that everything is going to be OK using the same old app creation ways in that one language — forever.

All it would take is for your fellow CF developer to quit or for your CIO to decide to leave the (falsely) perceived sinking ship of CFML and you could lose everything — your project, your hard-won CF skills, and possibly even your job.

Luckily, there are a number of simple, logical steps you can take now to protect yourself from these obvious risks.

No Brainer ColdFusion Best Practices to Ensure You Thrive No Matter What Happens Next

ColdFusion Alive Best Practices Checklist

Modern ColdFusion development best practices that reduce stress, inefficiency, project lifecycle costs while simultaneously increasing project velocity and innovation.

Easily create a consistent server architecture across development, testing, and production

A modern test environment to prevent bugs from spreading

√ Automated continuous integration tools that work well with CF

A portable development environment baked into your codebase… for free!

Learn about these and many more strategies in our free ColdFusion Alive Best Practices Checklist.



Originally published at teratech.com on October 30, 2018.

要查看或添加评论,请登录

Michaela Light的更多文章

社区洞察

其他会员也浏览了