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
Related
#Entity
class MyEntity {
//some properties to be explosed to REST, some not
}
I have some database classes that I want to explose via REST using spring.
Is it advisable to create a DTO for each database class, copying over all properties needed to be exposed.
Because certainly some fields like the id should never be available via rest. But these fields can maybe be annotated accordingly so they are ignored during REST offer?
Is writing DTOs still advisable today if they just serve as plain data containers that get the fields copied over from DB?
Some points I can think while deciding:
Arguments against common model for persistence & web service
In many applications the rest services are written to provide you a fully constructed object & not really a normalized view of the data. For example your rest service may return an Employee object with a Department object, wheras your db model just has a deparment id
Modifications in 1 model do not affect the other. For example you decide to change a String in the persistence model to an integer, you may still be ok with keeping it as a string in your rest service
You may have attributes in the rest model which make no sense to be on the persistence model or vice versa
If you are distributing your model jar (like a client API) then it may end up with a dependency on your persistence framework which your clients may not want/support.
Arguments supporting common model for persistence & web service
Avoid copying/cloning data for every interaction
Avoid duplicate maintenance or possible issues when an attribute is added in 1 model and forgotten in another
In my experience if you are creating services exclusively to be consumed by your own application (like a UI) and have tight control on those services, you might get away with using a common model
However if the rest API is intended for broader use and for longevity I would go with separate models. You can use spring's beanutils to ease the conversion of models from one format to other. See example here
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 6 years ago.
Improve this question
After reading some of the Q/As here on stackoverflow, I am still confused about the correct implementation of DTOs in my web application. My current implementation is a (Java EE based) multi-tier architecture (with persistence, service and presentation layer) but with a "common" package used by all layers, containing (amongst others) domain objecs. In this case the layers can not really be considered as independent.
I am planning to remove the common package step by step, but I encounter various challenges/questions:
Assume the persistence layer would use a class myproject.persistence.domain.UserEntity (a JPA based entity) to store and load data to/from the database. To show data in the view I would provide another class myproject.service.domain.User. Where do I convert them? Would the service for the users be responsible to convert between the two classes? Would this really help to improve the coupling?
How should the User class look like? Should it contain only getters to be immutable? Wouldn't it be cumbersome for the views to edit existing users (create a new User, use the getters of the existing User object etc.)?
Should I use the same DTO-classes (User) to send a request to the service to modify an existing user/create a new user or should I implement other classes?
Wouldn't the presentation layer be very dependent on the service layer by using all the DTOs in myproject.service.domain?
How to handle my own exceptions? My current approach rethrows most "severe" exceptions until they are handled by the presentation layer (usually they are logged and the user is informed that something went wrong). On the one hand I have the problem that I hava again a shared package. On the other hand I am still not sure that this can be considered "best practice". Any ideas?
Thank you for any answers.
Having some packages among different layers is not uncommon, however it is usually done only for cross-cutting concerns such as logging. Your model should not be shared by different layers, or changes to the model would require changes in all those layers. Typically, your model is a lower layer, close to data layer (over, under, or intertwined, depending on the approach).
Data Transfer Objects, as their name imply, are simple classes used to transfer data. As such, they are usually used to communicate between layers, specially when you have a SOA architecture which communicates through messages and not objects. DTOs should be immutable since they merely exist for the purpose of transferring information, not altering it.
Your domain objects are one thing, your DTOs are a different thing, and the objects you need in your presentation layer are yet another thing. However, in small projects it may not be worth the effort of implementing all those different sets and converting between them. That just depends on your requirements.
You are designing a web application but it may help your design to ask yourself, "could I switch my web application by a desktop application? Is my service layer really unaware of my presentation logic?". Thinking in these terms will guide you towards a better architecture.
On to your questions:
Assume the persistence layer would use a class myproject.persistence.domain.UserEntity (a JPA based entity) to store and load data to/from the database. To show data in the view I would provide another class myproject.service.domain.User. Where do I convert them? Would the service for the users be responsible to convert between the two classes? Would this really help to improve the coupling?
The service layer knows its classes (DTOs) and the layer below it (let's say persistence). So yes, the service is responsible for translating between persistence and itself.
How should the User class look like? Should it contain only getters to be immutable? Wouldn't it be cumbersome for the views to edit existing users (create a new User, use the getters of the existing User object etc.)?
The idea behind DTOs is that you only use them for transfer, so operations like creating a new user are not required. For that you need different objects.
Should I use the same DTO-classes (User) to send a request to the service to modify an existing user/create a new user or should I implement other classes?
The service methods might express the operation, the DTOs being its parameters containing just the data. Another option is using commands which represent the operation and also contain the DTOs. This is popular in SOA architectures where your service may be a mere command processor for instance having one single Execute operation taking a ICommand interface as parameter (as opposed to having one operation per command).
Wouldn't the presentation layer be very dependent on the service layer by using all the DTOs in myproject.service.domain?
Yes, the layer over the service layer will be dependent on it. That is the idea. The upside is that only that layer is dependent on it, no upper or lower layers so changes only affect that layer (unlike what happens if you use your domain classes from every layer).
How to handle my own exceptions? My current approach rethrows most "severe" exceptions until they are handled by the presentation layer (usually they are logged and the user is informed that something went wrong). On the one hand I have the problem that I hava again a shared package. On the other hand I am still not sure that this can be considered "best practice". Any ideas?
Each layer can have its own exceptions. They flow from one layer to another encapsulated into the next kind of exception. Sometimes, they will be handled by one layer which will do something (logging, for instance) and maybe then throw a different exception that an upper layer must handle. Other times, they might be handled and the problem might be solved. Think for instance of a problem connecting to the database. It would throw an exception. You could handle it and decide to retry after a second and maybe then there is success, thus the exception would not flow upwards. Should the retry also fail, the exception would be re-thrown and it may flow all the way up to the presentation layer where you gracefully notify the user and ask him to retry layer.
Loose coupling is indeed the recommended way to go, which means you will end up with huge, boring to write, painful to maintain converters in your business logic. Yes, they belong in the business logic: the layer between the DAOs and the views. So the business layer will end up depending on both the DAO DTOs and the view DTOs. And will be full of Converter classes, diluting your view of the actual business logic...
If you can get away with having immutable view DTOs, that's great. A library you use for serializing them might require them to have setters though. Or you might find them easier to build if they have setters.
I have gotten away just fine with using the same DTO classes for both the views and the DAOs. It is bad, but honestly, I did not have the feeling that the system was more decoupled otherwise, since business logic, the most essential part, has to depend on everything anyway. This tight coupling provided for great conciseness, and made it easier to sync the view and DAO layers. I could still have things specific just to one of the layers and not seen in the other by using composition.
Finally, regarding exceptions. It is a responsibility of the outermost layer, the view layer (the Controllers if you are using Spring) to catch errors propagated from the inner layers be it using exceptions, be it using special DTO fields. Then this outermost layer needs to decide if to inform the client of the error, and how. The fact is that down to the innermost layer, you need to distinguish between the different types of errors that the outermost layer will need to handle. For example if something happens in the DAO layer, and the view layer needs to know if to return 400 or 500, the DAO layer will need to provide the view layer with the information needed to decide which one to use, and this information will need to pass through all intermediary levels, who should be able to add their own errors and error types. Propagating an IOException or SQLException to the outermost layer is not enough, the inner layer needs to also tell the outer layer if this is an expected error or not. Sad but true.
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 9 years ago.
Improve this question
I had exam today and one of the questions was the following:
When implementing MVC, from which park of out web application (controller or view) we should call the methods defined in out DAO implementation? You should explain.
I know that the controller responsible of redirecting coming http request to the appropriate view,
and the views (JSP files) should use the DAOs function in order to get info and show it.
My lecturer says I've wrong and the controller take response of it.
When I asked why, he said that "I should have listen in the lectures".
So again, why should the DAOs called from the controller and not from the view?
You should have listened in the Lectures.
Sorry, just kidding :)
Model-View-Controller is an important design pattern used in all sorts of UI design.
View is about displaying the data and interacting with the user - nothing else
Model is about modelling and storing the data - nothing else
Controller is what processes the data, mapping stuff in and out of the model, etc.
You should be able to swap the View from an MVC system completely and it will change the user interaction - but none of the behaviour of the program. From that it should be clear why putting logic in the View is a bad idea.
The DAO is about how you implement your data storage and persistence layer. The View is about how you display your data.
They are two very different jobs and the whole point of MVC is to split things up and give them their own independent jobs to do. You can swap in and out a different persistence layer and the view doesn't need to change, you can swap in and out different views and the persistence layer doesn't change.
By directly coupling presentation to persistence you lose that decoupling. The correct way to do it is write views that just care about the model. Write models that just care about their data and then use a controller to glue them together and to populate the model.
DAO classes are used to access data from datasource like rdbms,xml etc.
Business object request data to be loaded from database through a DAO. DAO does the actual loading of data by using sql queries.
Business object represent actual data eg: EmployeeBO. DAO classes like EmployeeDAO abstracts the underlying database access logic for business object. This promotes decoupling.
Servlet which is a controller may create a EmployeeBO, store data sent by the user in EmployeeBO. EmployeeBO use the DAO EmployeeDAO to store or read data from database and send back to servlet and the servlet passes the data back to jSP again. So servlet uses the DAO and not the JSP.
The whole point is DAO pattern.
Neither of them. That would be answer to your question.
MVC pattern is for the presentation layer only and has nothing with the persistence layer.
DAO pattern is for persistence layer.
They are different patterns if applied to the web application.
Between these two layers should be a service layer.
The service layer holds all the business logic of the application interacting with the presentation and persistence layers simultaneously.
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))
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 4 years ago.
Improve this question
I'm building a MVC web application (using the Spring MVC framework), and I'm a little stumped on the best way to design a particular area.
The application has to interact with a series of web services which are not really all that greatly designed, and don't offer much abstraction in and of themselves - basically there is a web service method for each create/update/retrieve/delete operation for each "datatype", and there isn't much of an API beyond that. The web service client needs to know which methods to invoke, and in which order, to be able to create the data it needs to - in other words, there are no "transaction" based methods.
For example, simply to create a new user account requires calling a total of seven different web service methods to set up all of the records in the necessary tables (a user record, adding the correct privileges to that user, setting up the user's billing details, etc).
I'm struggling with the best way to abstract this and encapsulate it within our application. Most of the app follows a standard flow:
request ---> Controller <---> Service/Business-level object <---> DAOs for data access
Within my application, I'm using my own set of "domain objects" to represent and abstract the datatypes defined in the web service WSDL, so that my domain logic is not dependent on the web service types and so that we can abstract and hide whichever details we like.
What I'm looking for some opinions on is the best way to design the "user creation process" I mentioned above as an example. The process to create a "regular user" involves calling seven different web services, as I mentioned, but this is just one "type" of user - we will have to be able to create several different types of users, each of which require different web services to be invoked.
Currently I've only designed this "regular user" creation, as a bit of a proof of concept - I have a domain object User, a UserDao interface which has methods for getUser(name) and createUser(User), and a WebServiceUserDao which implements the UserDao methods and knows how to invoke the above-mentioned seven web service methods. The createUser() method is called by a UserCreationService, which is my business/service-level class, which in turn is invoked by the SignupController.
But to expand this logic in order to be able to create the different user types (which are represented by different values in User.getType(), I'm unsure where to draw the line between the business/service layer class and the DAO. For instance, should I:
Create one UserDao implementation per "user type", so the logic to create each "user type" can be encapsulated in it's own class, and let the UserCreationService decide which UserDao to use? This would correspond to 1 service class : many DAOs.
Should I break the UserDao into smaller pieces, one corresponding to each "record" that needs to be created in the web service / DB, even though my overall application doesn't need to know about each of these individual types? And then have different UserCreationService implementations for the various different "user types"? In other words, this strategy would have a PrivilegesDao, a BillingPlanDao, etc., even though I would have no need for a corresponding Privilege or BillingPlan domain object. This would be many service classes : many DAOs.
Contain all of the logic for which web services need to be called for each "user type" in a single WebServiceUserDao? This would have the drawback of having a very complicated
class (and PMD is already complaining about cyclomatic complexity), but all of this logic would be encapsulated in the one class and might lead to less complication when viewed from an overall API perspective.
One goal that I have with this application is to make sure that if we ever have to change the details of the data persistence, that all we need to do is change the DAO implementations - if we have to start interfacing with a different billing system, I don't want any part of the application to change other than at the DAO-level.
Any opinions? What kind of strategies do you use when deciding where to break down "business logic" versus "data access logic" when they seem to overlap?
What kind of strategies do you use when deciding where to break down "business logic" versus "data access logic" when they seem to overlap?
Maybe you can have three layers instead of two: "one extra level of indirection".
At the top layer, you might have business logic which doesn't know about data-access: this business layer uses classes like User, Account, etc., and maybe some factory methods like User.getAccounts and Account.getOwners.
The bottom layer might be a data-access layer, which is your wrapper around or facade to whatever your data layer is.
Between these two layers, a layer which knows what your business objects are (e.g. User and Account) but not what your business logic is. The middle layer knows your data access layer. The job of your middle layer is to use your data access layer's API to I/O your business objects.
"I'm unsure where to draw the line between the business/service layer class and the DAO."
Aren't we all?
I suggest using an ORM (iBatis, Hibernate, Toplink, etc.). Don't implement your own DAO's.