JpaRepository implementation- Lists vs. Sets - java

I'm building my first Spring Boot app using JPA and have setup my data repositories and services like this:
#Repository
public interface FooRepository extends JpaRepository<Foo, Long> {
Set<Foo> findAllByActiveInstallationIsNull();
}
Then a CrudService
public interface CrudService<T extends BaseEntity> {
Set<T> findAll();
T findById(Long id);
T save(T object);
void delete(T object);
void deleteById(Long id);
}
along with an example class service interface that extends it
public interface FooService extends CrudService<Foo> {
Set<Foo> findAllAvailable();
Foo getIfAvailable(Long id);
}
an abstract class for service implementations
public abstract class AbstractJpaService<T extends BaseEntity, R extends JpaRepository<T, Long>> implements CrudService<T> {
protected R repository;
public AbstractJpaService(R repository) {
this.repository = repository; }
#Override
public Set<T> findAll() {
return new HashSet<>(repository.findAll()); }
#Override
public T findById(Long id) {
return repository.findById(id).orElse(null); }
#Override
public T save(T object) {
return repository.save(object); }
#Override
public void delete(T object) {
repository.delete(object); }
#Override
public void deleteById(Long id) {
repository.deleteById(id); }
}
and finally an example of an actual service class that extends the above-mentioned one:
#Service
#Transactional
public class FooJpaService extends AbstractJpaService<Foo, FooRepository> implements FooService {
public FooJpaService(FooRepository repository) {
super(repository);
}
///
}
I wrote some service layer logic, controllers and once I was happy with the first iteration I've done some postman testing that worked without a hitch.
Then I took a step back and started writing some unit tests for my service classes only to realize that while findAll() in my services returns Set as I intended, the JpaRepository methods and by extension my own repos give List.
#Test
void findAll() {
Set<Foo> returnFooSet = new HashSet<>();
returnFooSet.add(new Foo(boo, 1d, 2d));
returnFooSet.add(new Foo(baz, 3d, 4d));
when(fooRepository.findAll()).thenReturn(returnFooSet);
Set<Foo> foos = service.findAll();
assertNotNull(foos);
assertEquals(2, foos.size());
}
resulting in thenReturn() method expecting a List.
Sorry for the wall of code, but I'm pretty new at this and very much confused so figured I'll provide excessive context even if most could have been assumed, since my newbie implementations may be weird and faulty.
So what gives?
I've read about the benefits of using Sets in JPA and most of the code examples I've seen use them.
My own findAllByArgument methods with Set returns like the ones you see in the repository have been working just fine, so I assume nothing stops me from overriding basic FindAll() methods in all of my repos (since CrudRepository seems to have just Iterable there), but that seems... off?
Should I be using Sets with JPA? What are good practices in this case?

I believe the only rule of thumb regarding List or Set in JPA world (with Hibernate under the hood) is to always use Set on a #ManyToMany relationship and never List.
Other than that I am not aware of anything else. Still, I can guess that maybe Set is better in terms of performance since it is unordered while List is ordered. Given that JpaRepository has a method that returns List this eventually better performance might not be relevant enough.

Related

Java Spring Method with #Cachable not intercepted by AOP Proxy

