Am implementing a custom all Spring Data Jpa repository like
#NoRepositoryBean
public interface TenantAwareRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {
#Override
Page<T> findAll(Pageable pageable);
}
and implemented it like
#Slf4j
public class TenantAwareRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements UserAwareRepository<T, ID>{
#Autowired
private ResourceServerTokenServices defaultTokenServices;
private final EntityManager entityManager;
public TenantAwareRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
// Keep the EntityManager around to used from the newly introduced methods.
this.entityManager = entityManager;
}
public Page<T> findAll(Pageable pageable){
OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
log.info("Token = {}", details.getTokenValue());
return null;
}
}
Unfortunately defaultTokenServices does not get injected and is null. How do I inject a spring bean in a custom-all repository implementation.
I am trying to add custom behavior to all repositories:
Ths issue is that TenantAwareRepositoryImpl class should implement TenantAwareRepository like shown below:
#Component
#Slf4j
public class TenantAwareRepositoryImpl<T, ID extends Serializable>
extends SimpleJpaRepository<T, ID> implements TenantAwareRepository<T, ID>{
//add your code here
}
Related
So I'm trying to extend a repository for some custom implementation. The code was working before when I had:
repositoryBaseClass = AccountRepositoryImpl.class
in the PGConfig.java class, but now multiple custom implementations have to be made and I can't have multiple repositoryBaseClass classes defined.
So when I run just a basic test, I'm getting this exception:
log:
...
Caused by: NoSuchBeanDefinitionException: No qualifying bean of type 'JpaEntityInformation<?, ?>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
I tried to follow the example laid out here: Baeldung tutorial
But I'm trying to deviate from it because I need another implementation class for a different repository.
I've tried multiple different things including adding #Autorwired to the EntityInformation member variable, but that didn't work. Not sure what I'm doing wrong, or if what I'm doing is possible?
Both the repositories and impl java files are in the same directory
PGConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
transactionManagerRef = "postgresTransactionManager",
entityManagerFactoryRef = "postgresEntityManagerFactory",
basePackages = {"org.user.domain"}
repositoryImplementationPostfix="Impl")
...
AccountRepository.java:
#Repository
public interface AccountRepository extends AccountRepositoryCustom<Account, Long> {
Optional<Account> findById(String id);
#Override
List<Account> findAllById(Iterable<Long> ids, Sort sort);
}
AccountRepositoryCustom.java
#NoRepositoryBean
public interface AccountRepositoryCustom<E, I extends Serializable> extends JpaRepository<E, I> {
Page<I> findAllAccounts(Specification<E> specification, Pageable pageable);
Page<I> findAllAccounts(Pageable pageable);
List<E> findAllById(Iterable<I> ids, Sort sort);
}
AccountRepositoryImpl.java
public class AccountRepositoryImpl<E, I extends Serializable> extends SimpleJpaRepository<E, I> implements AccountRepositoryCustom<E, I> {
private final JpaEntityInformation<E, I> entityInformation;
private final EntityManager entityManager;
public AccountRepositoryImpl(JpaEntityInformation<E, I> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityInformation = entityInformation;
this.entityManager = entityManager;
}
#Override
public Page<I> findAllAccounts(Specification<E> specification, Pageable pageable) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(entityInformation.getIdType());
...
}
#Override
public Page<I> findAllAccounts(Pageable pageable) {
return findAllUserAccounts(null, pageable);
}
#Override
public List<E> findAllById(Iterable<I> ids, Sort sort) {
...
}
}
public interface AccountRepository extends CrudRepository<AccountDBModel, Long> {
#Modifying
#Query(value = PortfolioQuery.ACCOUNT_INSERT)
void insert(#Param("exchangeId") Long exchangeId, #Param("name") String name, #Param("siteAccount") String siteAccount,
#Param("memo") String memo, #Param("createdAt") Long createdAt, #Param("updatedAt") Long updatedAt,
#Param("isActive") Boolean isActive);
#Modifying
#Query(value = PortfolioQuery.ACCOUNT_UPDATE)
void update(#Param("id") Long id, #Param("exchangeId") Long exchangeId, #Param("name") String name,
#Param("siteAccount") String siteAccount, #Param("memo") String memo, #Param("updatedAt") Long updatedAt,
#Param("isActive") Boolean isActive);
#Query
Optional<AccountDBModel> findByName(#Param("name") String name);
}
#Service
public class AccountService {
private final AccountRepository repository;
#Autowired
public AccountService(AccountRepository repository) {
this.repository = repository;
}
public void postAccount(AccountBaseModel baseModel) throws Exception {
Long now = System.currentTimeMillis();
this.repository.insert(baseModel.getExchangeId(), baseModel.getName(), baseModel.getSiteAccount(),
baseModel.getMemo(), now, now, baseModel.getIsActive());
}
}
#SpringBootTest
class WaveBackofficeApiApplicationTests {
#Autowired
private ApplicationContext applicationContext;
#Test
public void contextLoads() throws Exception {
if (applicationContext != null) {
String[] beans = applicationContext.getBeanDefinitionNames();
for (String bean : beans) {
System.out.println("bean : " + bean);
}
}
}
}
As you can see in AccountRepository interface I didn't use #Repository in AccountRepository interface.
But why is it registered as a bean in Spring Container?
There are no other class like AppConfig.
The interface itself is not registered as a bean. spring framework provides existing implementation of a repository bean (default impl is the class SimpleJpaRepository), which gets injected based on the specifications you provide in your interface. This specific class has the #Repository annotation and will be picked up by spring as a bean.
A simple overview:
#Repository
public class SimpleJpaRepository<T, ID> implements JpaRepositoryImplementation<T, ID> {
// code
}
public interface MyRepository extends CrudRepository<T, ID> {}
#Service
public MyService() {
#Autowired private MyRepository myRepository;
}
In the example above, our own repository interface extends CrudRepository, which has an implementation class named SimpleJpaRepository (provided in the framework), and SimpleJpaRepository is registered as a bean. In MyService, we just tell that we want a bean of type MyRepository, and Spring will inject an instance of SimpleJpaRepository.
You created interface called AccountRepository and extended (thus inherited) CrudRepository.
Now just do Ctrl + Left mouse click on CrudRepository, you will end up in it:
#NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S entity);
<S extends T> Iterable<S> saveAll(Iterable<S> entities);
Optional<T> findById(ID id);
boolean existsById(ID id);
Iterable<T> findAll();
Iterable<T> findAllById(Iterable<ID> ids);
long count();
void deleteById(ID id);
void delete(T entity);
void deleteAllById(Iterable<? extends ID> ids);
void deleteAll(Iterable<? extends T> entities);
void deleteAll();
}
Intellij actually gives you oportunity to find the implementations of all those methods with arrow down mark on the left side.
So there is a huge class called SimpleJpaRepository that has all the implementations, the actual code.
AND THE THING IS...
SimpleJpaRepository.class does have #Repository in it:
#Repository
#Transactional(
readOnly = true
)
public class SimpleJpaRepository<T, ID> implements JpaRepositoryImplementation<T, ID> {
I configured a Spring Data JPA Custom Method extending my app repository functionalities. I referenced this tutorial link and It works properly. I implemented the custom method because I have to set the user in all the JPA Entities before persisting.
This is the BaseRepository interface.
#NoRepositoryBean
public interface BaseRepository<T extends AuditableBean, ID extends Serializable> extends CrudRepository<T, ID> {
<S extends T> S save(S bean);
}
This is the BaseRepository Implementation
public class BaseRepositoryImpl <T extends AuditableBean, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseRepository<T, ID> {
#Inject private CloudContextProvider cloudContextProvider; // <-- I inject this component here but it is null.
private final EntityManager entityManager;
public BaseRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
super(domainClass, entityManager);
this.entityManager = entityManager;
}
public BaseRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityManager = entityManager;
}
public T populateUser(T t) {
t.setUpdaterUser(cloudContextProvider.getUserId());// <-- Here throws a NPE
return t;
}
#Transactional
#Override
public <S extends T> S save(S bean) {
this.auditUser(bean);// <-- This is the custom method.
return super.save(bean);
}
public T auditUser(T t) {
t = populateUser(t);
return t;
}
}
So the question is, ¿How can I inject the cloudContextProvider component in the BaseRepositoryImpl?.
Is that possible?
Maybe with constructor injection?
I customizei a repository for all my repositories children have the same methods. The code is below the repository implementation.
This interface:
#NoRepositoryBean
public interface BaseMyRepository<T, ID extends Serializable> extends JpaRepository<T, ID>{
List<T> findCustomNativeQuery(String sqlQuery);
}
This implementation class:
public class BaseMyRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseMyRepository<T, ID>{
private final EntityManager entityManager;
public BaseMyRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager){
super(entityInformation, entityManager);
this.entityManager = entityManager;
}
#Transactional
#Override
public List<T> findCustomNativeQuery(String sqlQuery) {
List<T> lista = entityManager.createNativeQuery(sqlQuery, this.getDomainClass()).getResultList();
return lista;
}
}
This my repository:
public interface MyRepository extends BaseMyRepository<SmaempreEntity, Integer>{
}
Now I need to know if is possible do exemplify the code below:
#Service
#Transactional
public class MyBaseService<R extends BaseMyRepository, E> {
#Autowired
private R;
public List<E> findAll() {
return R.findAll();
}
public List<E> findCustomNativeQuery(String sqlQuery) {
return R.findCustomNativeQuery(sqlQuery);
}
}
public class MyService extends MyBaseService<MyRepository, MyEntity> {
}
I'm building a small application using Spring and Spring Data JPA and I need to use the CrudRepository methods in the service layer, so I made 2 classes: GenericService and GenericServiceImpl. But I don't know if this is the right or even the best approach.
Here is an example:
POJO:
#Entity
public class User {
#Id
private Long id;
private String username;
}
DAO:
public interface UserDAO extends CrudRepository<User, Long> {
User findOneByUsername(String username);
}
Generic service
public interface GenericService<T, ID extends Serializable> {
<S extends T> S save(S entity);
}
Service
public interface UserService extends GenericService<User, Long> {
User findOneByUsername(String username);
}
Generic service impl.
public class GenericServiceImpl<T, ID extends Serializable> implements GenericService<T, ID> {
#Autowired
private CrudRepository<T, ID> repository;
#Override
public <S extends T> S save(S entity) {
return repository.save(entity);
}
}
Service Impl.
#Service
#Transactional
public class UserServiceImpl extends GenericServiceImpl<User, Long> implements UserService {
#Autowired
private UserDAO userDAO;
#Override
public User findOneByUsername(String username) {
userDAO.findOneByUsername(username);
}
}
Yes, you're providing your own impl that's may do custom things while still reusing the Derived queries from Spring JPA's CrudRepository. I've seen that a lot. :) We need to do that if we want to do our own computation before calling the Derived methods. After all, that computation may very well be part of a repository, so it doesn't make sense to put that logic in the service. But in your scenario, if there are no such custom computations, then this indirection isn't needed. As a commenter mentioned, you should directly use the UserDao interface. :)