DTO vs Formbean - java

I'm developing spring MVC application and I used AirPortForm.java to get information in my airport.jsp. But I'm just wandering what is the standard method do I need to use AirPortDTO.java instead of AirPortForm.java kindly advice me.
Many thanks.

The Form suffix usually indicates that the object is meant to contain values coming from an HTML form (Spring calls these command objects).
The DTO suffix indicates that the object is a Data Transfer Object. A Data Transfer Object is an object, usually without much logic, which is used to carry information between the presentation layer and the service layer.
Use the appropriate suffix for you use-case, or use another one or not at all if your object is neither a form nor a DTO.

DTO use to transfer data between your database and application. Model View Controller (MVC) is one of the design pattern that separate your application with different layers. DTO is in model layer.In your application, you can use AirportFrom.java class only but it is not good practice.

Related

Java-Use of knowing the differences between Entity, Vo, POJO, Javabeans, etc

I (think I) just understood the differences between Java Entity, VO, POJO, Javabeans, DAO, DTO, etc, I mean, the theory. Now, I'm trying to understand the implications of the implementations depending on the needs. Who cares if I create a POJO or a JavaBean? At the beginning I will create a POJO if I have no other constraint, until I realise I must make it a Javabean and deal with it's restrictions.
When do you tell yourself: "I need a DTO"? Only for web services or when any client/server call is made? In that case, do you put all the data you need (and the one you think you will need?) in one DTO bunch?
Lastly, in a MVC model, where does each one go? Can I make an entity or a vo in either layer? Where does the DTO go?
Thank you very much
You understood the difference between them, now you need to understand their purpose.
There is a neat definition for each one in this link.
Who cares if I create a POJO or a JavaBean? At the beginning I will create a POJO if I have no other constraint, until I realise I must make it a Javabean and deal with it's restrictions.
You need to think what the purpose of the class is. Is it a standalone class with no annotations that provides functionality but can be isolated (not counting libraries used)? Then it is likely a POJO.
Is it a class that serves as a bridge between layers of your project? Is it annotated? Does it implement some business logic for your project? Then it is a JavaBean.
When do you tell yourself: "I need a DTO"? Only for web services or when any client/server call is made? In that case, do you put all the data you need (and the one you think you will need?) in one DTO bunch?
DTOs are generally used to share information between layers. Their main purpose is isolating Entities so that you can change how your information is persisted from how the information flows through the different beans and controllers in your project.
To know when I need a DTO and when not I follow these rules:
Does the method more than three parameters? Then use a DTO.
Does the method return more than a single parameter? Then use a DTO.
When passing parameters to method calls / from method results: Does each element have more than one type (for Maps you would look at the value)? Then use a Collection of DTOs.
Otherwise use String, int, Long, etc.
Also never mind reusing DTOs even if most of its fields are not used for a specific method, you won't be wasting much memory if it's properly design. On the other hand, don't worry if you need to create new DTOs that share fields with some others, it might be clearer when reviewing your code. Try to find the right balance between too many DTOs and overpopulated DTOs.
Lastly, in a MVC model, where does each one go? Can I make an entity or a vo in either layer? Where does the DTO go?
It depends on how you structure your project. The term layer is a bit open as it can refer to each of the MVC elements and to the Data/Business/Client architecture (when I used the word layer in this answer, I'm talking about the later classification).
It is a good practice to separate each layer in a different project (specially in large projects). This is a common structure I use for enterprise web applications:
ProjectNameDao: Includes database access methods and entities.
ProjectNameBo: Includes all the business logic. Shares information with the other layers by using DTOs. It is, along ProjectNameDao, the Model in a MVC model.
ProjectNameWeb: Includes views and controllers from the MVC model.
ProjectNameDto: Includes all DTOs.
ProjectNameUtils: Shared utils, normally POJOs that hold constant values or provide basic functionality like Date formatting.
This structure needs to be adapted to whatever your requirements are, of course.

Use database #Entity classes for REST exposure?

#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

Difference b/w passing model and using request object at jsp/gsp

I have been working both on spring and grails (grails is built on spring).
We can pass our data from controller to view (jsp/gsp) via request object or via model.
Passing data via model is preferred because its easy.
Comparison of code :
Spring :
controller request.setAttribute("name","india");
view ${pageContext.request.getAttribute('name')}
controller ModelAndView("viewname",modelObject)
Grails
controller request.setAttribute("name","india")
view ${request.getAttribute("name")}
controller render(view:"viewName",model:[name:"india"])
I think request object does many functionalities other than this.
So my question is : If passing data from controller to view can be done with request object itself why java technology required to make a concept like model ?
necessity is mother of invention
I mean to say that there must be a task that can be implemented only via a model.
A few things come to mind, but they are speculation as to why.
Mainly, separation of concerns. Modifying the request, which is input, to hold output seems to be abusing this. The model is clearly ouput, and only output.
By clearly defining what constitutes output, using a model, frameworks such as Spring and Grails can then apply other processes to only the model. Grails filters come to mind, as an example.
That's my quick opinion.
That data which a controller gathers up and needs to make available to the view should be put in the model. That is kind of the definition of what the model is in this context. Never use request attributes for this.

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.

Spring MVC: should service layer be returning operation specific DTO's?

In my Spring MVC application I am using DTO in the presentation layer in order to encapsulate the domain model in the service layer. The DTO's are being used as the spring form backing objects.
hence my services look something like this:
userService.storeUser(NewUserRequestDTO req);
The service layer will translate DTO -> Domain object and do the rest of the work.
Now my problem is that when I want to retrieve a DTO from the service to perform say an Update or Display I can't seem to find a better way to do it then to have multiple methods for the lookup that return different DTO's like...
EditUserRequestDTO userService.loadUserForEdit(int id);
DisplayUserDTO userService.loadUserForDisplay(int id);
but something does not feel right about this approach. Perhaps the service should not return things like EditUserRequestDTO and the controller should be responsible of assembling a requestDTO from a dedicated form object and vice versa.
The reason do have separate DTO's is that DisplayUserDTO is strongly typed to be read only and also there are many properties of user that are entities from a lookup table in the db (like city and state) so the DisplayUserDTO would have the string description of the properties while the EditUserRequestDTO will have the id's that will back the select drop down lists in the forms.
What do you think?
thanks
I like the stripped down display objects. It's more efficient than building the whole domain object just to display a few fields of it. I have used a similar pattern with one difference. Instead of using an edit version of a DTO, I just used the domain object in the view. It significantly reduced the work of copying data back and forth between objects. I haven't decided if I want to do that now, since I'm using the annotations for JPA and the Bean Validation Framework and mixing the annotations looks messy. But I'm not fond of using DTOs for the sole purpose of keeping domain objects out of the MVC layer. It seems like a lot of work for not much benefit. Also, it might be useful to read Fowler's take on anemic objects. It may not apply exactly, but it's worth thinking about.
1st Edit: reply to below comment.
Yes, I like to use the actual domain objects for all the pages that operate on a single object at a time: edit, view, create, etc.
You said you are taking an existing object and copying the fields you need into a DTO and then passing the DTO as part of the model to your templating engine for a view page (or vice-versa for a create). What does that buy you? The ref to the DTO doesn't weigh any less than the ref to the full domain object, and you have all the extra attribute copying to do. There's no rule that says your templating engine has to use every method on your object.
I would use a small partial domain object if it improves efficiency (no relationship graphs to build), especially for the results of a search. But if the object already exists don't worry about how big or complex it is when you are sticking it in the model to render a page. It doesn't move the object around in memory. It doesn't cause the templating engine stress. It just accesses the methods it needs and ignores the rest.
2nd edit:
Good point. There are situations where you would want a limited set of properties available to the view (ie. different front-end and back-end developers). I should read more carefully before replying. If I were going to do what you want I would probably put separate methods on User (or whatever class) of the form forEdit() and forDisplay(). That way you could just get User from the service layer and tell User to give you the use limited copies of itself. I think maybe that's what I was reaching for with the anemic objects comment.
You should use a DTO and never an ORM in the MVC layer! There are a number of really good questions already asked on this, such as the following: Why should I isolate my domain entities from my presentation layer?
But to add to that question, you should separate them to help prevent the ORM being bound on a post as the potential is there for someone to add an extra field and cause all kinds of mayhem requiring unnecessary extra validation.

Categories