Situation -
During the implementation of an Activity tracking system, to improve performance I resort to Caching some repeated DB calls using #Cachable annotation.
The structure looks like this:
An Interface
ActivityCaseService<T>
An Abstract
AbstractActivityCaseImpl<T> implements ActivityCaseService<T>
Concrete classes
LoginActivityCaseImpl extends AbstractActivityCaseImpl<LoginActivityCase>
CallActivityCaseImpl extends AbstractActivityCaseImpl<CallActivityCase>
Based on the type of ActivityCaseType requested, it switches between LoginActivity or CallActivity implementation and executes the methods on them. Have implemented ActivityCaseServiceFactory to get the instance of a class at runtime.
But, during the implementation, #Cachable added on the method gets ignored. I have an intuition that beans returned by ActivityCaseServiceFactory are not Cacheable weaved proxies, that's why annotation is not working, but don't understand the exact issue, and how to rectify if that's the problem!
Reference:
spring.version 4.3.9.RELEASE
#Cachable works perfectly for other services in the same codebase
ActivityCaseServiceFactory
#Service
public class ActivityCaseServiceFactory {
/*ActivityCaseType:Enum*/
private Map<ActivityCaseType, ActivityCaseService<?>> activityCaseTypeVsActivityCaseService = new HashMap<>();
public ActivityCaseServiceFactory(List<ActivityCaseService<?>> abstractActivityCaseServiceImpls) {
activityCaseTypeVsActivityCaseService =
abstractActivityCaseServiceImpls.stream()
.collect(Collectors.toMap(ActivityCaseService::getActivityCaseType, A -> A));
}
public ActivityCaseService<?> getService(ActivityCaseType activityCaseType) {
return activityCaseTypeVsActivityCaseService.get(activityCaseType);
}
}
ActivityCaseService
public interface ActivityCaseService<T> extends BeanInitializer {
ActivityCaseType getActivityCaseType();
/* Method executed based on ActivityCaseType */
List<? extends ActivityBaseCaseDto> getActivityByUserIds(
ActivityInRangeQuery activityInRangeQuery, List<Integer> userIds, Boolean fromCache);
/* Tried to declare here so that execution could be intercepted by AOP Proxy */
Optional<List<T>> findActivityInRangeQuery(
ActivityInRangeQuery activityInRangeQuery, List<Integer> agentIds, Boolean fromCache);
}
AbstractActivityCaseServiceImpl
public abstract class AbstractActivityCaseServiceImpl<T extends ActivityCase> implements ActivityCaseService<T> {
public abstract ActivityCaseType getActivityCaseType();
public abstract List<? extends ActivityBaseCaseDto> getActivityByUserIds(
ActivityInRangeQuery activityInRangeQuery,
List<Integer> userIds,
Boolean fromCache);
public abstract Optional<List<T>> findActivityInRangeQuery(
ActivityInRangeQuery activityInRangeQuery, List<Integer> agentIds, Boolean fromCache);
}
LoginActivityCaseImpl
#Service(value = "LoginActivityService")
public class LoginAbstractActivityCaseServiceImpl extends AbstractActivityCaseServiceImpl<LoginActivityCase> {
#Override
public ActivityCaseType getActivityCaseType() {
return ActivityCaseType.LOGIN;
}
#Override
public List<LoginActivityBaseCaseDto> getActivityByUserIds(
ActivityInRangeQuery activityInRangeQuery, List<Integer> userIds, Boolean fromCache) {
String[]
beanNamesForType =
applicationContext.getBeanNamesForType(ResolvableType.forClassWithGenerics(ActivityCaseService.class,
LoginActivityCase.class));
(List<LoginActivityCase>) applicationContext.getBean(beanNamesForType[0],
ActivityCaseService.class).findActivityInRangeQuery(activityInRangeQuery, agents, fromCache);
/*- More logic to transform List<LoginActivityCase> received above -*/
}
/* ----> #Cacheable not working here <---- */
#Override
#Cacheable(value = CacheNames.ACTIVITY_CACHE,
condition = "#fromCache",
unless = "#result == null")
public Optional<List<LoginActivityCase>> findActivityInRangeQuery(
ActivityInRangeQuery activityInRangeQuery, List<Integer> agentIds, Boolean fromCache) {
/* -- Time taking IO calls -- */
}
}
OtherService
#Autowired
private ActivityCaseServiceFactory activityCaseServiceFactory;
public List<ActivityBaseCaseDto> getActivityForUserAndTeam(/*Params*/) {
return activityCaseServiceFactory.getService(ActivityCaseType.LOGIN)
.getActivityByUserIds(ActivityInRangeQuery.builder().build(),new ArrayList<>(Arrays.asList(1,2)),true);
}
Have been scratching my head for 2 days while searching solution to resolve this issue, but all in vain :). So, before moving to Custom Cache implementation, thought to get help from this amazing StackOverflow community.
What am I doing wrong with #Cachable? And also, open to any criticism/suggestion about how the code is overall structured to implement Activity Tracking.
Adding some screenshots to give more context:

