Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question 开发者_运维知识库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.
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.
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.
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.
精彩评论