Related
I am looking into Spring Data JPA. Consider the below example where I will get all the crud and finder functionality working by default and if I want to customize a finder then that can be also done easily in the interface itself.
#Transactional(readOnly = true)
public interface AccountRepository extends JpaRepository<Account, Long> {
#Query("<JPQ statement here>")
List<Account> findByCustomer(Customer customer);
}
I would like to know how can I add a complete custom method with its implementation for the above AccountRepository? Since its an Interface I cannot implement the method there.
You need to create a separate interface for your custom methods:
public interface AccountRepository
extends JpaRepository<Account, Long>, AccountRepositoryCustom { ... }
public interface AccountRepositoryCustom {
public void customMethod();
}
and provide an implementation class for that interface:
public class AccountRepositoryImpl implements AccountRepositoryCustom {
#Autowired
#Lazy
AccountRepository accountRepository; /* Optional - if you need it */
public void customMethod() { ... }
}
See also:
4.6 Custom Implementations for Spring Data Repositories
Note that the naming scheme has changed between versions. See https://stackoverflow.com/a/52624752/66686 for details.
In addition to axtavt's answer, don't forget you can inject Entity Manager in your custom implementation if you need it to build your queries:
public class AccountRepositoryImpl implements AccountRepositoryCustom {
#PersistenceContext
private EntityManager em;
public void customMethod() {
...
em.createQuery(yourCriteria);
...
}
}
There's a slightly modified solution that does not require additional interfaces.
As specificed in the documented functionality, the Impl suffix allows us to have such clean solution:
Define in you regular #Repository interface, say MyEntityRepository the custom methods (in addition to your Spring Data methods)
Create a class MyEntityRepositoryImpl (the Impl suffix is the magic) anywhere (doesn't even need to be in the same package) that implements the custom methods only and annotate such class with #Component** (#Repository will not work).
This class can even inject MyEntityRepository via #Autowired for use in the custom methods.
Example:
Entity class (for completeness):
package myapp.domain.myentity;
#Entity
public class MyEntity {
#Id private Long id;
#Column private String comment;
}
Repository interface:
package myapp.domain.myentity;
#Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {
// EXAMPLE SPRING DATA METHOD
List<MyEntity> findByCommentEndsWith(String x);
List<MyEntity> doSomeHql(Long id); // custom method, code at *Impl class below
List<MyEntity> useTheRepo(Long id); // custom method, code at *Impl class below
}
Custom methods implementation bean:
package myapp.infrastructure.myentity;
#Component // Must be #Component !!
public class MyEntityRepositoryImpl { // must have the exact repo name + Impl !!
#PersistenceContext
private EntityManager entityManager;
#Autowired
private MyEntityRepository myEntityRepository;
#SuppressWarnings("unused")
public List<MyEntity> doSomeHql(Long id) {
String hql = "SELECT eFROM MyEntity e WHERE e.id = :id";
TypedQuery<MyEntity> query = entityManager.createQuery(hql, MyEntity.class);
query.setParameter("id", id);
return query.getResultList();
}
#SuppressWarnings("unused")
public List<MyEntity> useTheRepo(Long id) {
List<MyEntity> es = doSomeHql(id);
es.addAll(myEntityRepository.findByCommentEndsWith("DO"));
es.add(myEntityRepository.findById(2L).get());
return es;
}
}
Usage:
// You just autowire the the MyEntityRepository as usual
// (the Impl class is just impl detail, the clients don't even know about it)
#Service
public class SomeService {
#Autowired
private MyEntityRepository myEntityRepository;
public void someMethod(String x, long y) {
// call any method as usual
myEntityRepository.findByCommentEndsWith(x);
myEntityRepository.doSomeHql(y);
}
}
And that's all, no need for any interfaces other than the Spring Data repo one you already have.
The only possible drawbacks I identified are:
The custom methods in the Impl class are marked as unused by the compiler, thus the #SuppressWarnings("unused") suggestion.
You have a limit of one Impl class. (Whereas in the regular fragment interfaces implementation the docs suggest you could have many.)
If you place the Impl class at a different package and your test uses only #DataJpaTest, you have to add #ComponentScan("package.of.the.impl.clazz") to your test, so Spring loads it.
The accepted answer works, but has three problems:
It uses an undocumented Spring Data feature when naming the custom implementation as AccountRepositoryImpl. The documentation clearly states that it has to be called AccountRepositoryCustomImpl, the custom interface name plus Impl
You cannot use constructor injection, only #Autowired, that are considered bad practice
You have a circular dependency inside of the custom implementation (that's why you cannot use constructor injection).
I found a way to make it perfect, though not without using another undocumented Spring Data feature:
public interface AccountRepository extends AccountRepositoryBasic,
AccountRepositoryCustom
{
}
public interface AccountRepositoryBasic extends JpaRepository<Account, Long>
{
// standard Spring Data methods, like findByLogin
}
public interface AccountRepositoryCustom
{
public void customMethod();
}
public class AccountRepositoryCustomImpl implements AccountRepositoryCustom
{
private final AccountRepositoryBasic accountRepositoryBasic;
// constructor-based injection
public AccountRepositoryCustomImpl(
AccountRepositoryBasic accountRepositoryBasic)
{
this.accountRepositoryBasic = accountRepositoryBasic;
}
public void customMethod()
{
// we can call all basic Spring Data methods using
// accountRepositoryBasic
}
}
This is limited in usage, but for simple custom methods you can use default interface methods like:
import demo.database.Customer;
import org.springframework.data.repository.CrudRepository;
public interface CustomerService extends CrudRepository<Customer, Long> {
default void addSomeCustomers() {
Customer[] customers = {
new Customer("Józef", "Nowak", "nowakJ#o2.pl", 679856885, "Rzeszów", "Podkarpackie", "35-061", "Zamknięta 12"),
new Customer("Adrian", "Mularczyk", "adii333#wp.pl", 867569344, "Krosno", "Podkarpackie", "32-442", "Hynka 3/16"),
new Customer("Kazimierz", "Dejna", "sobieski22#weebly.com", 996435876, "Jarosław", "Podkarpackie", "25-122", "Korotyńskiego 11"),
new Customer("Celina", "Dykiel", "celina.dykiel39#yahoo.org", 947845734, "Żywiec", "Śląskie", "54-333", "Polna 29")
};
for (Customer customer : customers) {
save(customer);
}
}
}
EDIT:
In this spring tutorial it is written:
Spring Data JPA also allows you to define other query methods by
simply declaring their method signature.
So it is even possible to just declare method like:
Customer findByHobby(Hobby personHobby);
and if object Hobby is a property of Customer then Spring will automatically define method for you.
Im using the following code in order to access generated find methods from my custom implementation. Getting the implementation through the bean factory prevents circular bean creation problems.
public class MyRepositoryImpl implements MyRepositoryExtensions, BeanFactoryAware {
private BrandRepository myRepository;
public MyBean findOne(int first, int second) {
return myRepository.findOne(new Id(first, second));
}
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
myRepository = beanFactory.getBean(MyRepository.class);
}
}
Considering your code snippet, please note that you can only pass Native objects to the findBy### method, lets say you want to load a list of accounts that belongs certain costumers, one solution is to do this,
#Query("Select a from Account a where a."#nameoffield"=?1")
List<Account> findByCustomer(String "#nameoffield");
Make sue the name of the table to be queried is thesame as the Entity class.
For further implementations please take a look at this
If you want to be able to do more sophisticated operations you might need access to Spring Data's internals, in which case the following works (as my interim solution to DATAJPA-422):
public class AccountRepositoryImpl implements AccountRepositoryCustom {
#PersistenceContext
private EntityManager entityManager;
private JpaEntityInformation<Account, ?> entityInformation;
#PostConstruct
public void postConstruct() {
this.entityInformation = JpaEntityInformationSupport.getMetadata(Account.class, entityManager);
}
#Override
#Transactional
public Account saveWithReferenceToOrganisation(Account entity, long organisationId) {
entity.setOrganisation(entityManager.getReference(Organisation.class, organisationId));
return save(entity);
}
private Account save(Account entity) {
// save in same way as SimpleJpaRepository
if (entityInformation.isNew(entity)) {
entityManager.persist(entity);
return entity;
} else {
return entityManager.merge(entity);
}
}
}
There is another issue to be considered here. Some people expect that adding custom method to your repository will automatically expose them as REST services under '/search' link. This is unfortunately not the case. Spring doesn't support that currently.
This is 'by design' feature, spring data rest explicitly checks if method is a custom method and doesn't expose it as a REST search link:
private boolean isQueryMethodCandidate(Method method) {
return isQueryAnnotationPresentOn(method) || !isCustomMethod(method) && !isBaseClassMethod(method);
}
This is a qoute of Oliver Gierke:
This is by design. Custom repository methods are no query methods as
they can effectively implement any behavior. Thus, it's currently
impossible for us to decide about the HTTP method to expose the method
under. POST would be the safest option but that's not in line with the
generic query methods (which receive GET).
For more details see this issue: https://jira.spring.io/browse/DATAREST-206
I liked Danila's solution and started using it but nobody else on the team liked having to create 4 classes for each repository. Danila's solution is the only one here that let's you use the Spring Data methods in the Impl class. However, I found a way to do it with just a single class:
public interface UserRepository extends MongoAccess, PagingAndSortingRepository<User> {
List<User> getByUsername(String username);
default List<User> getByUsernameCustom(String username) {
// Can call Spring Data methods!
findAll();
// Can write your own!
MongoOperations operations = getMongoOperations();
return operations.find(new Query(Criteria.where("username").is(username)), User.class);
}
}
You just need some way of getting access to your db bean (in this example, MongoOperations). MongoAccess provides that access to all of your repositories by retrieving the bean directly:
public interface MongoAccess {
default MongoOperations getMongoOperations() {
return BeanAccessor.getSingleton(MongoOperations.class);
}
}
Where BeanAccessor is:
#Component
public class BeanAccessor implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static <T> T getSingleton(Class<T> clazz){
return applicationContext.getBean(clazz);
}
public static <T> T getSingleton(String beanName, Class<T> clazz){
return applicationContext.getBean(beanName, clazz);
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanAccessor.applicationContext = applicationContext;
}
}
Unfortunately, you can't #Autowire in an interface. You could autowire the bean into a MongoAccessImpl and provide a method in the interface to access it, but Spring Data blows up. I don't think it expects to see an Impl associated even indirectly with PagingAndSortingRepository.
I faced with this using mongo and spring. So let's assume we use MongoRepository to provided base crud operations, and let's say we need to implement some custom criteria query operation using mongoTemplate. To achieve one interface to inject repository for crud and custom we need to specify:
Custom interface:
public interface UserCustomRepository {
List<User> findAllUsersBySomeCriteria(UserCriteriaRequest criteriaRequest);
}
UserRepository interface 'must' first extends UserCustomRepository and then MongoRepository
#Repository
public interface UserRepository extends UserCustomRepository, MongoRepository<User, ObjectId> {
}
UserRepositoryImpl must have the same name as what crud interface with *Impl suffix.
#Component
#NoArgsConstructor
#AllArgsConstructor(onConstructor = #__(#Autowired))
public class UserRepositoryImpl implements UserCustomRepository {
private MongoTemplate mongoTemplate;
#Override
public List<User> findAllUsersBySomeCriteria(UserCriteriaRequest criteriaRequest){
//some impl
}
}
Let's impl some service - here we inject only UserRepository interface and use methods from crud repository and custom class impl.
#Service
#NoArgsConstructor
#AllArgsConstructor(onConstructor = #__(#Autowired))
public class UserService {
private UserRepository userReposityry;
public List<User> getUserByCriteria(UserCriteriaRequest request) {
userRepository.findById(request.getUserId); // Crud repository method
userRepository.findAllUsersBySomeCriteria(request); // custom method.
}
}
I extends the SimpleJpaRepository:
public class ExtendedRepositoryImpl<T extends EntityBean> extends SimpleJpaRepository<T, Long>
implements ExtendedRepository<T> {
private final JpaEntityInformation<T, ?> entityInformation;
private final EntityManager em;
public ExtendedRepositoryImpl(final JpaEntityInformation<T, ?> entityInformation,
final EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityInformation = entityInformation;
this.em = entityManager;
}
}
and adds this class to #EnableJpaRepositoryries repositoryBaseClass.
I use SimpleJpaRepository as the base class of repository implementation and add custom method in the interface,eg:
public interface UserRepository {
User FindOrInsert(int userId);
}
#Repository
public class UserRepositoryImpl extends SimpleJpaRepository implements UserRepository {
private RedisClient redisClient;
public UserRepositoryImpl(RedisClient redisClient, EntityManager em) {
super(User.class, em);
this.redisClient = redisClient;
}
#Override
public User FindOrInsert(int userId) {
User u = redisClient.getOrSet("test key.. User.class, () -> {
Optional<User> ou = this.findById(Integer.valueOf(userId));
return ou.get();
});
…………
return u;
}
Quoting https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations
To enrich a repository with custom functionality, you must first define a fragment interface and an implementation for the custom functionality
And Example 32 shows that this is even the case for repositories that do not extend CrudRepository (as in Example 31) or merge multiple repository interfaces (as in Example 33).
It also notes that
The most important part of the class name that corresponds to the fragment interface is the Impl postfix
But forgoes any explanation as to why.
How do custom repositories / repository fragments work, and why isn't an #Repository annotation on an ordinary bean sufficient?
You have basically two options. The first one is to provide an implementation of each repository interface. This can be seen in your examples. In this case you can override the default implementation of a repository for one entity repo. This can be useful to enhance a special entity repository, e.g. for reportings, etc.
The other option is when you want to provide a base implementation for ALL repositories then you need to use base repository fragments. Repository fragments can be very useful when you want to provide only one base implementation for every custom repository. Let me show you an example:
CustomReadRepository:
#NoRepositoryBean
public interface CustomReadRepository<T> extends Repository<T, String> {
public List<T> someMethod();
public List<T> someHighPerformanceMethod();
}
Now let's say we want one interface which combines different repositories and call it DataRepository.
DataRepository:
#NoRepositoryBean
public interface DataRepository<T>
extends CrudRepository<T, String>, CustomReadRepository<T> {
}
The following interface is now the specific repository for an entity which extends the overall repository
#Repository
public interface UserRepository extends DataRepository<UserEntity> {
}
or
#Repository
public interface OrderRepository extends DataRepository<OrderEntity> {
}
And now we want to provide only ONE implementation for all specific repositories (OrderRepository, UserRepository, etc.).
public class CustomReadRepositoryImpl<T> implements CustomReadRepository<T> {
private static final EntityPathResolver resolver = SimpleEntityPathResolver.INSTANCE;
private final JpaEntityInformation<T, ?> entityInformation;
private final EntityManager entityManager;
private final Querydsl entityManager;
public CustomReadRepositoryImpl(JpaEntityInformation<T, ?> entityInformation,
EntityManager entityManager) {
this.entityManager = entityManager;
this.entityInformation = entityInformation;
}
#Override
public List<T> someMethod() {
//do something and return result
}
#Override
public List<T> someHighPerformanceMethod() {
// do some high performance querying here
}
}
So what you basically can do here is to enhance your repositories and provide only one implementation which can be useful e.g. to override Spring's default implementations (in order to make it faster or whatever reason). You also can provide new custom repos and implementations.
To make your fragment implementation accessible in Spring you have to do the following:
CustomRepositoryFactoryBean:
public class CustomRepositoryFactoryBean<T extends Repository<S, I>, S, I>
extends JpaRepositoryFactoryBean<T, S, I> {
public CustomRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
super(repositoryInterface);
}
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new CustomRepositoryFactory(entityManager);
}
this bean should used in the Main class:
Main Class:
#EnableJpaRepositories(repositoryFactoryBeanClass = CustomRepositoryFactoryBean.class)
public class App {
}
and the implementation of the factory:
CustomRepositoryFactory:
public class CustomRepositoryFactory extends JpaRepositoryFactory {
private final EntityManager entityManager;
public CustomRepositoryFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
}
#Override
protected RepositoryFragments getRepositoryFragments(RepositoryMetadata metadata) {
RepositoryFragments fragments = super.getRepositoryFragments(metadata);
if (CustomReadRepository.class.isAssignableFrom(
metadata.getRepositoryInterface())) {
JpaEntityInformation<?, Serializable> entityInformation =
getEntityInformation(metadata.getDomainType());
Object customRepoFragment = getTargetRepositoryViaReflection(
CustomReadRepositoryImpl.class, entityInformation, entityManager);
fragments = fragments.append(RepositoryFragment.implemented(customRepoFragment));
}
return fragments;
}
If you want to see a kind of real example have a look on the question here.
I am following Spring manual to create a Shared Repository to all my sub-repositories to provide more capability in the queries.
However, I am getting "No Property Found exceptions." Basically, I am following step 1.3.2 Adding custom behavior to all repositories from this link http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html
I tried to change names and everything in the repos, however no luck.
Here is my code:
Interface
package com.ang.repository.common;
#NoRepositoryBean
public interface BaseRepositoryCustom<T, ID extends Serializable> extends JpaRepository<T, ID>, QueryDslPredicateExecutor<T>, JpaSpecificationExecutor<T> {
void sharedCustomMethod(ID id);
//Page<T> findAll(String relationship, Pageable paging);
}
Implemenation
package com.ang.repository.common;
public class BaseRepositoryCustomImpl<T, ID extends Serializable>
extends QueryDslJpaRepository<T, ID>
implements BaseRepositoryCustom<T, ID> {
public BaseRepositoryCustomImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
}
public void sharedCustomMethod(ID id) {
// implementation goes here
}
#Override
public Page<T> readPage(TypedQuery<T> query, Pageable pageable, Specification<T> spec) {
return super.readPage(query, pageable, spec);
}
// #Override
// public Page<T> findAll(String relationship, Pageable paging) {
// return null;
// }
}
First Repository
package com.ang.repository.core;
#RepositoryRestResource(collectionResourceRel = "alndomain", path = "alndomain")
#CrossOrigin(maxAge = 3600)
#Repository("customAlnDomainRepository")
public interface AlnDomainRepository extends BaseRepositoryCustom<AlnDomain, Long>{
#Query(value="select * from #{#entityName} e where e.alnName = ?1",nativeQuery=true)
List<AlnDomain> findAllByAlnDomain(String alnDomain);
#Query(value="select * from #{#entityName} e where e.alnName = ?1 and e.name = ?2",nativeQuery=true)
AlnDomain findOneByAlnDomainName(String alnDomain,String name);
}
Exception:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property sharedCustomMethod found for type AlnDomain!
I tried to remove the "Custom" from the naming convention, however no luck.
Solution
My factory bean in step 1.3.2 (Section 4) was not properly set. After debugging, I found out that Spring was not recognising the method as a Custom Method.
I added the following annotation to my main Spring Application class:
#EnableJpaRepositories(repositoryFactoryBeanClass=com.ang.repository.common.BaseRepositoryFactoryBean.class)
Everything is working.
Thanks all.
The name of the base repository implementation should be BaseRepositoryImpl instead of BaseRepositoryCustomImpl :
public class BaseRepositoryImpl<T, ID extends Serializable>
extends QueryDslJpaRepository<T, ID>
implements BaseRepositoryCustom<T, ID> {
public BaseRepositoryCustomImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
}
public void sharedCustomMethod(ID id) {
// implementation goes here
}
#Override
public Page<T> readPage(TypedQuery<T> query, Pageable pageable, Specification<T> spec) {
return super.readPage(query, pageable, spec);
}
}
Solution
My factory bean in step 1.3.2 (Section 4) was not properly being instantiated. After debugging, I found out that Spring was not recognising the method as a Custom Method. RepositoryFactorySupport from Spring was not instantiating the custom Factory Bean.
I added the following annotation to my main Spring Application class:
#EnableJpaRepositories(repositoryFactoryBeanClass=com.ang.repository.common.BaseRepositoryFactoryBean.class)
Everything is working.
Thanks all.
When using the new Spring Data Evans release it's nice to be able to use some of the nice stuff that came with java 8. One of them is default implementations in interfaces. The repository below uses QueryDSL to make queries type safe.
My problem is that before when I wrote this I used the pattern of a separate UserRepositoryCustom interface for the findByLogin and then another class UserRepositoryImpl and in that class I would have the #PersistenceContext to get the current EntityManager.
How do I get the EntityManager when I don't have a class? Is it even possible?
#Repository
public interface UserRepository extends JpaRepository<User, UUID> {
final QUser qUser = QUser.user;
// How do I get the entityManager since this is a interface, i cannot have any variables?
//#PersistenceContext
//EntityManager entityManager;
public default Optional<User> findByLogin(String login) {
JPAQuery query = new JPAQuery(entityManager);
User user = query
.from(qUser)
.where(
qUser.deleter.isNull(),
qUser.locked.isFalse(),
qUser.login.equalsIgnoreCase(login)
)
.singleResult(qUser);
return Optional.ofNullable(user);
}
}
Default methods should only be used to delegate calls to other repository methods. Default methods - by definition - cannot access any state of an instance (as an interface has none). They only can delegate to other interface methods or call static ones of other classes.
Actually, using a custom implementation as described in the reference documentation is the right approach. Here's the short version for reference (in case others wonder, too):
/**
* Interface for methods you want to implement manually.
*/
interface UserRepositoryCustom {
Optional<User> findByLogin(String login);
}
/**
* Implementation of exactly these methods.
*/
class UserRepositoryImpl extends QueryDslRepositorySupport implements UserRepositoryCustom {
private static final QUser USER = QUser.user;
#Override
public Optional<User> findByLogin(String login) {
return Optional.ofNullable(
from(USER).
where(
USER.deleter.isNull(),
USER.locked.isFalse(),
USER.login.equalsIgnoreCase(login)).
singleResult(USER));
}
}
/**
* The main repository interface extending the custom one so that the manually
* implemented methods get "pulled" into the API.
*/
public interface UserRepository extends UserRepositoryCustom,
CrudRepository<User, Long> { … }
Be aware that the naming conventions are important here (but can be customized if needed). By extending QueryDslRepositorySupport you get access to the from(…) method so that you don't have to interact with the EntityManager yourself.
Alternatively you can let UserRepository implement QueryDslPredicateExecutor and hand in the predicates from outside the repository but that'd let you end up with the clients needing to work with Querydsl (which might be unwanted) plus you don't get the Optional wrapper type OOTB.
You don't get the EntityManager in an interface, although you might be able to work around it by doing a lookup.
But why are you even doing this? Spring Data JPA already supports the Optional return type so you don't need to implement it. Spring Data will do it for you.
public interface UserRepository extends JpaRepository<User, UUID> {
Optional<User> findByLoginIgnoreCase(String login) {
}
The code above should be all you need. You could even specify a query with #Query if you would need it.
A Sample can be found here.
What i ended up doing is creating a repository base which has a getEntityManager()
But it isn't all straight forward to get the base class working with spring boot
// DomainRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import javax.persistence.EntityManager;
import java.io.Serializable;
#NoRepositoryBean
public interface DomainRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
EntityManager getEntityManager();
}
Then the implementation
// DomainRepositoryImpl.java
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import javax.persistence.EntityManager;
import java.io.Serializable;
public class DomainRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements DomainRepository<T, ID> {
private EntityManager entityManager;
public DomainRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
super(domainClass, entityManager);
this.entityManager = entityManager;
}
public EntityManager getEntityManager() {
return entityManager;
}
}
But then spring needs to know how to create domain repositories so we need to create a factory.
// DomainRepositoryFactoryBean.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import javax.persistence.EntityManager;
import java.io.Serializable;
public class DomainRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new RepositoryBaseFactory(entityManager);
}
private static class RepositoryBaseFactory<T, I extends Serializable> extends JpaRepositoryFactory {
private EntityManager entityManager;
public RepositoryBaseFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
}
protected Object getTargetRepository(RepositoryMetadata metadata) {
return new DomainRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager);
}
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
// The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory
//to check for QueryDslJpaRepository's which is out of scope.
return DomainRepository.class;
}
}
}
And then to tell spring boot to use this factory when creating repositories
// DomainConfig.java
#Configuration
#EnableJpaRepositories(repositoryFactoryBeanClass = DomainRepositoryFactoryBean.class, basePackages = {"com.mysite.domain"})
#EnableTransactionManagement
public class DomainConfig {
}
and then change the UserRepository to use it instead.
#Repository
public interface UserRepository extends DomainRepository<User, UUID> {
public default Optional<User> findByLogin(String login) {
JPAQuery query = new JPAQuery(getEntityManager());
...
}
}
I am looking into Spring Data JPA. Consider the below example where I will get all the crud and finder functionality working by default and if I want to customize a finder then that can be also done easily in the interface itself.
#Transactional(readOnly = true)
public interface AccountRepository extends JpaRepository<Account, Long> {
#Query("<JPQ statement here>")
List<Account> findByCustomer(Customer customer);
}
I would like to know how can I add a complete custom method with its implementation for the above AccountRepository? Since its an Interface I cannot implement the method there.
You need to create a separate interface for your custom methods:
public interface AccountRepository
extends JpaRepository<Account, Long>, AccountRepositoryCustom { ... }
public interface AccountRepositoryCustom {
public void customMethod();
}
and provide an implementation class for that interface:
public class AccountRepositoryImpl implements AccountRepositoryCustom {
#Autowired
#Lazy
AccountRepository accountRepository; /* Optional - if you need it */
public void customMethod() { ... }
}
See also:
4.6 Custom Implementations for Spring Data Repositories
Note that the naming scheme has changed between versions. See https://stackoverflow.com/a/52624752/66686 for details.
In addition to axtavt's answer, don't forget you can inject Entity Manager in your custom implementation if you need it to build your queries:
public class AccountRepositoryImpl implements AccountRepositoryCustom {
#PersistenceContext
private EntityManager em;
public void customMethod() {
...
em.createQuery(yourCriteria);
...
}
}
There's a slightly modified solution that does not require additional interfaces.
As specificed in the documented functionality, the Impl suffix allows us to have such clean solution:
Define in you regular #Repository interface, say MyEntityRepository the custom methods (in addition to your Spring Data methods)
Create a class MyEntityRepositoryImpl (the Impl suffix is the magic) anywhere (doesn't even need to be in the same package) that implements the custom methods only and annotate such class with #Component** (#Repository will not work).
This class can even inject MyEntityRepository via #Autowired for use in the custom methods.
Example:
Entity class (for completeness):
package myapp.domain.myentity;
#Entity
public class MyEntity {
#Id private Long id;
#Column private String comment;
}
Repository interface:
package myapp.domain.myentity;
#Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {
// EXAMPLE SPRING DATA METHOD
List<MyEntity> findByCommentEndsWith(String x);
List<MyEntity> doSomeHql(Long id); // custom method, code at *Impl class below
List<MyEntity> useTheRepo(Long id); // custom method, code at *Impl class below
}
Custom methods implementation bean:
package myapp.infrastructure.myentity;
#Component // Must be #Component !!
public class MyEntityRepositoryImpl { // must have the exact repo name + Impl !!
#PersistenceContext
private EntityManager entityManager;
#Autowired
private MyEntityRepository myEntityRepository;
#SuppressWarnings("unused")
public List<MyEntity> doSomeHql(Long id) {
String hql = "SELECT eFROM MyEntity e WHERE e.id = :id";
TypedQuery<MyEntity> query = entityManager.createQuery(hql, MyEntity.class);
query.setParameter("id", id);
return query.getResultList();
}
#SuppressWarnings("unused")
public List<MyEntity> useTheRepo(Long id) {
List<MyEntity> es = doSomeHql(id);
es.addAll(myEntityRepository.findByCommentEndsWith("DO"));
es.add(myEntityRepository.findById(2L).get());
return es;
}
}
Usage:
// You just autowire the the MyEntityRepository as usual
// (the Impl class is just impl detail, the clients don't even know about it)
#Service
public class SomeService {
#Autowired
private MyEntityRepository myEntityRepository;
public void someMethod(String x, long y) {
// call any method as usual
myEntityRepository.findByCommentEndsWith(x);
myEntityRepository.doSomeHql(y);
}
}
And that's all, no need for any interfaces other than the Spring Data repo one you already have.
The only possible drawbacks I identified are:
The custom methods in the Impl class are marked as unused by the compiler, thus the #SuppressWarnings("unused") suggestion.
You have a limit of one Impl class. (Whereas in the regular fragment interfaces implementation the docs suggest you could have many.)
If you place the Impl class at a different package and your test uses only #DataJpaTest, you have to add #ComponentScan("package.of.the.impl.clazz") to your test, so Spring loads it.
The accepted answer works, but has three problems:
It uses an undocumented Spring Data feature when naming the custom implementation as AccountRepositoryImpl. The documentation clearly states that it has to be called AccountRepositoryCustomImpl, the custom interface name plus Impl
You cannot use constructor injection, only #Autowired, that are considered bad practice
You have a circular dependency inside of the custom implementation (that's why you cannot use constructor injection).
I found a way to make it perfect, though not without using another undocumented Spring Data feature:
public interface AccountRepository extends AccountRepositoryBasic,
AccountRepositoryCustom
{
}
public interface AccountRepositoryBasic extends JpaRepository<Account, Long>
{
// standard Spring Data methods, like findByLogin
}
public interface AccountRepositoryCustom
{
public void customMethod();
}
public class AccountRepositoryCustomImpl implements AccountRepositoryCustom
{
private final AccountRepositoryBasic accountRepositoryBasic;
// constructor-based injection
public AccountRepositoryCustomImpl(
AccountRepositoryBasic accountRepositoryBasic)
{
this.accountRepositoryBasic = accountRepositoryBasic;
}
public void customMethod()
{
// we can call all basic Spring Data methods using
// accountRepositoryBasic
}
}
This is limited in usage, but for simple custom methods you can use default interface methods like:
import demo.database.Customer;
import org.springframework.data.repository.CrudRepository;
public interface CustomerService extends CrudRepository<Customer, Long> {
default void addSomeCustomers() {
Customer[] customers = {
new Customer("Józef", "Nowak", "nowakJ#o2.pl", 679856885, "Rzeszów", "Podkarpackie", "35-061", "Zamknięta 12"),
new Customer("Adrian", "Mularczyk", "adii333#wp.pl", 867569344, "Krosno", "Podkarpackie", "32-442", "Hynka 3/16"),
new Customer("Kazimierz", "Dejna", "sobieski22#weebly.com", 996435876, "Jarosław", "Podkarpackie", "25-122", "Korotyńskiego 11"),
new Customer("Celina", "Dykiel", "celina.dykiel39#yahoo.org", 947845734, "Żywiec", "Śląskie", "54-333", "Polna 29")
};
for (Customer customer : customers) {
save(customer);
}
}
}
EDIT:
In this spring tutorial it is written:
Spring Data JPA also allows you to define other query methods by
simply declaring their method signature.
So it is even possible to just declare method like:
Customer findByHobby(Hobby personHobby);
and if object Hobby is a property of Customer then Spring will automatically define method for you.
Im using the following code in order to access generated find methods from my custom implementation. Getting the implementation through the bean factory prevents circular bean creation problems.
public class MyRepositoryImpl implements MyRepositoryExtensions, BeanFactoryAware {
private BrandRepository myRepository;
public MyBean findOne(int first, int second) {
return myRepository.findOne(new Id(first, second));
}
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
myRepository = beanFactory.getBean(MyRepository.class);
}
}
Considering your code snippet, please note that you can only pass Native objects to the findBy### method, lets say you want to load a list of accounts that belongs certain costumers, one solution is to do this,
#Query("Select a from Account a where a."#nameoffield"=?1")
List<Account> findByCustomer(String "#nameoffield");
Make sue the name of the table to be queried is thesame as the Entity class.
For further implementations please take a look at this
If you want to be able to do more sophisticated operations you might need access to Spring Data's internals, in which case the following works (as my interim solution to DATAJPA-422):
public class AccountRepositoryImpl implements AccountRepositoryCustom {
#PersistenceContext
private EntityManager entityManager;
private JpaEntityInformation<Account, ?> entityInformation;
#PostConstruct
public void postConstruct() {
this.entityInformation = JpaEntityInformationSupport.getMetadata(Account.class, entityManager);
}
#Override
#Transactional
public Account saveWithReferenceToOrganisation(Account entity, long organisationId) {
entity.setOrganisation(entityManager.getReference(Organisation.class, organisationId));
return save(entity);
}
private Account save(Account entity) {
// save in same way as SimpleJpaRepository
if (entityInformation.isNew(entity)) {
entityManager.persist(entity);
return entity;
} else {
return entityManager.merge(entity);
}
}
}
There is another issue to be considered here. Some people expect that adding custom method to your repository will automatically expose them as REST services under '/search' link. This is unfortunately not the case. Spring doesn't support that currently.
This is 'by design' feature, spring data rest explicitly checks if method is a custom method and doesn't expose it as a REST search link:
private boolean isQueryMethodCandidate(Method method) {
return isQueryAnnotationPresentOn(method) || !isCustomMethod(method) && !isBaseClassMethod(method);
}
This is a qoute of Oliver Gierke:
This is by design. Custom repository methods are no query methods as
they can effectively implement any behavior. Thus, it's currently
impossible for us to decide about the HTTP method to expose the method
under. POST would be the safest option but that's not in line with the
generic query methods (which receive GET).
For more details see this issue: https://jira.spring.io/browse/DATAREST-206
I liked Danila's solution and started using it but nobody else on the team liked having to create 4 classes for each repository. Danila's solution is the only one here that let's you use the Spring Data methods in the Impl class. However, I found a way to do it with just a single class:
public interface UserRepository extends MongoAccess, PagingAndSortingRepository<User> {
List<User> getByUsername(String username);
default List<User> getByUsernameCustom(String username) {
// Can call Spring Data methods!
findAll();
// Can write your own!
MongoOperations operations = getMongoOperations();
return operations.find(new Query(Criteria.where("username").is(username)), User.class);
}
}
You just need some way of getting access to your db bean (in this example, MongoOperations). MongoAccess provides that access to all of your repositories by retrieving the bean directly:
public interface MongoAccess {
default MongoOperations getMongoOperations() {
return BeanAccessor.getSingleton(MongoOperations.class);
}
}
Where BeanAccessor is:
#Component
public class BeanAccessor implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static <T> T getSingleton(Class<T> clazz){
return applicationContext.getBean(clazz);
}
public static <T> T getSingleton(String beanName, Class<T> clazz){
return applicationContext.getBean(beanName, clazz);
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanAccessor.applicationContext = applicationContext;
}
}
Unfortunately, you can't #Autowire in an interface. You could autowire the bean into a MongoAccessImpl and provide a method in the interface to access it, but Spring Data blows up. I don't think it expects to see an Impl associated even indirectly with PagingAndSortingRepository.
I faced with this using mongo and spring. So let's assume we use MongoRepository to provided base crud operations, and let's say we need to implement some custom criteria query operation using mongoTemplate. To achieve one interface to inject repository for crud and custom we need to specify:
Custom interface:
public interface UserCustomRepository {
List<User> findAllUsersBySomeCriteria(UserCriteriaRequest criteriaRequest);
}
UserRepository interface 'must' first extends UserCustomRepository and then MongoRepository
#Repository
public interface UserRepository extends UserCustomRepository, MongoRepository<User, ObjectId> {
}
UserRepositoryImpl must have the same name as what crud interface with *Impl suffix.
#Component
#NoArgsConstructor
#AllArgsConstructor(onConstructor = #__(#Autowired))
public class UserRepositoryImpl implements UserCustomRepository {
private MongoTemplate mongoTemplate;
#Override
public List<User> findAllUsersBySomeCriteria(UserCriteriaRequest criteriaRequest){
//some impl
}
}
Let's impl some service - here we inject only UserRepository interface and use methods from crud repository and custom class impl.
#Service
#NoArgsConstructor
#AllArgsConstructor(onConstructor = #__(#Autowired))
public class UserService {
private UserRepository userReposityry;
public List<User> getUserByCriteria(UserCriteriaRequest request) {
userRepository.findById(request.getUserId); // Crud repository method
userRepository.findAllUsersBySomeCriteria(request); // custom method.
}
}
I extends the SimpleJpaRepository:
public class ExtendedRepositoryImpl<T extends EntityBean> extends SimpleJpaRepository<T, Long>
implements ExtendedRepository<T> {
private final JpaEntityInformation<T, ?> entityInformation;
private final EntityManager em;
public ExtendedRepositoryImpl(final JpaEntityInformation<T, ?> entityInformation,
final EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityInformation = entityInformation;
this.em = entityManager;
}
}
and adds this class to #EnableJpaRepositoryries repositoryBaseClass.
I use SimpleJpaRepository as the base class of repository implementation and add custom method in the interface,eg:
public interface UserRepository {
User FindOrInsert(int userId);
}
#Repository
public class UserRepositoryImpl extends SimpleJpaRepository implements UserRepository {
private RedisClient redisClient;
public UserRepositoryImpl(RedisClient redisClient, EntityManager em) {
super(User.class, em);
this.redisClient = redisClient;
}
#Override
public User FindOrInsert(int userId) {
User u = redisClient.getOrSet("test key.. User.class, () -> {
Optional<User> ou = this.findById(Integer.valueOf(userId));
return ou.get();
});
…………
return u;
}