Spring Boot not fetching correct data from Oracle database

My code is as follows:
Repository:
#Repository
#Component
public interface SearchInventoryRepository extends JpaRepository<Inventory, String>{
#Query(nativeQuery = true, value = "select * from ORACLE_DATA1")
List<Inventory> findAllDatabases();
#Query(nativeQuery = true, value = "select count(*) from ORACLE_DATA1")
int getCount();
}
Service:
#Transactional
#Service
public class GetInventoryService {
#Autowired
private SearchInventoryRepository searchInventoryRepository;
public List<Inventory> findAllDatabases()
{
return searchInventoryRepository.findAllDatabases();
}
#Autowired
public int getCount()
{
return searchInventoryRepository.getCount();
}
}
Controller:
#RestController
#Component
public class GetInventoryController {
#Autowired
private GetInventoryService getInventoryService;
#CrossOrigin
#GetMapping("/getAll")
public List<Inventory> getAll()
{
return getInventoryService.findAllDatabases();
}
#CrossOrigin
#GetMapping("/getCount")
public int getCount()
{
return getInventoryService.getCount();
}
}
The following queries yield the correct result when I run them in SQL developer:
select * from ORACLE_DATA1;
select count(*) from ORACLE_DATA1;
However, in the spring api, many of the results are duplicates, and many results are not fetched. The count of results, remains the same in SQL Developer as well as when fetched through the API.
I have never come across such an issue before. Can anyone help?
1) There is no need to annotate with #Repository an interface that extends JpaRepository
2) It's not correct to annotate with #Component a class that already has a #Repository, #Service or #Controller annotation.
#Component simply marks the class as a bean, the others integrate this feature.
3) #Autowired is used to inject instances of the annotated type. This is not correct:
#Autowired
public int getCount()
{
return searchInventoryRepository.getCount();
}
4) You can use the default methods provided by JpaRepository instead of using #Query. E.g.:
searchInventoryRepository.findAll(); // already defined
and
searchInventoryRepository.count(); // already defined
I dont know why you are using native queries, but JpaRepository extends PagingAndSortingRepository, and PagingAndSortingRepository extends CrudRepository, and this provides, and I quote:
sophisticated CRUD functionality for the entity class that is being managed
Example:
public interface CrudRepository<T, ID extends Serializable>
extends Repository<T, ID> {
(1)
<S extends T> S save(S entity);
(2)
T findOne(ID primaryKey);
(3)
Iterable<T> findAll();
Long count();
(4)
void delete(T entity);
(5)
boolean exists(ID primaryKey);
(6)
// … more functionality omitted.
}
Among the existing methods, there are two that do what you need. It is not good to reinvent the wheel.
You can get more information from this link
https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

Not able to override Spring data Pageable - Spring Neo4j

