When we speak of command objects in Grails and even in Spring, are they the same as data transfer objects? Meaning, is a command object an example of the implementation of the DTO enterprise design pattern? If not, what is the difference?
A data transfer object (DTO) is an object (simple java bean) that carries data between any two layers or processes. You might generally introduce/use DTO layer & populate the DTO bean with the data received from an external web service or external system. Refer Martin Fowler's blog on Data Transfer Object for more details
Command object is just a spring (mvc) terminology which maps the html form data to a java bean (form bean). Here Spring Dispatcher servlet & helper classes map the data from html form to the java bean. In Grails, command objects do serve more than data carriers like AST transformation.
In summary, they both are data carriers from one layer to the other.
Is a command object in Spring an example of the implementation of the DTO enterprise design pattern ?
Yes, but the point to note is that the Spring Dispatcher servlet &
helper classes populate the command object with html form data.
Related
Suppose I've a bunch of microservices, each written on SpringBoot MVC (REST, Controller, Service, etc..)
Can anybody explain what is DDD's Aggregate in SpringBoot MVC? is it a controller? Or is it a specific microservice which is a root for some other microservices?
In other words, is aggregate something within a service with a controller's endpoint as a root? or is aggregate a sub-set of microservices with a particular SpringBoot application/service as an entry point to them?
It is neither a controller nor specific microservice.
It is a cluster of the domain objects that can be treated as a single unit (e.g. Order and its order line) (see this) which is retrieved , saved and searched by the repository.
The spring framework also provides an more specialised #Component called #Repository to represent the repository concepts (quoted from its javadoc) :
Indicates that an annotated class is a "Repository", originally
defined by Domain-Driven Design (Evans, 2003) as "a mechanism for
encapsulating storage, retrieval, and search behavior which emulates a
collection of objects".
Teams implementing traditional Java EE
patterns such as "Data Access Object" may also apply this stereotype
to DAO classes, though care should be taken to understand the
distinction between Data Access Object and DDD-style repositories
before doing so. This annotation is a general-purpose stereotype and
individual teams may narrow their semantics and use as appropriate.
As we use repository to save JPA #Entity or MongoDB #Document to the underlying datastore , so DDD aggregate is more align to them
Two things here.
Spring MVC is a boundary layer to translate between HTTP and internals of the app. The internals are where all the DDD happens, not the boundary itself
Spring Boot is for bootstrapping an application with all the common tools and making a runnable deployment unit.
So, in case of DDD an HTTP request comes to Spring MVC layer, there a domain request is instantiated and passed to domain core for execution. Domain response then comes back and is translated into HTTP response by Spring MVC layer.
I do REST API on Spring. Took a course in Spring Data Hibernate and found that it made the REST API the most time-consuming way.
When I added a new entity to the domain, I went through the following chain of objects:
Entity - domain object
DTO - for transmitting/receiving an object to/from a client
Mapper - to convert between Entity and DTO
Repository - for interacting with the database
RestController - for processing API requests
Service - service class for the object
The approximate chain of my actions was as follows:
RestController processes requests - receives DTO from the client (in case of creation of a new object)
Mapper in controller converts DTO to Entity
Service is called
Service accesses the Repository
Repository returns the result of execution (created by Entity)
Service returns Entity is created in RestController
RestController returns to the client an object of type ResponseEntity, where I put the body and response code.
As you can see a large chain of actions and a large number of objects.
But then I found out that if you use Spring Data REST, all this doesn't need all the API supplied by Spring from the box. In general, you only need to create an Entity and Repository.
It turns out that for typical CRUD-type operations, I wrote a lot of controllers and their methods in vain.
Questions:
When should I use RestConroller, and when is Spring Data REST?
Is it possible to combine two approaches for one Entity? It turns out that I was wasting my time writing for simple operations like creating, getting, saving, deleting controllers, it can be moved to Spring Data REST.
Will I be able to implement some of the actions that I did in Spring Data Rest in RestConroller? Such as:
Return an entity property value as id instead of object? I mean I have properties for entities that are entities themselves, for these fields I sometimes need to return their ID instead of the whole entity.
Is there any way to control error handling? In RestController I have implemented the ResponseEntityExceptionHandler extension class and all errors wherever they occur in my RestController are handled in the same way in one place and I always know that all errors will return approximately the same response structure.
Data validation will have to be hinged on the fact that it used to be validated on DTOs received from the client. Are there any nuances waiting for me in this regard?
I'm a little stumped on how to move forward. Give me your recommendations and thoughts on this. Push forward on what to use and how.
What Spring Data REST can do for you is scaffolding of the plain repository to rest service. It is much faster, and in theory it should be flexible, but in practice it is hard to achieve something more than REST access to your repositories.
In production I've used Spring Data REST as a wrapper of the database - in a service/microservice architecture model you just wrap-up sometimes the core DB into such layer in order to achieve DB-agnostic Application. Then the services will apply the business logic on top of this wrapper and will provide API for the front-end.
On the other hand Spring Data Rest(SDR) is not suitable if you plan to use only these generated endpoints, because you need to customize the logic for fetching data and data manipulation into Repoitories/Services. You can combine both and use SDR for the "simple" entities, where you need only the basic CRUD over them, and for the complex entities to go with the standard approach, where you decouple the entity from the endopint and apply your custom business logic into the services. The downside of mixing up both strategies is that your app will be not consistent, and some "things" will happen out-of-the-box, which is very confusing for a new developer on this project.
It loooks wasted time and efforts to write these classes yourself, but it only because your app doesn' have a complex database and/or business logic yet.
In short - the "standard" way provides much bigger flexibility at the price of writing repetetive code in the beginning.
You have much more control building the full stack on your own, you are using DTO's instead of returning the entity objects, you can combine repositories in your services and you can put your business logic on the service layer. If you are not doing anything of the above (and you don't expect to in the near future) there is no need for writing all that boilerplate yet over again, and that's when Spring Data REST comes into play.
This is an interesting question.
Spring Data Rest provides abstraction and takes a most of the implementation in its hand. This is helpful for small applications where the business logic resides at the repository layer. I would choose this for applications with simple straight forward business logic.
However if I need fine grained control (eg: transaction, AOP, unit testing, complex business decisions etc. ) at each of the layers as you mentioned which is most often needed for large scale applications I will prefer writing each of these layers.
There is no thumb rule.
By default Spring Data Repositories process database Entities. Please, suggest the standard approach of getting same functionality with Spring Data framework, which allows you operating on your Business Domain Objects (DTO) instead of Entities, and encapsulates all DTO to/from Entity mappings.
My current obvious options are:
Additional "proxy-wrapper" where all methods have same names as in Spring Repository but accept and return DTO types and encapsulate conversions(mappings).
Some clever implementation of previous option using AOP with less boilerplate code.
Both options seem pretty awkward to me for such a standard task. So, I assume I am jut missing something here.
I am asking because I have only seen java beans used with a framework like struts or JSF.
Is it possible to send and access a java bean over an AJAX request?
Servlet myServlet creates and fills a java bean instance, and sets it in the request scope. An already loaded jsp/html page uses AJAX to request data from myServlet. Can this bean be accessed in any way? After thinking for a while, I have come to accept that this cannot be done.
If it can't be done, what would be the best practice when trying to transmit data from a model (i.e. user information from a database) asynchronously to a client when using Tomcat/Servlets and JSP?
It's technically possible if you serialize the javabean to a byte array or even a base64 encoded string using the usual Java Serialization API.
But how would it ever make sense to use a proprietary format to transfer data around? How would non-Java clients (e.g. JavaScript!) ever be able to consume the serialized Java object? These days XML, JSON and even CSV are much more widely supported and accepted. Practically every self-respected programming language has tools to easily convert between XML/JSON/CSV and the model as definied in the programming language in question. E.g. Java has JAX-RS API to easily convert between javabeans and XML or JSON. JavaScript has —obviously— builtin support for JSON (guess what "JS" in JSON stands for).
To learn and play around with the basic concept, head to this answer: How to use Servlets and Ajax?
To learn about the advantages of JAX-RS over servlet, head to this answer: Servlet vs RESTful
You can still use struts or jsf as you would normally to construct markup(html). And then consume the markup that was constructed via ajax and then append to the dom. If you are familiar with jQuery, something like jQuery('#selector').load('actionUrl.action');
But if you are looking to examine a java bean, then you will have to serialize it to xml or json. If you are using a web framework like struts2 or spring, there is likely a mechanism for doing this serialization for you. If you want to edit the bean you will have to serialize, then edit the serialized bean, and then deserialize back to the java bean.
we are using EJB3 in our application. Our design aim is to separate persistence layer from Business Layer. So we have developed XXXbean classes to be used as SLSB and XXXRepository classes to be used as persistence classes. We also have POJO that implement reusable NON business logic(get list of countries etc) and we call then service/helper Classes.
We use EJB3 JPA (using Hibernate provider) and Repository classes has all the methods for CRUD operation and the get methods for data access. Currently XXXRepository classes are all POJO and we instantiate these classes directly from the bean XXXClasses or from the service Objects.
Should the XXXRepository classes be SLSB ? what would be the benefits and pitfalls of converting them to SLSB?
An EJB is a container managed bean. This means, that the container manages a lot of options like the transaction, security, resource access (e.g. database) and offers possibilities like timers, remote access or interceptors. Another advantage is the pool and the reuse of instances.
I would say, that if you need something from this container managed options like an entity manager, then use an EJB, in your case an SLSB. But if you don't need any of the provided features, then a usual POJO will do that job.
If the XXXRepository classes are no SLSB, how do they access to the database to perform the CRUD operations? Are you using the Hibernate Session directly? How are the transactions managed? It may make sense to transform thes classes in SLSB and use the injected entity manager for this case.
Adam Bien has written a book called Real World Java EE Pattern. In this book he writes about good EJB architectures and also mentions, which classes should be an EJB (for example a ServiceFacade as a transaction boundary) and which classes can be used as POJOs.