Usecase of Spring DAO - spring

I'm wondering what is the typical usecase of Spring DAO where we can easily switch between different persistence frameworks.
Apart from abstracting the boiler-plate code (for JDBC, Hibernate like) Why does any application want to change its ORM frameworks so frequently?

By using a DAO pattern with a distinct DAO interface, this enables you to mock the DAO implementation. With this you improve testability of your code, as you are then able to write tests that do not need database access.
It is not only about frequently being able to switch between ORM frameworks, but is also about reducing effort if you are enforced to change the ORM.
Another reason is, that you might have different data sources like a database, a webservice or the file system for example. In this case you don't abstract the ORM but simply the persistence mechanism in general.

I think the real important idea behind DAOs are that you have just one spot where all data access related code for a particular entity ist located. That makes testing and refactoring of your persistence layer easier and your code is better readable.
Furthermore, it makes the code better readable. Think of a new developer in your team that should implement a feature. If she needs to access the databasase she would look into the dao for data access methods.
If you scatter the data access code in different services the risk is pretty high that someone produces code duplicates.

Related

Not seeing people use interfaces and #Transactional in their Spring Applications

I have been seeing this trend recently with some Spring Framework developers. When they create their Service classes they are not creating interfaces for them to implement and they are not using #Transactional in their service classes when they are definitely in need of transactions.
Is there a good reason for this?
And one more question, Spring Boot has Session In View set to be true. Why? I always thought that to be a really bad design, allowing for developers to be lazy and allow for N+1 queries to happen all the time and slowing down performance. If you know you are going to need it for the UI, why not query for it in the Service-Repository classes in the least amount of queries instead?
It's true that building Services with interfaces and class implementations has been under questioning lately. There a classic post about this: https://octoperf.com/blog/2016/10/27/impl-classes-are-evil/ .
About Transactions, for read operations the readOnly=true parameter should be included in the #Transactional annotation to make sure it is done properly. As for the write operations, of course the transaction management should be done with care and the #Transactional annotation is there to make sure it is done so. Not using it is certainly a code smell, since a transaction will happen nonetheless, but you just won't have control over it.
Session In View set to true is a code smell too, and it should be used in learning environments or short-term experiments only. Batching, among other possibilities, can and should be used to avoid the N+1 problem.

Should repositories in Spring Boot applications be tested directly?

