Parsing the result-set in DAO vs Service layer - spring

Let's consider a use-case of loading a map with from the db.
Even though I use Hibernate, my use-case doesn't require the whole student entity, which is huge, to be loaded. I just need the above pair of values.
When I execute plain sql query using the Hibernate, the response is in the format of List .
Here's my questions.
Q) Should the parsing of that raw result-set take place in DAO layer or Service layer?
My opinion is that as I'm not executing any business logic (like filtering one of those students), the method in the DAO layer itself should parse those results, construct the map, and return that pairs.
Any other insights or fundamentals reg DAO vs Service layer would be highly appreciated.

The rule of thumb I use is:
Only return from your data layer exactly what your service layer is going to use. So in this case, I would parse the list and build your map before returning. All your service layer is interested in is the map so why bother with the rest?

Related

Data conversion pattern with Business Object, DTO and Entity/Domain Object

In my Spring boot project I use hibernate and basically we have three kinds of objects
DTO object which is used in the controller layer.
Business Object - business object is what we use throughout our application.
Entity/Domain Object - which is used in JPA layer.
When we are ready to save the data we turn the Business Object to Domain/Entity Obj
And when we are ready to send it to the client/controller we can convert the entity object to Business Obj and this Business object in turn to DTO Obj.
Ideally I was told that the conversion logic of changing BOs to -> (DTOs and entities) and vice versa reside in the BOs itself?
How do we achieve this in an efficient way? Can anyone help with any examples?
I love to use Mapstruct in all the projects that I am participate in
There are several things that I adore most about it:
Obviously, you spend less time on coding the conversions (have a look at 'MapStruct in 2 Minutes' on the main page)
If you the property names in your class that you want to transform to and from are the same then you write even less of code.
It integrates well with spring, so you don`t need to declare any beans or something, just specify that it is "spring" component model.
You have variety of ways how to map entities - create new, update existing with values from DTO(for example).
Children objects are easily mapped as well. It has internal mechanism that tries to pick up the right mapper method in other mappers. Or you can specify its name yourself arbitrary.
Though you can also have a look at ModelMapper as well. Pretty similar library, but less used by myself. So cannot make any particular advice.
There is no silver bullet for this task, but you can consider using model mapper for that; that's the simple example https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application

Spring Entities should convert to Dto in service?

After a comment of this question. I started to research but I am still confused.
Entities should convert to Dto before return to controller? To me it sounds not really practical.
We are talking about software architecture and as always when we are talking about software architecture there are a thousand ways of doing something and many opinions about what is the best way. But there is no best way, everything has advantages and disadvantages. Keep this in mind!
Typically you have different layers:
A persistence layer to store data
Business layer to operate on data
A presentation layer to expose data
Typically, each layer would use its own kind of objects:
Persistence Layer: Repositories, Entities
Business Layer: Services, Domain Objects
Presentation Layer: Controllers, DTOs
This means each layer would only work with its own objects and never ever pass them to another layer.
Why? Because you want each layer to be separated from the other layers. If you would use entities in your controller, your presentation would depend on how your data is stored. That's really bad. Your view has nothing to do with how the data is stored. It shouldn't even know that or how data is stored.
Think of that: You change your database model, e.g. you add a new column to one of your database tables. If you pass the entities to your controller (or worse: your controller exposes them as JSON), a change at the database would result in a change in your presentation. If the entities are directly exposed as JSON, this might even result in changes in JavaScript or some other clients which are using the JSON. So a simple change in the database might require a change in the JavaScript front end, because you couple your layers very tight. You definitely don't want that in a real project.
How? You doubt that this is practical, so just a small example of how to do that in (pseudo) code:
class Repository {
public Person loadById(Long id) {
PersonEntity entity = loadEntityById(id);
Person person = new Person();
person.setId(entity.getId());
person.setName(entity.getFirstName + " " + entity.getLastName());
return person;
}
}
In this example, your repository would use entities internally. No other layer knows or uses this entities! They are an implementation detail of this particular layer. So if the repository is asked to return a "person", it works on the entity, but it will return a domain object. So the domain layer which works with the repo is save in the case the entities need to be changed. And as you can see in the case of the name, the domain and the database might be different. While the database stores the name in first name and last name, the domain only know a single name. It's a detail of the persistence how it stores the name.
The same goes for controllers and DTOs, just another layer.

What is the pros and cons of using Generic DAO and Generic Service Pattern in Spring MVC with Hibernate

I have a thought to implement Generic DAO and Generic Service in my new project. I have seen lot of examples in the web.
Before start I want to know the pros and cons of using this design pattern.
Can any one tell Is it advisable to use this pattern?
I think, it will be better to have an other opinion about DAO and generic DAO. Some words about Pros (My suggestions are valid if you use ORM, Hibernate for an example, not plain JDBC).
Creates a nice abstraction layer of the actual storage system.
It is a marketing bullshit. In real life we have problems to migrate between various RDBMS (Oracle RDBMS -> PostgreSQL). Not speaking about change of a storage system type (RDBMS -> NoSQL for example).
Provide a more object-oriented view of the persistence layer.
No! It is very hard to do properly. Most DAO implementations have a dozens of methods like
getSomething(String x, String y, String z);
getSomethingOther(String x, String z);
Provide a clean separation between the domain class and code which will perform the data access from databse.[using JDBC,ORM[like
hibernate] or JPA].
May be, but usefulness of this separation is exaggerated.
Once you have the general CRUD flow set, the same layout can be repeated for other DAOs.
It is correct.
Generic DAO design pattern comes into picture when more then one DAO classes wants to communicate with database (as per example CRUD(Create,Read ,Update and Delete) ),with out this design pattern you will end up writing separate code to make database call (using session) for each of your DAO classes which is a tedious work in general because with each new implementation of DAO classes you have to write you own code to deal with database.
Below are some Pros and cons of using Generic DAO.
Note: Details give below are what I have learned from answers given to SO Question Pros and Cons of the use of DAO pattern
Pros
1. Creates a nice abstraction layer of the actual storage system.
2. Provide a more object-oriented view of the persistence layer .
3. Provide a clean separation between the domain class and code which
will perform the data access from databse.[using JDBC,ORM[like
hibernate] or JPA]
4. Once you have the general CRUD flow set, the same layout can be
repeated for other DAOs.
Cons
1. If you handwrite the DAOs, then the code can become tedious and repetitive you have to use code generators/templates and ORM.
Q - Can any one tell Is it advisable to use this pattern?
A- After Observing above pros and cons I used Generic DAO in my application as abstraction layer to communicate with database in Terms Of CRUD which actual helped me reduces lots of duplicate code to do same thing other DAOs.At first it will take time to get used to it of afterwards use of Generic DAO will make you life easy.

Where to format non-standardized data into a standard format (View, Service, or DAO layer)?

I am using Spring MVC for my presentation layer, and am also using Spring for my Service and DAO layers. Normally I would format data in the View layer of MVC (in my case JSPs), but what if the data that is retrieved from the database is not in a standardized format?
For instance, I am pulling phone numbers from one of my company's databases, but they could potentially be in any format (111)-555-1234 or 1115551234, etc. This seems like it would be too much functionality and processing to place in the JSP/View layer. I would prefer to put all of the numbers in the same format somewhere else and then re-format on the View. Where should I format in this situation - Service layer? DAO?
This would also allow me to take advantage of libraries that I could not potentially call from a JSP (or that would not make sense to call from a JSP).
Thanks!
I would have the DAO query methods remove the formatting characters from the phone numbers, and have the presentation layer give them a consistent format (probably in JSP tags). I am not a fan of putting business logic in DAOs, but this seems extremely data-related.
(Actually if the formatting code first removes any pre-existing formatting before doing its own formatting, you might be able to get by without removing formatting characters anywhere else. I just like having things in a canonical form.)
As an alternative to putting the formatting-char-removal in the DAO, if you are using Hibernate then you can create custom user types that remove or insert formatting characters from the phone number attributes.
I generally do formatting, when I map the Model to Value object (VO or whatever you want to call them), mostly in the presentation layer (or i put a layer in between the presentation and service layer, If I have too many things to do). This brings consistency in the format across the application, if that is what you want.
When i want the name to be in camelcase, I do this
BeanUtils.copyProperties(userAccount, userAccountVO, ignoreProperties);
userAccountVO.setName(StringUtilities.convertToCamelCase(userAccountVO.getName()));

Expose IQueryable Over WCF Service

I've been learning about IQueryable and lazy loading/deferred execution of queries.
Is it possible to expose this functionality over WCF? I'd like to expose a LINQ-to-SQL service that returns an IQueryable which I can then perform additional queries on at the client, and finally execute using a .ToList(). Is OData format applicable at all in this context?
If possible, what is the term for this technique and what are some good tutorials I can follow? Thank you.
You should check WCF Data Services which will allow you to define Linq query on the client. WCF Data Services are probably the only solution for your requirement.
IQueryable is still only interface and the functionality depends on the type implementing the interface. You can't directly expose Linq-To-Sql or Linq-To-Entities queries. There are multiple reasons like short living contexts or serialization which will execute the query so the client will get list of all objects instead of the query.
as far as i know, the datacontext is not serializable meaning that you cannot pass it around with WCF
You can use http://interlinq.codeplex.com/ which allows you to send Linq query over WCF.
WCF Data Services only can be using with webHttpBinding and not all Linq queries can be expressed. Writing queries when WCF Data Service is used is not so attractive - requires string expressions such as:
.AddQueryOption("$filter", "Id eq 100");
https://remotelinq.codeplex.com/ is another choice. But it works in AppDomain to scan the Current Assemblies and serialize them. This tech is not suitable to WinRT as no Domains for WinRT App
I've been struggling with the same question, and realized that a well formed question is a problem solved.
IQueryable basically serves to filter the query before sending it to your DB call so instead of getting 1000 records and filter only 10, you get those 10 to begin with. That filtering belongs to your Service Layer, but if you are building an API I would assume you would map it with AND/OR parameters in your URL.
http://{host}/{entity}/q?name=john&age=21.
So you end up with something like this:
Filter:Column1=Value1 > http://{host}/{entity}q?column1=value1 > SELECT *
FROM Entity
WHERE Column1=Value1
MVC > WCF > DB
You can find a very good sample [here]
Lastly, since your payload from the WCF will be most likely a JSON, you can (and should) then deserialize them in your Domain Models inside a collection. It is until this point where the paging should occur, so I would recommend some WCF caching (and since its HTTP, it's really simple). You still will be using LINQ on the WebApp side, just w/o "WHERE" LINQ clause (unless you want to dynamically create the URL expressed above?)
For a complex OR query, you mind end up with multiple WCF queries (1 per "AND") and then concatenate them all together
If it's possible to send IQuerable<> over WCF it's not a good thing security wise, since IQuerable<> could expose stuff like the connection string to the database.
Some of the previous comments seem promising though.

Resources