How are Models (in MVC) and DAOs supposed to interact? - java

How are models and DAOs supposed to interact? I'm in the process of putting together a simple login module and I'm unsure where to put the "business logic." If I put the logic with the data in the model, how would I access the logic?
Currently, I have:
A controller that receives form data
A model that is a simple reflection of a db table
A DAO that using hibernate performs a simple select query, based on the
form parameters received by the
controller.

The controller has to find/load the business object matching the request and execute it. The Strategy Pattern is useful in this. The business object on its turn has to get a handle of the DAO and the model to do the process.
E.g. (pseudo, inside a front controller servlet)
public void process(request, response) {
View view = new View(request, response);
Action action = ActionFactory.getAction(request);
if (action != null) action.execute(view);
view.navigate();
}

Put it in the controller. Controller is like a heart of your application where most of the logic is written.
It's not good to put the business logic at Model Level.

You might want to take a look at some of the answers to Best designs for breaking down business logic and data layer when they seem to overlap?

A typical layering would be like this:
Controller
Model
Business Layer
Data Layer (DAO)
The model would contain both the business and data layers while keeping those layers loosely coupled to the extent that makes sense. The controller would access the model, which in most cases should be the business layer. It's preferable that the controller not have direct access to the data layer, but it happens quite a bit in smaller apps.

Related

MVC Structure for Web application in Spring?

Using Spring MVC to develop a web application. Earlier I was using Controller layer, Service layer(business logic), Model layer(entity) and DAO(DB) layer.
But someone pointed out that i should introduce two more layer ie. dto layer for collecting data from front end and transforming layer which will convert than dto into model(entity) layer objects.
Now I am using:
Controller layer (which will send the data to DTO layer)
DTO layer (which will send the its data to transforming layer)
Transforming layer(for converting dto layer objects into entity layer objects)
Service layer(Business logic)
Entity layer(POJO which will map with database)
DAO(which will use entity objects to store the database)
In this way we can keep front end and backend data different. Please help me out, is this a proper structure for Spring MVC ?
There is an interesting question answer thread on MVC here:https://softwareengineering.stackexchange.com/questions/127624/what-is-mvc-really
Some of the key points to remember when designing an application should be; layered and loosely coupled.
In your scenario, having additional transform layer does not necessarily make our break MVC pattern. It is just an additional layer you have introduced in MVC; a design strategy followed by many.
DTO is just a pattern to encapsulate data. Normally is used to be returned in your controllers, but you don't need always to create a DTO, you can use your entities for this. I just use a Dto when i need a different data structure, that any entity support, like a report for example.
About your project layers Model/Dao/Service/Controller it's correct, i strongly recommend for you the book Domain-driven design, it's will help you to build your software architectures!
But someone pointed out that i should introduce two more layer ie. dto layer for collecting data from front end and transforming layer which will convert than dto into model(entity) layer objects.
No, it's incorrect. You should use only layers that are necessary.
Earlier I was using Controller layer, Service layer(business logic), Model layer(entity) and DAO(DB) layer.
This is also incorrect. There's no strict definition of MVC is a pattern, but it's used only on one layer called a view layer, or in other terms presentation layer. Where the model, view, and controller reside. There's another layer called a service layer, which is optional. Then persistence layer, in this layer you model your objects and save them in the database or somewhere else. No more layers are necessary to the simple web application.
A few words about model, it's a set of classes that you want to persist or use in the view layer to show/store the data. Here you can play with it, because someone prefer to use it's own model to show/store the data, and others prefer their own model to persist it. These transformations are usually done in persistence or service, or in both layers. Keep in mind that all layers a loosely coupled to each other, but you can transfer data beans from one layer to another and back without problems. Entities in the detached state or other beans like DTOs are examples of such objects that you can pass and bake between layers. And no additional layers are necessary.

