views:

101

answers:

3

I am working with a number of data entities which can be created, read, updated and deleted, and I find myself writing more or less the same code for them. For example, I need to sometimes output data as JSON, and sometimes in a table format. I am finding myself writing 2 different types of view to export the data to. Also, the creation of those entities within DB usually differs just by the SQL statements and the input parameters.

I am thinking of creating a strategy pattern to represent different 'contexts'. For example, the read() method of an AJAX context will be to return the data as JSON. However, I wonder if others have deal with this problem beforehand and will like to know what design patterns are usually use for CRUD operations.

Edit: One note is that sometimes compound entities are used to make up one whole one; for example, a location can have many descriptions, one for each supported language.

A: 

Check ODATA (http://www.odata.org) - that has pretty decent setups for CRUD over HTTP - including a mechanism to push batched updates to the server.

TomTom
A: 

Not really a pattern answer - sorry. But I would suggest using an ORM system (repository pattern) for the database interface. JPA, Hibernate, iBatis, etc. You won't need to write any SQL any more.

If you want to minimize the amount of code that you have to write, try a framework such as Grails. (Write a full CRUD web site with about 30 lines of code.) You don't need to write any of the boilerplate code any more.

John
+1  A: 

There isn't one single pattern for CRUD, there are many overlapping/competing patterns. One of the best sources for these CRUD patterns is:

Martin Fowler's Patterns of Enterprise Application Architecture

In general, the best way to solve this particular problem is with an ORM (assuming a relational data store, which seems like a safe assumption in this case):

http://en.wikipedia.org/wiki/Object-relational_mapping

As far as exposing your objects through views, there are frameworks out there to help with that as well, but those frameworks are specific to your coding environment, which you did not specify.

Michael Maddox
Fowler's website appears to be down at the moment.
Michael Maddox

related questions