what is Model in MVC pattern - model-view-controller

I am creating an application were I am using MVC pattern.For this I am considering my view as jsps,controller as servlets and model as DAO objects.I have a doubt that me considering DAO objects as Model is right or wrong?

Model is not a DAO. It is a layer, which contains all the domain logic, and is composed mostly from two types of elements, with following responsibilities:
business logic
data access (usually implemented as DataMapper)
The idea is that business logic should never be tied to the storage mechanism. When you are creating an invoice, the domain object should not care, if data comes from SQL database, MSWord document, remote REST API or just a mocked up data.
You might find this article interesting and relevant: GUI Architectures.

A model in MVC is where the business logic lives.
Looking at the sun Java EE pattern definitions we see that DAOs encapsulate persistence mechanisms and are used by a Business Object. I don't therefore see DAOs as natuarally having any business logic.
In simple systems, a few database tables, or those where the business logic is implemented in
the database (stored procedures, referential integrity checks, triggers) then the DAO is effectively a facade in front of Business Logic, so they pretty much look like the Model. So in some introductory material you may see the DAO as pretty much the only Java expression of the Model.
When we choose to implement our business logic in Java, it would lie in a layer above the DAO, in for example Session Beans, which use the DAOs, and in my mind it's the Session Bean or equivalent which is the Model.
So ask yourself: where is the business logic? That's where the Model really is.

Related

Model classes vs Model in MVC

Does the model in MVC contain both business logic (algorithms and stuff) and the classes that are mapped to entity tables in databases? Those mapped classes are called model as well, specifically, because they model some data. My confusion is this: Does model contain the business logic? or is it just entities? It turns out that it contains, from Mozilla docs: Model: Manages data and business logic.
I got confused by how Java Spring projects are structured. There are controllers, service (business logic), repository(connection to database, aka DAOs) and model classes (Classes of objects that are received by controller and often mapped to database entities). Let's map this to MVC "components":
View - Not in a spring app;
Controller - Rest controller (or just Controller, depending on how you want to structure your app);
Model - Services, Repositories, Model classes (???).
I am confused here, that we have model in both left and right sides.
Thanks.
Edit: Adding a snippet of code, and the structure of app.
This is how spring application looks usually. What most of people do.
.
├── BasicSpringAppApplication.java
├── controller
│   └── CustomerController.java
├── model
│   └── Customer.java
├── repository
│   └── CustomerRepository.java
└── service
└── CustomerService.java
This is how model/entity looks in a java file:
package com.example.basicspringapp.model;
public class Customer {
private String id;
private String name;
private String surname;
private int age;
//constructors, getters, setters
}
Look what I called (and what they call usually) a model, only a specific thing, an entity. But in MVC it's more than that! Model includes not only entities, but services and repositories as well, anything which is not a view and a controller.
Why MVC pattern is messed up in usual spring applications? It seems messed up for me, at least. Why people doesn't call those classes an entity or something like that? Since the model is more than that, for MVC.
The model in MVC-based applications:
In an MVC-based application, the domain model (or, short, the model) mirrors a certain business. It is programmed as a layer - the model layer, or the business layer - and is composed of multiple objects of various types:
Data mappers: transfer data between entities and the chosen persistence space (database, session, remote repository accessible through SOAP, etc).
Repositories: transfer data between entities and the chosen persistence space, too, though by using data mappers from the data mapers layer. They build a layer additional to the data mappers layer, in order to hide the type of persistence space from their users. Each repository object is coded as a collection of entities of a certain type, accessible in a collection-like manner. So, for example, a collection of Book entities could be named BookCollection, or Library, or BooksRepository and would contain methods used to handle a collection of objects of type Book, like: "find/get/remove/update/store/exists/count/etc the book(s) in the book collection".
Entities, or domain objects: to hold the data and the behavior requested by the specific business. These components contain the business logic which is independent of the application in which they are used. In other words, they can be reused by multiple applications.
Value objects.
Services, as part of the service layer. These objects contain business logic as well, but, in comparison to entities, their business rules are dependent of the application in which they are used. Because of this fact, it is debatable if the service classes should be defined as part of the domain model, or of the delivery mechanism (see the first two resources below).
So, in MVC-based applications:
the model is not a class, but a layer of objects with different responsibilities;
the model contains business logic in both entities and services;
the domain objects contain both data and behavior.
By themselves, the entities are NOT mapped in any way to any persistence system (like a database). Their properties and methods mirror the specific business, by using a business-specific vocabulary, therefore beeing completely independent of the structure of the chosen persistence system. It is the responsibility of the data mappers - and theirs only! - to know about and map between the properties of the domain objects and the structure of the database records, for example.
In the first two resources below, at least, you'll discover that, in MVC-based applications, the persistence system (database, etc) does NOT determine the structure of the application. The persistence system is "just a detail".
Notes:
Injecting other components of the model layer beside services into controllers results in wrongly having business logic in them. The sole purpose of the controllers should be to delegate the processing of the user request to the service layer.
The advantages and disadvantages of the object-relational mapping systems (ORMs) are debatable.
Resources:
Keynote: Architecture the Lost Years by Robert C. Martin
Sandro Mancuso : Crafted Design
How should a model be structured in MVC?
Unbreakable Domain Models with slides
DDD Building Blocks: Value Object
Validating Value Objects
A definition of the Ubiquitous Language
The tutorials of Alejandro Gervasio, with PHP code: Building a Domain Model – An Introduction to Persistence Agnosticism, Building a Domain Model – Integrating Data Mappers, Handling Collections of Aggregate Roots – the Repository Pattern, An Introduction to Services
Challenges of object–relational mapping, Object–relational impedance mismatch