I need to override the Pageable class provided by spring data and then override the findAll method provided by the SimpleNeo4jRepository.
But on doing so, I am getting an error on server startup
Caused by: java.lang.IllegalArgumentException: Paging query needs to have a Pageable parameter! Offending method public abstract com.app.backend.repository.pagination.AppPage com.app.backend.repository.BaseRepository.findAll(com.app.backend.repository.pagination.AppPageRequest)
at org.springframework.util.Assert.isTrue(Assert.java:116) ~[spring-core-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.data.repository.query.QueryMethod.<init>(QueryMethod.java:99) ~[spring-data-commons-2.0.9.RELEASE.jar:2.0.9.RELEASE]
at org.springframework.data.neo4j.repository.query.GraphQueryMethod.<init>(GraphQueryMethod.java:41) ~[spring-data-neo4j-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.data.neo4j.repository.query.GraphQueryLookupStrategy.resolveQuery(GraphQueryLookupStrategy.java:49) ~[spring-data-neo4j-5.0.9.RELEASE.jar:5.0.9.RELEASE]
Here is the code
public class AppPageRequest extends PageRequest implements Pageable {
private AppPageRequest(int page, int size, Sort sort) {
super(page - 1, size, sort);
}
public static AppPageRequest of(int page, int size) {
return of(page, size, Sort.unsorted());
}
public static AppPageRequest of(int page, int size, Sort sort) {
return new AppPageRequest(page, size, sort);
}
}
#NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Neo4jRepository<T, ID> {
Page<T> findAll(AppPageRequest appPageRequest);
}
#NoRepositoryBean
public class BaseRepositoryImpl<T, ID extends Serializable> extends SimpleNeo4jRepository<T, ID> implements BaseRepository<T, ID> {
public BaseRepositoryImpl(Class<T> domainClass, Session session) {
super(domainClass, session);
}
public Page<T> findAll(AppPageRequest appPageRequest) {
return super.findAll(appPageRequest);
}
}
assuming you want to make sure that no-one is able to call findAll and related with the default implementation of Pageable, there are two things you have to take care of:
You cannot override the signature of findAll and related by extending your BaseRepository from Neo4jRepository, the methods are not overwritten but overloaded and can be called as before.
To make Spring Data aware of the your custom repository implementation you have to specify the new base class when enabling Neo4j (or any other repository) (as described here).
With that in mind, here is a solution that works for us. Tested with Spring Boot 2.0.4, Spring Data Kay and OGM 3.1.0, running on Java 10. Find the complete solution in this Gist.
Keypoints:
Extend Spring Datas CrudRepository at max:
#NoRepositoryBean
interface BaseRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {
Page<T> findAll(AppPageRequest appPageRequest);
}
CrudRepository does not contain findAll, so your users cannot use it. Keep your BaseRepositoryImpl as is (see gist).
Make your domain repository extend BaseRepository and again not Neo4jRepository as such:
interface ThingRepository extends BaseRepository<ThingEntity, Long> {
}
Then the important step, make SDN aware of the new base implementation through #EnableNeo4jRepositories:
#SpringBootApplication
#EnableNeo4jRepositories(repositoryBaseClass = BaseRepositoryImpl.class)
public class CustomPagerequestApplication {
public static void main(String[] args) {
SpringApplication.run(CustomPagerequestApplication.class, args);
}
}
And then you're able to use your repo like this:
#Component
class ExampleUsage implements CommandLineRunner {
private final ThingRepository thingRepository;
public ExampleUsage(ThingRepository thingRepository) {
this.thingRepository = thingRepository;
}
#Override
public void run(String... args) {
var things = IntStream.iterate(1, i -> i <= 10, i -> i + 1)
.mapToObj(ThingEntity::new)
.collect(toList());
this.thingRepository.saveAll(things);
var page = this.thingRepository.findAll(AppPageRequest.of(1, 5));
page.stream().map(ThingEntity::getName).forEach(System.out::println);
}
}
Please let me know, if this helps. Again, here the link to the complete example:
Enforce a concrete implementation of Pageable for paged Queries with Spring Data (Neo4j)
It was a configuration miss. Mentioning BaseRepositoryImpl as the repository base class fixed the issue.
I changed
#EnableNeo4jRepositories
to
#EnableNeo4jRepositories(repositoryBaseClass = BaseRepositoryImpl.class)

Repository design pattern - should there be one repo for every Dao?

i have a few DAOs in my app which access a database for CRUD operations. Lets say there News, weather and , sports DAO. So im confused on how many Repositories i would need. should i just use one repository say DataRepository and let me hold my database and all dao's. and encapsulate methods for the CRUD operations in it ? or should each DAO have its own repository ?
I mean a repository should return only data objects that the calling layer understands. so its like a encapsulation over the DAOs but im not sure if i should create one per DAO or just have one repo per app, etc.
If you read this article we begin to understand that the pattern is over engineered or over abstracted. Its turned into hiding detail vs minimizing query statements.
But it seems There should be a Repo per DAO as the interface itself looks like this:
interface Repository<T> {
void add(T item);
void remove(Specification specification);
List<T> query(Specification specification);
}
where T can be the type/table of data DAO accesses. Just need clarification now. Can you imagine i have 30 different types, so then i need 30 different Repo implementations. this is ridiculous. It seems the repository pattern itself is like a DAO, no different. im so confused.
I am not sure this is what all you looking for but In my application I am using described DAO pattern with Spring
So im confused on how many Repositories i would need.
IMHO you will need at least single Repository for each entity as they lead to simple design but since you are making them generic and they are up in hierarchy, can be used simply with child classes/interfaces
Below is the example
Interface to define all basic methods that to use commonly
public interface GenericDAO<T, ID extends Serializable> {
T findById(ID id, LockModeType lock);
void save(T entity);
T update(T entity);
List<T> findAll();
}
Generic Implementation
public abstract class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID> {
#PersistenceContext
protected EntityManager em;
private final Class<T> entityClass;
public GenericDAOImpl(Class<T> entityClass) {
this.entityClass = entityClass;
}
#Override
public T findById(ID id, LockModeType lock) {
return em.find(entityClass, id, lock);
}
#Override
public void save(T entity) {
em.persist(entity);
}
#Override
public T update(T entity) {
return em.merge(entity);
}
#Override
public List<T> findAll() {
CriteriaQuery<T> c = em.getCriteriaBuilder().createQuery(entityClass);
c.select(c.from(entityClass));
return em.createQuery(c).getResultList();
}
.
.
.
}
Foo class
#Entity
public class Foo implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String text;
}
Foo Repositiry
public interface FooRepositiry extends GenericDAO<Foo, Long> {
Foo findTextById(Long id);
}
Implemented Foo Repositiry
#Transactional
#Repository
public class FooRepoImpl extends GenericDAOImpl<Foo, Long> implements FooRepositiry {
public FooRepoImpl() {
super(Foo.class);
}
#Override
public Foo findTextById(Long id) {
CriteriaQuery<Foo> c = em.getCriteriaBuilder().createQuery(Foo.class);
// .
// .
// .
return em.createQuery(c).getSingleResult();
}
}
Same for Bar class
#Transactional
#Repository
public class BarRepoImpl extends GenericDAOImpl<Bar, Long> implements BarRepo {
public BarRepoImpl() {
super(Bar.class);
}
#Override
public List<Bar> findAllBarWithText(String text) {
CriteriaQuery<Bar> c = em.getCriteriaBuilder().createQuery(Bar.class);
return em.createQuery(c).getResultList();
}
}
Here this generic implementation needs two things to work: an EntityManager and an
entity class. A subclass must provide the entity class as a constructor argument. EntityManager is provided by using PersistenceContext or you can use getter-setter methods for the same. Since GenericDAOImpl is abstract threfore you cannot use it directly but Indirectly and most of the commnoly used methods are generic and up in hierarchy which makes them Ideal candidate to be reused.
You can read more about this from book Java Persistence with Hibernate 2nd Edition