Not sure if this will be considered a "legitimate question" or "purely opinion based", but is there a "best practice" with regards to directly testing a repository in a Spring Boot application? Or, should any integration testing simply target the associated service?
The reasoning for the question is simply the fact that, for the most part, a repository in a Spring Boot application contains no project-generated code. At best, it contains project-defined method signatures which Spring generates implementations for (assuming correct naming conventions).
Thanks...
If you can mess it up, you should test it. Here the opportunities to mess up can include:
Custom Queries (using #Query) might be wrong (there can be all kinds of logic mistakes or typos writing a query with no compile-time checking)
Repository methods where the query is derived from the method name might not be what you intended.
Arguments passed in, the type on the parameter list might not match the type needed in the query (nothing enforces this at compile time).
In all these cases you're not testing Spring Data JPA, you're testing the functionality you are implementing using Spring Data JPA.
Cases of using provided methods out of the box, like findOne, findAll, save, etc., where your fingerprints are not on it, don't need testing.
It's easy to test this stuff, and better to find the bugs earlier than later.
Yes, I think is a good pratice to do that. You could use #DataJpaTest annotation, it starts a in memory database. The official documentation says:
You can use the #DataJpaTest annotation to test JPA applications. By default, it configures an in-memory embedded database, scans for #Entity classes, and configures Spring Data JPA repositories. Regular #Component beans are not loaded into the ApplicationContext.
Link to the docs: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
Starting from the idea that repositories should be used only inside services and services are used to interact with the other layers of the system, I would say that testing services should be enough in the majority of cases.
I would not test standard repository methods like findAll, or findBy.., they were tested already and the purpose is not to test JPA, but rather the application.
The only repository methods that should have direct tests are the ones with custom queries. These queries may be located in a shared library and it is not efficient to write similar tests across different projects(in this case regression is a big concern)

how to use spring 3.0 without service?

I am using spring 3.0 with annotation which i am creating dao interface , then dao implementation class,
then creating service interface and then creating service implementation class.
and using object of service implementation into controller. this process is too lengthy.
can i use only dao class and directly use it in controller?
#service
#controller
public class MyController { ... }
You can but you really really really shouldn't. If you have any plans of putting this code into production, then you need to keep your layers well defined. This is because each layer has a different responsibility.
Your DAO layer is responsible for all database access. It doesn't care what object you want, what you want to do with it, and when you want it done. It only cares about how it's done.
Your Service layer is responsible for what you want to do to your objects. It contains all of your business logic, convenience methods and may use multiple DAO's inside a single service. Your service layer is where you handle your database transactions as well.
Your controller layer is responsible for how you want to show your data to the user. It only contains services and minimal logic concerned with how to display the data returned by your service layer.
I think there are 2 distinct questions being asked here :
Is it really necessary to have all three layers : web layer, service layer, and DAO ?
and :
Do Spring beans necessarily need to implement and interface and to bve (auto)wired by interface rather thant concrete class ?
The answer to both is the same : it is not a necessity, but it is strongly recommended for anything other thant trivial projects.
For the first question, yes it is better so separate concerns in different layers. However I must admint that my controllers sometimes access the DAOs directly for simple read-only tasks in some projects. Sometimes the service layer seems like too much when all it does is to map the DAO methods. However I always use a service layer for transactional business logic that actually modifies the data.
For the second question : Spring can, without problem, instantiate and inject beans that don't implement any interface. However you will start to have problems if you use more advanced stuff linked to aspect-oriented programming, the most common being the #Transactional annotation. In this case Spring has to create proxies to your objects, and it is all simpler to create proxies of interfaces. Ohterwise it has to manipulate bytecode and it introduces limitations.
Perhaps more importantly, "programming to an interface" is a good practice regardless if you are using Spring or not, or even Java or anothrer language. A simple google search will bring up many good articles on this, or SO questions such as this one.
So again, while you can live well without both things in the short term, both will make your life much better in the long term.

Reasons to use a persistence framework in Java EE?

I'm working on a Java EE Application, and I use Spring as framework.
Now I've seen people talking about ORM Frameworks (Hibernate/JPA/iBatis...) but I don't know what might be the reasons to use those frameworks?
I mean what those frameworks will change in the project functions & performance?
if you can give me a clear example it will be great.
Since you will get bored by writing the SQL insert/update/select statements for entire java objects and keep the Object <-> SQL code in shape when your object changes. JPA is actually a part of the Java EE standard.
However, it will not provide any means to keep you from knowing what you are doing with the database, except for very simple cases. My experience is that any JPA framework will add just another layer of complexity to performance issue track down and debugging.
In the end, you might end up need to understand how JPQL (SQL-ish syntax for JPA) translate into SQL for every combination of JPA provider (OpenJPA, HIbernate, eclipse link..) and datbase implementation. This will be non trivial.
If you have no specific performance requirements and just want easy object persistance, give it go! Hibernate seems to be state of the art atm.
To avoid writing your own SQL for everything, and to [partially] bridge the object-relational gulf ("abyss").
For simple requirements, ORMs are great, and make thinking about some DB stuff go away--with the caveat that you still need to be aware of what's actually happening on the DB side to prevent what can be serious performance implications.
For complicated requirements, you'll learn to understand why they call ORMs the "Vietname of computer science"... "We have learned the lessons of Vietnam... do not go to Vietnam."

Up to date, JPA compliant GenericDAO Implementation

I read this article:
http://www.ibm.com/developerworks/java/library/j-genericdao.html
several times and believe I understand what it is saying. However, it is 4 years old and I have a JPA compliant Java application to contend with. In addition, I see that there is a JPATemplate in Spring that has some good functionality, but the Spring documentation says it is already deprecated!
Can anybody point me to a solid, modern, JPA compliant, Spring based, working example of a GenericDAOImpl that proxies an Interface to provide generic finder execution?
Nowadays JPA 2 in itself has become a decent implementation of a DAO layer since its responsibility (or contract if you wish) is the same as for the traditional "crafted" DAO, that is an isolation of a business logic from a storage mechanism. An important implication out of this is that you may need an explicit DAO only when working with non-DBMS storages like spreadsheet files, web-services, etc.
I've created a generic DAO mixing different approaches that I shared on SO in this question. I use these 2 approaches: DDD: The Generic Repository and JPA implementation patterns: Data Access Objects.
Please feel free to comment/edit if you think it can be improved.

Resources