What is the pros and cons of using Generic DAO and Generic Service Pattern in Spring MVC with Hibernate - spring

I have a thought to implement Generic DAO and Generic Service in my new project. I have seen lot of examples in the web.
Before start I want to know the pros and cons of using this design pattern.
Can any one tell Is it advisable to use this pattern?

I think, it will be better to have an other opinion about DAO and generic DAO. Some words about Pros (My suggestions are valid if you use ORM, Hibernate for an example, not plain JDBC).
Creates a nice abstraction layer of the actual storage system.
It is a marketing bullshit. In real life we have problems to migrate between various RDBMS (Oracle RDBMS -> PostgreSQL). Not speaking about change of a storage system type (RDBMS -> NoSQL for example).
Provide a more object-oriented view of the persistence layer.
No! It is very hard to do properly. Most DAO implementations have a dozens of methods like
getSomething(String x, String y, String z);
getSomethingOther(String x, String z);
Provide a clean separation between the domain class and code which will perform the data access from databse.[using JDBC,ORM[like
hibernate] or JPA].
May be, but usefulness of this separation is exaggerated.
Once you have the general CRUD flow set, the same layout can be repeated for other DAOs.
It is correct.

Generic DAO design pattern comes into picture when more then one DAO classes wants to communicate with database (as per example CRUD(Create,Read ,Update and Delete) ),with out this design pattern you will end up writing separate code to make database call (using session) for each of your DAO classes which is a tedious work in general because with each new implementation of DAO classes you have to write you own code to deal with database.
Below are some Pros and cons of using Generic DAO.
Note: Details give below are what I have learned from answers given to SO Question Pros and Cons of the use of DAO pattern
Pros
1. Creates a nice abstraction layer of the actual storage system.
2. Provide a more object-oriented view of the persistence layer .
3. Provide a clean separation between the domain class and code which
will perform the data access from databse.[using JDBC,ORM[like
hibernate] or JPA]
4. Once you have the general CRUD flow set, the same layout can be
repeated for other DAOs.
Cons
1. If you handwrite the DAOs, then the code can become tedious and repetitive you have to use code generators/templates and ORM.
Q - Can any one tell Is it advisable to use this pattern?
A- After Observing above pros and cons I used Generic DAO in my application as abstraction layer to communicate with database in Terms Of CRUD which actual helped me reduces lots of duplicate code to do same thing other DAOs.At first it will take time to get used to it of afterwards use of Generic DAO will make you life easy.

Related

Core data dao pattern

