Spring Data JPA underlying mechanism without implementation - spring

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.

Related

"The method findById is undefined for the type" after migrating to Boot 3

I have the following Spring Data JPA repository:
public interface FooRepository extends PagingAndSortingRepository<Foo, Long> {}
And after migrating to Spring Boot 3, I started getting Error messages for most standard repository methods (e.g. fooRepository.findById(id), fooRepository.save(foo), fooRepository.findAll())
I couldn't find anything related to this in the Spring Boot 3.0 Migration Guide
It seems that Spring Data 3.0 has now separated the "Sorting" repositories from the base ones (i.e. PagingAndSortingRepository and other interfaces don't extend CrudRepository anymore), and so, we have to make our repositories extend more than one framework repo interfaces, combining them as we want to.
A cause for this is that Spring Data JPA has introduced a ListCrudRepository interface now that retrieves List results instead of Iterable as the CrudRepository did (which in many cases was a pain to deal with).
So, with this unbinding, we can now choose to combine PagingAndSortingRepository with CrudRepository as was the previous behavior, or instead use it with ListCrudRepository.
All this is explained in this Spring Data Announcement post, and also in the Spring Data 3.0 docs:
Note that the various sorting repositories no longer extended their respective CRUD repository as they did in Spring Data Versions pre 3.0. Therefore, you need to extend both interfaces if you want functionality of both.

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.

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)

Spring Data JPA like project not dependent on Spring

Does anyone know any Java frameworks that follows the repository approach with automatic implementation of query methods (e.g. findByNameAndLastName(…)) but not tied to Spring, only pure JPA. Such feature also exists in GORM. I would like to see if there is any project that can be used in Guice or pure JavaEE environment without bringing Spring as a dependency.
(Disclaimer: I am the author of Spring Data JPA)
There is the CDI Query Module which is very similar to what Spring Data JPA. There's also a DeltaSpike module.
Note that Spring Data JPA ships with a CDI extension that creates repository proxies as plain CDI beans and does not bootstrap a Spring container. There are APIs that allow the creationg of repository proxies programmatically such as:
EntityManager em = // … obtain EntityManager
JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
UserRepository repository = factory.getRepository(UserRepository.class);
Yes, it still requires Spring libraries to be present on the classpath but it is then using them similar to how you would use Commons Collection or the like. We try not to reinvent the wheel and the Spring libraries we depend on provide a lot of useful code that we do not have to re-code.
So if it's Spring as DI container you're worrying about, feel free to give the CDI extension of Spring Data JPA a choice. If you don't want to use any Spring whatsoever (for whatever reason), have a look at the alternatives.
Based on Oliver's information, followed up as also interested in this topic --
CDI Query joining Deltaspike mail thread: http://apache-deltaspike-incubator-discussions.2316169.n4.nabble.com/Porting-the-CDI-Query-extension-project-to-DeltaSpike-td4329922.html
Deltaspike base link: http://deltaspike.apache.org/index.html
Getting started: http://deltaspike.apache.org/documentation.html
Just did their 0.4th release as of 5/31/2013.
However, have not done enough of a review to contrast/compare Deltaspike versus Spring-Data w/ CDI extensions (spring-data being very mature).
Take a look at Tomato on github!
It is a functional replacement for Spring JPA, has zero dependencies, performs better and is far easier to use. It will reduce your data access code by 98% and deliver the results you want right out of the box.
https://rpbarbati.github.io/Tomato.
If you want free, fully functional dynamic forms and/or tables for any Tomato entity or hierarchy, that can also be customized easily, try the angular based companion project...
https://rpbarbati.github.io/Basil
Both are current, maintained projects.
Try it yourself, or contact the author at rodney.barbati#gmail.com with questions.

Which class implements the spring roo repository interface

I am new to spring roo, and now, I am building a small project using spring roo 1.2.0.M1, and I fins=d that when I create a jpa repository using repository jpa, I only see the interface has been created, but I cannot find the class which implements that interface.
Another thing is I want to add #PersistenceContext to repository to specify which persistence context it should use. Because I cannot find the implement class, I cannot find out a way to do this.
If someone knows how to do this, please help me!
Thanks in advance!
This sounds like roo uses Spring Data JPA which works exactly that way: you define an interface using fixed name conventions, and at runtime the implementation proxy is generated for you based on the method name and return type (similar to the scaffolding approach of rails / grails).
Here's blog post that explains the mechanism:
GETTING STARTED WITH SPRING DATA JPA

Resources