In which layer do I access database in a MVC design [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a question regarding database access in a mvc application. Where should my database access logic placed?
should it be placed in each model? (if I have a Person model)
Person p = new Person();
p.save();
should it be placed in each controller?
or should I create a different set of classes only to perform the database logic, which means I have an additional layer in addition to model,view and controller?
How is this done?
Also what if an ORM is used?
In MVC pattern, M means models, V means view, C means controller. A common MVC application progress is that once a request is coming, controller get it and do necessary processing, retrieving results data, then pass the results data to view for rendering. After view layer is rendered, it displays to users via GUI.
Controller can be regarded as a commander, it controls process, but it is not good to handle data retrieving in controller. Model should be responsible for retrieving and organizing data. That means data objects should be stored in Model instead of Controller, Controller calls Model to retrieve data objects.
For your case, my suggestion is it needs following components:
PersonController, it calls PersonService.savePerson(Person person) method to save data(or in other case it retrieves result). I suggest Controller layer should be thin.
PersonService, it has method savePerson(Person person), this method calls PersonDAO.savePerson(Person person) method to save/retrieve projects data(here it saves data), and maybe other handling. Here business logic goes.
PersonDAO, it has several methods which deal with Person objects(like savePerson(Person person), getAllPersons()), deal with database in this layer. But these methods should be independent with business logic(as business logic should be deal in PersonService).
Person object, it is value object, it just defines what attributes a Person should have, like name, age, etc, with get/set methods, used for passing data through different layers. It does not deal with database at all.
While for uncomplex application, Service layer is not very necessary and can be integrated to Controller layer, which means just PersonController is ok.
Others have pointed out that database access is a Controller function, but I recommend that you create a new library project to handle the database interaction. Typically this will have a name like "customerService.jar" - i.e. it encapsulates everythng you want to do to a customer. This will simplify your application, and add greatly to the reusability of your code.
This would be by approach:
Define an interface that exposes business level operations (eg. changeUserRole(long userId, Role newRole) or makePayment(long accountId, BigDecimal amount) rather than the CRUD approach of updateUser(User user) etc. Typically some of the methods exposed by the interface will look like CRUD methods but might do more at the database end (e.g. check account status, maintain audit tables).
Implement your business logic in this layer. Purists would say that there should be a separate layer for the business logic, but this makes it difficult to use SQL facilities (joins in particular) to efficiently access the database. In my experience these two layers need to be combined to keep the system simple and performant.
Use an ORM tool to access the database and map from business objects to the database. (MyBatis is my favorite). If your database accurately reflects your business model, then you probably won't need separate DAO and business objects.
Inject an instance of your customerService into your web MVC controller. The job of the controller is now to validate user input, populate the model, pass through requests to the customerService and put response data back into the model.
So if your needs change in future (e.g. You need to create an IOS or Android native app) you have a re-usable service that will happily do the job. Similarly if the architects insist on exposing it as a REST or SOAP service, you only need add the "glue logic" to implement the REST or SOAP service.
Also, it is easy to mock out the customerService in web unit tests.
Best of luck!
Its always better to segregate your code and group them according to their behavior. Model classes can be used as logical representation of your DB. You should have some Utility / helper classes which does your DB activities, and controller should interact with them.
Ideally you should have as many model classes (if not more) as you number of tables in the DB.
When you use ORM, the connections and mappings (once declared) are take care off by the framework and you focus on the business logic.
In a Web application using a framework such as Spring or Jersey (which you should use), it's generally best to make your "controllers" (HTTP request handlers) as simple as is practical, wrappers around a service layer that contains your business logic such as database access. This both makes testing dramatically simpler, since you can test the business logic directly without the complication of HTTP requests, and makes it easier to reuse your business logic in future changes such as adding scheduled tasks.
When more than very simple CRUD operations are involved with something like a Person object, I will create a PersonService with methods that are expressed in terms of the business operations and inject that service into the controller. For simple CRUD operations, I generally use Spring Data repositories directly from the controller.
Define function which accesses Db or which does DB related operations in your class file which we call it as Model and then access that function using that class object in Controller. Controller is just set of functions which give us DB results and assign those results to variables in Controller and access those variables in View which is your front-end

Passing data back and forth from Spring MVC Controllers to Service layer

Could anyone suggest the best approach for sending data from controllers to service layer ?
I have UI <--> Controllers <--> Services <--> DAOs
I have models (or commands) to hold the data that user inputs in the UI to pass to controllers
I thought of creating models in controller layer , but don't want to pass them directly as service layer then depends on controller layer.
Do you suggest creating models in service layer and use them in controller layer ? But in this case these models will be used by jsps to serve data to the user ? is that ok ?
Could anyone suggest the best way in java to design the mvc layer shown above ?
Thanks
Ramesh
It's not necessarily wrong to serve domain model object directly to the UI layer, it's just that you tend quickly to run into a few common problems:
the view screen only needs a small subset of the model
certain fields like for example User.password you never want to send to the view layer
the domain model can contain loops, meaning object navigation paths in the object graph that go back to the initial object. This cannot be serialized correctly
lazy initialization exception on the domain model caused by detached objects
The common pattern to solve this is the DTO pattern, see here the description by Martin Fowler.
The common way to to it in larger applications is for the controller to send and received DTOs, and then do some mapping if needed to convert them into domain objects, this can be done for example with the Dozer mapping library.
On a smaller application this might not be justifiable, specially if you haven't encountered the problems mentioned above, although these tend to show up frequently.
Controllers take input from UIs and forward (hence the name Controller) the request to appropriate Model in tradional MVC pattern. But since you are using Spring MVC why not create your model objects in Spring context and use them is your service layer? You can use #Resource or #Autowired in service layer. Besides, if you want to reuse model objects you can easily do that because this way they are not locked into a particular layer. For eg., web service using your context.
Maybe others have a better way to do this.

In a typical MVC application, which layer is responsible for a Model->DTO conversion?

In a standard Spring MVC application, where I have a Presentation layer, Controller layer, a Service layer, Repository/Persistence layer, which layer should be responsible for converting data retrieved from the DB to a DTO prior to sending to the presentation?
On one hand, I am thinking it should be at the Controller layer since it is specific to the data that is being required by the presentation, and is not "business logic" per se, however, on the other hand, I have nagging feeling that putting in intelligence (ie: knowing which fields to populate in the DTO) in the Controller is not really the job of the controller and should be relegated to the Service layer.
I realize that this may be a "gray" area, but is there a recommended practice?
I honestly do not know of a recommended practice, but I can tell you how it has been done in the projects I've worked on so far.
The Data (let's say Entity) is retrieved from the DB is mapped onto a corresponding Java class in an EntityMapper class, which relies of course in the Repository layer, because it is a DAO operation.
Any business logic applied on it should be tackled in the Service Layer, which passes it to the Controller.
The controller must return the data, but if you do not want to retrieve all the DB data (e.g. IDs, unnecessary columns, etc) which are in your Entity, you can convert them to a server-client DTO, meaning that you can have a similar EntityPresentation (silly name, I know) class, but with fewer fields, that will be communicated by the Controller to the presentation layer.

DAO pattern and model objects

I have looked up a lot of information about the DAO pattern and I get the point of it. But I feel like most explainations aren't telling the whole story and by that I mean where would you actually use your DAO. So for example if I have a User class and a corresponding UserDAO that is able to save and restore users for me, which is the correct way:
The controller creates the User object and passes it to the UserDAO to save it to the database
The controller creates the User object and in its constructor the user object makes a call to the userDAO in order to save itself into the database
This is a code smell and you are missing an extra class "UserManager" which the controller will ask to create the user. The UserManager is responsible for creating the user and asking the UserDAO to save it
I really feel like the third option is the best, because all that the controller is responsible for is delegating the request to the correct model object.
What is your favorite way? Am I missing something here ?
From my experience with DAOs, the first approach is the only correct one. The reason is that it has the clearest responsibilities and produces the least clutter (well, some very respectable programmers regard DAOs themselves as clutter. Adam Bien sees the original DAO pattern already implemented in the EntityManager and further DAOs to be mostly unnecessary "pipes")
Approach 2 binds the model to the DAO, creating an "upstream dependency". What I mean is that usually the models are distributed as separate packages and are (and should be) ignorant of the details of their persistence. A similar pattern to what you are describing is the Active Record pattern. It is widely used in Ruby on Rails but has not been implemented with equal elegance and simplicity in Java.
Approach 3 - what is supposed to be the point of the UserManager? In your example the Manager performs 2 tasks - it has the duties of a User factory and is a proxy for persistence requests. If it is a factory and you need one, you should name it UserFactory without imposing additional tasks on it. As for the proxy - why should you need it?
IMHO most classes named ...Manager have a smell. The name itself suggests that the class has no clear purpose. Whenever I have an urge to name a class ...Manager, it's a signal for me to find a better fitting name or to think hard about my architecture.
For the first approach; IMHO, controller calling a method on a DAO object is not a good design. Controllers must be asking "service" level objects about business. How these "services" persist the data is not a concern for the controller.
For the second approach; sometimes you may want to just create the object, so constructor duty and persisting duty must not be tightly coupled like this.
Lastly, the manager or the service objects is a good abstraction for the layered architecture. This way you can group the business flows in the appropriate classes and methods.
But for Play, companion objects of case classes are also a good candidate to use as DAO. The singleton nature of these objects make it a good candidate.
case class TicketResponse(appId: String, ticket: String, ts: String)
object TicketResponse{
implicit val ticketWrites = Json.writes[TicketResponse]
def save(response: TicketResponse) = {
val result = DB.withConnection {
implicit connection =>
SQL("insert into tickets(ticket, appid, ts)"
+ " values ({ticket},{appid},{ts})")
.on('ticket -> response.ticket, 'appid -> response.appId, 'ts -> response.ts).executeInsert()
}
}
}
The Data Access Object (DAO) should be used closer to the data access layer of your application.
The data access object actually does the data access activities. So it is part of data access layer.
The architecture layers before DAO could vary in projects.
Controllers are basically for controlling the request flow. So they are kind of close to UI.
Although, a Manager, Handler is a bad idea, we could still add a layer between controller and DAO. So controller will pre-process the data that is coming from a request or going out (data sanity, security, localization, i18n, transform to JSON, etc). It sends data to service in the form of domain objects (User in this case). The service will invoke some business logic on this user or use it for some business logic. And it would then pass it to DAO.
Having the business logic in controller layer is not good if you are supporting multiple clients like JSPs, WebServices, handheld devices, etc.
Assuming Controller means the "C" in MVC, your third option is the right approach. Generally speaking Controller code extends or follows the conventions of a framework. One of the ideals of MVC is swapping frameworks, which is really the Controller, should be relatively easy. Controllers should just move data back and forth between the model and view layers.
From a model perspective, Controllers should interact with a service layer - a contextual boundary - in sitting front of the domain model. The UserManager object would be an example of a piece that you would consider part of your service layer - that is the domain model's public API.
for typical webapp i will prefer play framework with play's JPA and database implementation. It much more productive way.
please take a look here http://www.playframework.org/documentation/1.2.5/jpa
and here
http://www.playframework.org/documentation/1.2.5/guide1 and http://www.playframework.org/documentation/1.2.5/guide2
That's it))

Categories