I'm starting developing for ios, and now i'm studying core-data.
One thing was not clear for me, when i was studying a lot of people was managing core-data entitys on the controller.
For me this isn't MVC, since core-data is from Model layer.
So i think will be nice to implement core-data using DAO pattern, but before i wanna know if there is any core-data pattern or if there's some cons implementing DAO using core-data?
It is indeed correct to avoid implementing data look-up methods in the controller. This way the philosophy of the MVC design pattern is adhered to: the controller should just be calling high-level "glue" code and therefore acting as a document that describes how the view is interacting with the model.
With regards to persistent objects, there are two main approaches to this:
Use the ActiveRecord pattern
Use the Data Access Object pattern.
A Data Access Object (DAO) is an interface dedicated to the persistence of a model/domain object to a data-source.
The ActiveRecord pattern puts the persistence methods on the model object itself, whereas the DAO defines a discrete interface. The advantage of the DAO pattern is:
Its easy to define another style of persistence, eg moving from a Database to cloud, without changing the interface and thus effecting other classes.
The persistence concerns are modularized away from the main model object concerns.
The advantage of the ActiveRecord pattern is simplicity.
ActiveRecord for CoreData
At the present time the ActiveRecord pattern seems to be a lot more popular among Objective-C developers. The following project provides ActiveRecord for CoreData: https://github.com/magicalpanda/MagicalRecord
DAO for CoreData
I'm not familiar with a widely used library that provides the DAO pattern for CoreData. However, it could be quite easily applied without the assitance of a library:
Define all your data methods for a particular entity - findByName, save, delete, etc on a protocol.
Implement the protocol by calling the appropriate CoreData methods.
NB: The example project for the Typhoon framework will soon include some examples of applying the DAO pattern with CoreData.
You are looking for something like Core Date Persistence Framework
This framework allows you doing like:
DAOFactory *factory = [DAOFactory factory];
DAO *dao = [factory createRuntimeDAO:#"EntityName"];
NSArray *items = [dao findAll];
And a lot of more interesting things.

EF to ADO.NET transition

Need suggestion for migration few modules of asp.net mvc 3 application:
Right now we are using EF with POCO classes, but in the future for some performance driven modules we need to move to ADO.NET or some other ORM tool (may be DAPPER.NET).
The issue we are facing as of now is: our views dependent on Collection classes getting loaded through EF, what strategy should i used for these entity classes to be get loaded exactly the same way as by EF with some other ADO.NET or ORM tool.
What i want is to be able to switch between EF & ADO.NET with minimum of change at data access layer, as i don't want my Views to get effect by that.
You should use the Repository Design Pattern to hide the implementation of your data access layer. The Repository will return the same POCO's and have the same operations contracts no matter what data access layer you are using underneath the hood. Now this works fine if you are using real POCO's that do not have virtual methods for lazy loading in them. You will need to explicitly handle loading of dependent collections on entities to make this work.
What I've seen so far, a seamless transition from one ORM/DAL to another is an illusion. The repository pattern as suggested by Kevin is a great help, a prerequisite even (+1). But nonetheless, each ORM has a footprint in the domain layer. With EF you probably use virtual properties, maybe data annotations or, easily forgotten, a validation framework that easily fits in (and dismiss others that don't). You may rely on EF's ability to map across join tables. There may be things you don't (but would like to) do because of EF.
(Not to mention tools that execute scaffolding on top of an EF context. That would make the lock-in even tighter.)
Some things I might do in your situation (forgive me if I'm stating the obvious for you)
Use EF optimally. (Best mappings, best associations, ...) Preparing for the future is good, but it easily degenerates into the YAGNI pattern.
Become proficient in linq + EF: there are many ways to needlessly kill performance with EF. Suppose EF is good enough!
Keep looking for alternatives for high performance, like using stored procedures, parallellization, background processing, and/or reducing data volumes, and choose one when the requirements (functional and non-functional) are clear enough.
Maybe introduce an abstraction layer with DTO's that serve your views now, and in the future can be readily materialized by another ORM or ADO.
Expose POCO's as interfaces, which can be implemented by other objects later.
Just to add to both of these answers...
I always structure my solution into these basic projects:
Front end (usually asp.net MVC web app),
Services/Core with business processes,
Objects with application model POCOs and communication interfaces - referenced by all other projects so they serve as data interchange contracts and
Data that implements repositories that return POCO instances from Objects
Front end references Objects and Services/Core
Services Core references Objects and Data
Data references Objects
Objects doesn't reference any of the others, because they're the domain application model
If front end needs any additional POCOs I create those in the front end as view models and are only seen to that project (ie. registration process usually uses a separate type with more (and different) properties than Objects.User entity (POCO). No need to put these kind of types in Objects.
The same goes with data-only types. If additional properties are required, these classes usually inherit from the same Objects class and add additional properties and methods like generic ToPoco() method that knows exactly how to map from data type to application mode class.
Changing DAL
So whenever I need to change (which is as #GetArnold pointed out) my data access code I only have to provide a different Data project that uses different library/framework. All additional data-specific types etc. are then part of it as well... But all communication with other layers stays the same.
Instead of creating a new Data project you can also change existing one, by changing repository code and use a different DAL in them.

Model View Controller (MVC) : Model & Data Types

Suppose you have an N-Tier, MVC architecture of your (java or *) application. You chose MVC for its logical, manageable partitioning of the application code.
Suppose you are into Java, since there are many frameworks or tools out there, you don't want to tie a Layer (M or V or C) to a specific technology, and would like to maintain the freedom for later upgrades or even integration with other parts.
Now, in every scenario, a Model may contain primitive data types (like Int, String..etc), or more advanced ones in the form of classes (OO features for max complexity).
How would you deal with that:
keep your Model as POJO as you can, and implement the typing at the V or C layer, since it is mostly about data input and validation . This way, you don't have to worry about your Model being used elsewhere, almost nothing will change at the DAL as well, but you have to do extra effort to convert your model to a rich-model (rich in types); when you transfer it from the storage to the view
enable your Model to support types as other nested Models, and implement V or C layer tricks to deal with it, each Layer will have to process the model-complex, instead of just using getters and setters. However this way, you keep the model-complex in other technological settings, which should be adapted accordingly.
[none of the above or else]
I think the technology is irrelevant if you wanna go fully distributed. I would create separate apps for each layer, which you can easily cluster and then choose a standardized communication format like JSON over HTTP(s).
JSON can be as simple or complex as you like and pretty much every language out there has support for it built in.
HTTP is fast and simple, and very easy to scale.
Just my two cents.

Business Layer structure, how do you build yours?

I am a big fan of NTiers for my development choices, of course it doesnt fit every scenario.
I am currently working on a new project and I am trying to have a play with the way I normally work, and trying to see if I can clean it up. As I have been a very bad boy and have been putting too much code in the presentation layer.
My normal business layer structure is this (basic view of it):
Business
Services
FooComponent
FooHelpers
FooWorkflows
BahComponent
BahHelpers
BahWorkflows
Utilities
Common
ExceptionHandlers
Importers
etc...
Now with the above I have great access to directly save a Foo object and a Bah object, via their respective helpers.
The XXXHelpers give me access to Save, Edit and Load the respective objects, but where do I put the logic to save objects with child objects.
For example:
We have the below objects (not very good objects I know)
Employee
EmployeeDetails
EmployeeMembership
EmployeeProfile
Currently I would build these all up in the presentation layer and then pass them to their Helpers, I feel this is wrong, I think the data should be passed to a single point above presentation in the business layer some place and sorted out there.
But I'm at a bit of a loss as to where I would put this logic and what to call the sector, would it go under Utilities as EmployeeManager or something like this?
What would you do? and I know this is all preference.
A more detailed layout
The workflows contain all the calls directly to the DataRepository for example:
public ObjectNameGetById(Guid id)
{
return DataRepository.ObjectNameProvider.GetById(id);
}
And then the helpers provider access to the workflows:
public ObjectName GetById(Guid id)
{
return loadWorkflow.GetById(id);
}
This is to cut down on duplicate code, as you can have one call in the workflow to getBySomeProperty
and then several calls in the Helper which could do other operations and return the data in different ways, a bad example would be public GetByIdAsc and GetByIdDesc
By seperating the calls to the Data Model by using the DataRepository, it means that it would be possible to swap out the model for another instance (that was the thinking) but ProviderHelper has not been broken down so it is not interchangable, as it is hardcode to EF unfortunately.
I dont intend to change the access technology, but in the future there might be something better or just something that all the cool kids are now using that I might want to implement instead.
projectName.Core
projectName.Business
- Interfaces
- IDeleteWorkflows.cs
- ILoadWorkflows.cs
- ISaveWorkflows.cs
- IServiceHelper.cs
- IServiceViewHelper.cs
- Services
- ObjectNameComponent
- Helpers
- ObjectNameHelper.cs
- Workflows
- DeleteObjectNameWorkflow.cs
- LoadObjectNameWorkflow.cs
- SaveObjectNameWorkflow.cs
- Utilities
- Common
- SettingsManager.cs
- JavascriptManager.cs
- XmlHelper.cs
- others...
- ExceptionHandlers
- ExceptionManager.cs
- ExceptionManagerFactory.cs
- ExceptionNotifier.cs
projectName.Data
- Bases
- ObjectNameProviderBase.cs
- Helpers
- ProviderHelper.cs
- Interfaces
- IProviderBase.cs
- DataRepository.cs
projectName.Data.Model
- Database.edmx
projectName.Entities (Entities that represent the DB tables are created by EF in .Data.Model, this is for others that I may need that are not related to the database)
- Helpers
- EnumHelper.cs
projectName.Presenation
(depends what the call of the application is)
projectName.web
projectName.mvc
projectName.admin
The test Projects
projectName.Business.Tests
projectName.Data.Test
+1 for an interesting question.
So, the problem you describe is pretty common - I'd take a different approach - first with the logical tiers and secondly with the utility and helper namespaces, which I'd try and factor out completely - I'll tell you why in a second.
But first, my preferred approach here is pretty common enterprise architecture which I'll try to highlight in brief, but there's much more depth out there. It does require some radical changes in thinking - using NHibernate or Entity framework to allow you to query your object model directly and let the ORM deal with things like mapping to and from the database and lazy loading relationships etc. Doing this will allow you to implement all of your business logic within a domain model.
First the tiers (or projects in your solution);
YourApplication.Domain
The domain model - the objects representing your problem space. These are plain old CLR objects with all of your key business logic. This is where your example objects would live, and their relationships would be represented as collections. There is nothing in this layer that deals with persistence etc, it's just objects.
YourApplication.Data
Repository classes - these are classes that deal with getting the aggregate root(s) of your domain model.
For instance, it's unlikely in your sample classes that you would want to look at EmployeeDetails without also looking at Employee (an assumption I know, but you get the gist - invoice lines is a better example, you generally will get to invoice lines via an invoice rather than loading them independently). As such, the repository classes, of which you have one class per aggregate root will be responsible for getting initial entities out of the database using the ORM in question, implementing any query strategies (like paging or sorting) and returning the aggregate root to the consumer. The repository would consume the current active data context (ISession in NHibernate) - how this session is created depends on what type of app you are building.
YourApplication.Workflow
Could also be called YourApplication.Services, but this can be confused with web services
This tier is all about interrelated, complex atomic operations - rather than have a bunch of things to be called in your presentation tier, and therefore increase coupling, you can wrap such operations into workflows or services.
It's possible you could do without this in many applications.
Other tiers then depend on your architecture and the application you're implementing.
YourApplication.YourChosenPresentationTier
If you're using web services to distribute your tiers, then you would create DTO contracts that represent just the data you are exposing between the domain and the consumers. You would define assemblers that would know how to move data in and out of these contracts from the domain (you would never send domain objects over the wire!)
In this situation, and you're also creating the client, you would consume the operation and data contracts defined above in your presentation tier, probably binding to the DTOs directly as each DTO should be view specific.
If you have no need to distribute your tiers, remembering the first rule of distributed architectures is don't distribute, then you would consume the workflow/services and repositories directly from within asp.net, mvc, wpf, winforms etc.
That just leaves where the data contexts are established. In a web application, each request is usually pretty self contained, so a request scoped context is best. That means that the context and connection is established at the start of the request and disposed at the end. It's trivial to get your chosen IoC/dependency injection framework to configure per-request components for you.
In a desktop app, WPF or winforms, you would have a context per form. This ensures that edits to domain entities in an edit dialog that update the model but don't make it to the database (eg: Cancel was selected) don't interfere with other contexts or worse end up being accidentally persisted.
Dependency injection
All of the above would be defined as interfaces first, with concrete implementations realised through an IoC and dependency injection framework (my preference is castle windsor). This allows you to isolate, mock and unit test individual tiers independently and in a large application, dependency injection is a life saver!
Those namespaces
Finally, the reason I'd lose the helpers namespace is, in the model above, you don't need them, but also, like utility namespaces they give lazy developers an excuse not to think about where a piece of code logically sits. MyApp.Helpers.* and MyApp.Utility.* just means that if I have some code, say an exception handler that maybe logically belongs within MyApp.Data.Repositories.Customers (maybe it's a customer ref is not unique exception), a lazy developer can just place it in MyApp.Utility.CustomerRefNotUniqueException without really having to think.
If you have common framework type code that you need to wrap up, add a MyApp.Framework project and relevant namespaces. If your're adding a new model binder, put it in MyApp.Framework.Mvc, if it's common logging functionality, put it in MyApp.Framework.Logging and so on. In most cases, there shouldn't be any need to introduce a utility or helpers namespace.
Wrap up
So that scratches the surface - hope it's of some help. This is how I'm developing software today, and I've intentionally tried to be brief - if I can elaborate on any specifics, let me know. The final thing to say on this opinionated piece is the above is for reasonably large scale development - if you're writing notepad version 2 or a corporate phone book, the above is probably total overkill!!!
Cheers
Tony
There is a nice diagram and a description on this page about the application layout, alhtough looks further down the article the application isnt split into physical layers (seperate project) - Entity Framework POCO Repository

Design Patterns: Factory and Repository

I have been wondering if the Factory Pattern and the Repository Pattern is keened to go hand in hand in a Domain Driven Design project?
The reason i ask is the way i'm doing this is like so:
GUI -> ClassFactory -> ClassProduct (is in the Domain Model) -> ClassProductRepository -> Datasource
The GUI calls the ClassFactory to separate the GUI from business logic. The ClassProduct calls the ClassProductRepository to separate the business logic from the datasource.
Is this a wrong approach of using these Design Patterns with Domain Driven Design? If so, please state your opinion on this subject.
Your on the right track. As Chad pointed out, you'll want to use a GUI interface separation pattern as an additional layer between your domain and the UI. MVC, MVP, Presentation Model, etc are established and well documented patterns for UI separation. Martin Fowler's excellent PoEAA covers many of them
As for your main question. Yes. Factories and Repositories work very well together. In fact, Evans suggests in DDD that in some cases you can delegate responsibility for object creation from your repository to your factory classes when you're reconstructing objects from the data store.
client <=> repository -> factory
|
v
database
The client requests an object from
the repository.
The repository queries the database.
The repository sends raw data to the
factory.
The factory returns object.
An over simplification but you get the idea. One point that isn't touched on by Evans (but which Fowler covers) is dependency injection. As your domain complexity continues to grow you may want to consider moving to an IoC container for managing object life cycles.
I would suggest sticking to MVC as a generic approach to separate your business logic from your view and your controller. This has been well documented and well studied approach, though its the best that we have currently.
Though, it seems like you're trying to use the pattern just for the reason of using the pattern. This is good for learning,but in most application systems I've seen the patterns you have described either don't exist and a simpler approach works or that its a nightmare to maintain.
Please see my previous answer to a question similar like this, that has a video that can help you in your design in the future.
Linky

Resources