Understanding CrudRepository - spring

I'm new to Spring and spring boot and i'm trying to understand how stuff works as much as I can. There's something I don't seem to get. After extending the CrudRepository interface on the Repository Layer, methods from this interface can be called and used by the service layer ( by using an instance of the interface which extends it). Since methods are not implemented in interfaces, and from what I know no code is written to implement these methods, how come we are able to use them ?

Related

Spring Boot Repository [duplicate]

I have been working with Spring Data JPA repository in my project for some time and I know the below points:
In the repository interfaces, we can add the methods like findByCustomerNameAndPhone() (assuming customerName and phone are fields in the domain object).
Then, Spring provides the implementation by implementing the above repository interface methods at runtime (during the application run).
I am interested on how this has been coded and I have looked at the Spring JPA source code & APIs, but I could not find answers to the questions below:
How is the repository implementation class generated at runtime & methods being implemented and injected?
Does Spring Data JPA use CGlib or any bytecode manipulation libraries to implement the methods and inject dynamically?
Could you please help with the above queries and also provide any supported documentation ?
First of all, there's no code generation going on, which means: no CGLib, no byte-code generation at all. The fundamental approach is that a JDK proxy instance is created programmatically using Spring's ProxyFactory API to back the interface and a MethodInterceptor intercepts all calls to the instance and routes the method into the appropriate places:
If the repository has been initialized with a custom implementation part (see that part of the reference documentation for details), and the method invoked is implemented in that class, the call is routed there.
If the method is a query method (see DefaultRepositoryInformation for how that is determined), the store specific query execution mechanism kicks in and executes the query determined to be executed for that method at startup. For that a resolution mechanism is in place that tries to identify explicitly declared queries in various places (using #Query on the method, JPA named queries) eventually falling back to query derivation from the method name. For the query mechanism detection, see JpaQueryLookupStrategy. The parsing logic for the query derivation can be found in PartTree. The store specific translation into an actual query can be seen e.g. in JpaQueryCreator.
If none of the above apply the method executed has to be one implemented by a store-specific repository base class (SimpleJpaRepository in case of JPA) and the call is routed into an instance of that.
The method interceptor implementing that routing logic is QueryExecutorMethodInterceptor, the high level routing logic can be found here.
The creation of those proxies is encapsulated into a standard Java based Factory pattern implementation. The high-level proxy creation can be found in RepositoryFactorySupport. The store-specific implementations then add the necessary infrastructure components so that for JPA you can go ahead and just write code like this:
EntityManager em = … // obtain an EntityManager
JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
UserRepository repository = factory.getRepository(UserRepository.class);
The reason I mention that explicitly is that it should become clear that, in its core, nothing of that code requires a Spring container to run in the first place. It needs Spring as a library on the classpath (because we prefer to not reinvent the wheel), but is container agnostic in general.
To ease the integration with DI containers we've of course then built integration with Spring Java configuration, an XML namespace, but also a CDI extension, so that Spring Data can be used in plain CDI scenarios.

Spring Boot layer architecture

I am implementing a REST service with Spring Boot and I have an architectural doubt:
I have my #RestController (controller layer) where I check and take the request parameters of my service.
I have a #Service (business layer) where I get some information from other REST services and apply some logic to return it to the controller.
My question is, where is the best place or layer to write the logic to implement the call to the other REST Services and get the objects I need from them?
I am thinking to create another layer, where I provide, through dependency injection, the information to the #Service, is this ok? Is there a better way to do it? Which stereotype annotation would fit in these classes?
I like the dependency inversion principle.
1) Create an interface with the expected baheviour.
2) Create implementation of it as a service, which maps to external dependency.
3) Inject the interface dependency in your business layer and use it.

Why while using Spring Boot I need entities to be serializable?

Simple Spring Boot entity CRUD operations work and do not implement the serializable interface. Almost every example and tutorial is not doing this and still these examples work well. But the official simple code samples use it.
Why is this interface needed and what is the simplest exemplary use case when implementing serializable interface is required?
You don't have to. But looking at the JPA JSR-220 spec there are cases you need to. From the spec:
If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface.
So if you are passing your object via RMI then you will need to implement Serializable. I can also imagine that Serializable might be needed if you are putting your Entities inside the Session which might be serialized to disk on shutdown of the server.

Spring Data JPA underlying mechanism without implementation

I started to read this tutorial: spring boot tutorial
In this I read that under model module they implemented POJOs and Repository interfaces. -> tutorial on github
In Repository interfaces I found two methods without implementations:
findByUsername,
findByAccountUsername.
My questions are:
How does it work when those methods in repository interfaces have no
implementations and those are not inherited from any super class?
Does it work with name conventions and reflections?
Does Spring Data has inmemory database to work with?
(1) How does it work when those methods in repository interfaces have
no implementations and those are not inherited from any super class?
The Repository interfaces are being implemented (backed up) by Spring Container at Runtime.
(2) Does it work with name conventions and reflections?
Yes, it works on naming conventions and spring container uses JDK's proxy classes to intercept the calls to the Repository.
(3) Does Spring Data has inmemory database to work with?
No, Spring does not use any inmemory database
Please refer the below link for more detailed explanation:
How are Spring Data repositories actually implemented?
For your question 1 and 2, they are right. They use naming convention and reflection. If you don't want to use their naming convention, you can use #Query with HQL, and certainly the hidden class (which implements for your interface) will handle these query also (you don't need to roll the implementation out).
For your last question, as list of IMDB here: https://en.wikipedia.org/wiki/List_of_in-memory_databases , spring data is not supporting for them. You must invoke another Java driver or spring product for each one.

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.

Resources