Java - Spring data access object implementation

In my current spring setup i would like to implement a slightly different architecture, here is my setup:
I have a "base" DAO interface, which lists all CRUD operations:
public interface BaseDao {
public boolean create(Object obj);
public List<Object> read();
public boolean update(Object obj);
public boolean delete(Object obj);
}
Next i have "specific" DAO interface, which extends from the "base" one:
public interface ArticleDao extends BaseDao {
public List<Article> getArticlesByAttribute(String attribute);
}
And finally, the Repository, which implements the interface:
public class ArticleDaoImpl implements ArticleDao {
public boolean create(Article article) {
// code
}
public List<Article> read() {
// code
}
public boolean update(Article article) {
// code
}
public boolean delete(Article article) {
// code
}
public List<Article> getArticlesByAttribute(String attribute) {
// code
}
}
So the idea is simple:
I want every Repository to implement all crud operations + "the methods from the specific dao-interface"
But i get the following error:
ArticleDaoImpl is not abstract and does not override
abstract method delete(java.lang.Object) in BaseDao
etc..
So this is probably because i defined Object as a parameter in the interface and "Article" as a parameter in the actual implementation..
Anybody got the idea how i can follow this pattern correctly?
Should i consider working with generics?
Thanks and Greetings
No. You should work with Spring Data JPA/MongoDB etc. It will make MOST of your boilerplate code go away. Seriously - forget about DAO and go with Spring Data JPA: https://spring.io/guides/gs/accessing-data-jpa/

Categories

Resources