Is it a good idea to use Bean Validation (JSR303) in JSF2 Webapplications?

Iam about to create a webapplication with JavaServer Faces 2. In the backend things are managed with other usual JEE technologies like EJB3.1 and JPA2. The point is, Iam following some domain driven architecture, which means, the the domain models are used at the JSF layer as backing bean models and are typically persisted as persistent entities at the persistence layer. Using the same model at different layers yields the advantage of only defining the related model restrictions once and for all. Using Bean Validation at this level provides the restrictions of this model to either JSF, JPA etc.
Now my question is, whether using bean validation with JSF2 is a good idea? My concerns are that linking the validation restrictions directly to the model might be the wrong approach, as the validation of the JSF lifecycle usually happens somehow earlier than accessing the model (for its validations rules). As much as I know JSF validation is not taking place during model processing (aka. phase 4: apply model values) but earlier in its own dedicated point in time (phase 3: process validations) and is applied on the component value (submitted value). However, how should the JSF validation (in phase 3) know the actual restrictions of the bean, if it is not validating during the model processing?
Thanks for any clarification on this.
[Edit]
To be more specific, right now Iam using Bean Validation for this purpose and it is working, as invalid values are rejected and a faces message is properly shown. I just wonder if it is the right approach, as to my understanding the validation might take place in the wrong JSF phase and thus might lead to an inconsist component model.
You can add all those bean validations in Data Transfer Object(DTO), The DTO's responsible for delevering the UI data in the JSF. After all the validations are succeed you can copy the DTO's to the Entity(Model) Object.
For copying the (DTO's to Entity) or (Entity to DTO's) we can use third party librires like dozer mapper.
This will avoid the validation restrictions directly to the model layer. I mean the Entity Objects

BO and DAO in Spring + JSF

I have a architecture dillema. I've implemented Bean (#Named) BO and DAO. And I am not sure how communication should be implemented. Let's say I want to register user. I am filling the bean from JSF then I use userBO.registerUser(this) method on injected userBO. I am not sure what should happen next. I think validation should be BO's work and if everything is ok data should be passed to DAO. DAO should create UserEntity and persist it into database. But what if we create UserEntity in BO and pass it to DAO. I am a little bit confused.
BO should deal with any business logic.
If the creation of the UserEntity is related with any business logic (i.e. the attributes or the values need to be calculated according to a non-trivial logic rule) the creation might stay in the BO. If the creation is simple, and basically puts the values of the form in the object, it can be populated in a previous layer (Controller, or JSF, or whatever).
About the DAO, it should only persist a populated object into your database.
Hope this helps you!

struts2 spring jpa layers best practice

I have an app written with Struts2 Spring3 JPA2 and hibernate. In this app i have the following levels :
- struts2 actions
- spring services
- spring DAO
So, one struts action call for a service which can contain calls to one or many dao objects.
In order to display the info on the screen i have created some "mirror" objects for entities; ie: EmailMessage entity has a EmailMessageForm bean that is used to display/gather data from webforms (i don`t know if this is the best practice), and hence my problem.
In EmailMessageServiceImpl i have a method called:
public List < EmailMessage > getEmailMessages(){
//code here
}
and, if i call this from struts action i cannot get dependencies because session has expired (i have TRANSACTION entity manager). So, one solution would be to create another method
List<EmailMessageForm> getEmailMessagesForDisplay()
{
//....
}
and here to call for getEmailMessages() and convert this to form objects.
What do you recommend me ?
What is the best practice for this kind of problem ?
If by "dependencies" you mean "lazy-loaded objects", IMO it's best to get all the required data before hitting the view layer. In your current architecture it looks like that would mean a service method that retrieves the DTOs ("form beans"; I hesitate to use the term since it's easy to confuse with Struts 1).
Some say using an Open Session in View filter/interceptor is better. It's easier, but can lead to unintended consequences if the view developer isn't paying attention, including multiple N+1 queries etc.

ViewModel and Model in ASP.NET MVC 3 in regards to DDD - Advice

Going through the tutorial here: http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs
I've noticed that they are passing the EF generated entity from the controller to the service layer. Should they be passing the viewmodel instead and then do the mapping in the service layer or is what they are doing correct?
I'm trying to understand the translation of the view model into the actual domain model passed from the service layer to the persistence layer.
Thanks
The general rule is that lower layers should have no knowledge about the upper levels.
This means that the service layer should have no knowledge of the view models (since they are an implementation detail in the user interface layer)

Resources