Is it possible to create a generic Repository interface to save POJOs in my spring-data project?
I have around 50 different objects and I don't want to create 50 corresponding repository interfaces one of each pojo ?
For example,
public interface FooRepository extends JpaRepository<Foo, Integer> { }
public interface BarRepository extends JpaRepository<Bar, Integer> { }
and so on...
I do see similar questions on this site but not having a really good example.
Thanks in advance for any help.
I think the only way is to create a #NoBeanRepository because the main goal of a Spring's repository is to provide a user-friendly interface to manipulate entities. But in this case your entities must have same properties.
#NoRepositoryBean
public interface SortOrderRelatedEntityRepository<T, ID extends Serializable>
extends SortOrderRelatedEntityRepository<T, ID> {
T findOneById(Long id);
List<T> findByParentIdIsNullAndSortOrderLessThanEqual(Integer sortOrder);
/** and so on*//
}
public interface StructureRepository
extends SortOrderRelatedEntityRepository<Structure, Long> {
Structure findOneById(Long id);
List<Structure> findByParentIdIsNullAndSortOrderLessThanEqual(Integer sortOrder);
/** and so on*//
}
Related
I want to make a generic repository that accepts the entity class and few attributes like start_date and end_date, etc and returns all the records in the table.
To fetch the results for a single entity using repository I will need to write a custom query. I am not sure how would I write a Custom query in a generic way for any entity that is passed and filter according to the attributes.
Since you are using Spring Data JPA you can declare your own shared repository interface with your own methods and avoid a custom query. The same approach is used by CrudRepository to provide additional methods which are not present in Repsitory.
For example you can declare:
public interface SharedRepository<T, ID> extends CrudRepository<T, ID> {
List<T> findByStartDateAndEndDate(LocalDate startDate, LocalDate endDate);
}
Then extend from this new interface for your entities
#Repository
public interface PersonRepisotry extends SharedRepository<Person, Long> {
}
#Repository
public interface RoomRepository extends SharedRepository<Room, Long> {
}
Both PersonRepository and RoomRepository will have findByStartDateAndEndDate method.
Spring now supports a kind of query by example
Service:
Person person = new Person();
person.setFirstname("Dave");
Example<Person> example = Example.of(person);
Repo Interface:
public interface QueryByExampleExecutor<T> {
<S extends T> S findOne(Example<S> example);
<S extends T> Iterable<S> findAll(Example<S> example);
}
I have a simple entity inheritance tree composed of the following:
abstract class Item (id, ...)
class Chart extends Item (...)
class Table extends Item (...)
Each class has its own repository: ItemRepository, ChartRepository and TableRepository. All three repositories are exposed.
Because of domain rules, I need to implement custom logic on delete, as explained here: http://docs.spring.io/spring-data/jpa/docs/1.10.3.RELEASE/reference/html/#repositories.custom-implementations
This custom delete logic concerns all entities in the inheritance tree (the abstract one and the two concretes).
Is there a way to implement custom logic on the ItemRepository and make the repositories of the children entities extend ItemRepository?
This would avoid duplicate of the same logic for each entity of the inheritance tree. Without that this makes a lot of boilerplate classes :
EntityRepository + EntityRepositoryCustom + EntityRepositoryImpl x 3 entities = 9 classes just to implement 1 ligne of code to be executed on delete...
EDIT
The answer of user user7398104 got me on the way to implement things as explained here and there, but theses resources do not explain how to implement a custom repository on the #NoRepositoryBean base repository. I tried the following without luck:
#NoRepositoryBean
public interface ItemBaseRepository<T extends Item> extends
CrudRepository<T, Integer>,
ItemBaseRepositoryCustom<T>
#RepositoryRestResource
public interface ItemRepository extends ItemBaseRepository<Item> {}
#RepositoryRestResource
public interface ChartRepository extends ItemBaseRepository<Item> {}
#RepositoryRestResource
public interface TableRepository extends ItemBaseRepository<Item> {}
public interface ItemBaseRepositoryCustom<T extends Item> {
public void delete (T i);
}
public class ItemBaseRepositoryImpl<T extends Item>
implements ItemBaseRepositoryCustom<T> {
public void delete (T i) {
// Custom logic
}
}
EDIT EDIT
I tried to set #NoRepositoryBean to ItemBaseRepositoryCustom as suggested on comments but it doesnt work either.
You can create ItemRepositoryCustom interface extending the ItemRepository interface, with each chart and table repos extending the ItemRepositoryCustom repo. For this interface you can have a custom implmentation for the delete operation.
EDIT: I just realised that this would not work.
But the following approach would work.
interface CustomItemRepository<T extends Item> extends CrudRepository<T, Long>{
}
interface ChartRepository extends CustomItemRepository<Chart>{
}
interface TableRepository extends CustomItemRepository<Table>{
}
Then you can create a class for delete logic for CustomItemRepository.
I'm using Spring Data JPA and want to add a method in my base Repository interface to get all entities ordered by field order:
#NoRepositoryBean
public interface OrderedEntityDao<T extends OrderedEntity> extends EntityDao<T, Long> {
List<T> findOrderByOrder();
}
OrderedEntity is a #MappedSuperclass entity.
But I'm getting exception when creating this bean:
Caused by: java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:854)
at org.springframework.data.jpa.repository.query.ParameterMetadataProvider.next(ParameterMetadataProvider.java:121)
at org.springframework.data.jpa.repository.query.JpaQueryCreator$PredicateBuilder.build(JpaQueryCreator.java:274)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.toPredicate(JpaQueryCreator.java:180)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.create(JpaQueryCreator.java:109)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.create(JpaQueryCreator.java:49)
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createCriteria(AbstractQueryCreator.java:109)
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:88)
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:73)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.<init>(PartTreeJpaQuery.java:118)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$CountQueryPreparer.<init>(PartTreeJpaQuery.java:241)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:68)
How to write this method correct?
Edit:
#MappedSuperclass
public abstract class OrderedEntity extends IdEntity implements Comparable<OrderedEntity> {
#Nonnull
#Column(name = "`order`")
private Long order;
}
The correct named query will be:
public interface OrderedEntityDao<T extends OrderedEntity> extends EntityDao<T> {
public List<T> findAllByOrderBy<colname><Desc|Asc>();
}
In your case:
public List<T> findAllByOrderByOrderDesc();
public List<T> findAllByOrderByOrderAsc();
I think this below code is work,
#NoRepositoryBean
public interface OrderedEntityDao<T extends OrderedEntity> extends EntityDao<T, Long> {
List<T> findAllOrderByOrderAsc();
}
It should be
public List<T> findByOrder(Long order);
The correct syntax for query methods with Spring Data is basically findBy followed by the variable names, separated with And/Or. Refer to the full documentation here.
I am new to stack overflow and working on spring jpa data with hibernate and mysql. I have created One JpaRepository for each entity class. But now I feel that I should use One repository for all entities because In all my repositories has common CRUD operation methods.
save()
update()
delete()
findOne()
findAll()
Besides of above methods, I have other custom methods also in my applications.
my aim is to implement GenericRepo like,
public interface MyGenericRepo extends JpaRepository<GenericEntity,Integer>
{
}
my entities will be like:
class Place extends GenericEntity
{
private Event event;
}
class Event extends GenericEntity
{
}
class Offer extends GenericEntity
{
private Place place;
}
class User extends GenericEntity
{
private Place place;
}
when I call:
MyGenericRepo myRepo;
GenericEntity place=new Place();
myRepo.save(place);
It should save place.
[http://openjpa.apache.org/builds/1.0.2/apache-openjpa-1.0.2/docs/manual/jpa_overview_mapping_inher.html#jpa_overview_mapping_inher_joined][1]
I have referred above link and I found that Jpa Inheritance with Joined and Table-Per-Class strategies are similar to what I am looking for, but these all have certain limitations.So please tell me should I try to implement this generic thing.If I get any demo code then I will be very greatful...
Thanks..
How to make generic jpa repository? Should I do this? Why?
If you want to create your own Repos (and not spring data which does some work for you) your example isn't bad, i am using a similar strategy in one application.
Here a few thoughts to improve the generic way:
I've added the ID-information in my basic domain which is implemented by all domain objects:
public interface UniqueIdentifyable<T extends Number> {
T getId();
void setId(T id);
}
In the next step i've created a generic CRUDRepo:
public interface CRUDRepository<ID extends Number, T extends UniqueIdentifyable<ID>>{
ID insert(T entity);
void delete(T entity);
....
}
And I am using an abstract class for the CRUDRepo:
public abstract class AbstractCRUDRepo<ID extends Number, T extends UniqueIdentifyable<ID>> implements CRUDRepo<ID, T>, {...}
a domain repo api will now look like:
public interface UserRepo extends CRUDRepo<Integer, User > {
User mySpecificQuery(..);
}
and finally you can implement your repo via:
public class UserRepoImpl extends AbstractCRUDRepo<Integer, User > implements UserRepo {
public User mySpecificQuery(..){..}
}
I have a number of simple object types that need to be persisted to a database. I am using Spring JPA to manage this persistence. For each object type I need to build the following:
import org.springframework.data.jpa.repository.JpaRepository;
public interface FacilityRepository extends JpaRepository<Facility, Long> {
}
public interface FacilityService {
public Facility create(Facility facility);
}
#Service
public class FacilityServiceImpl implements FacilityService {
#Resource
private FacilityRepository countryRepository;
#Transactional
public Facility create(Facility facility) {
Facility created = facility;
return facilityRepository.save(created);
}
}
It occurred to me that it may be possible to replace the multiple classes for each object type with three generics based classes, thus saving a lot of boilerplate coding. I am not exactly sure how to go about it and in fact if it is a good idea?
First of all, I know we're raising the bar here quite a bit but this is already tremendously less code than you had to write without the help of Spring Data JPA.
Second, I think you don't need the service class in the first place, if all you do is forward a call to the repository. We recommend using services in front of the repositories if you have business logic that needs orchestration of different repositories within a transaction or has other business logic to encapsulate.
Generally speaking, you can of course do something like this:
interface ProductRepository<T extends Product> extends CrudRepository<T, Long> {
#Query("select p from #{#entityName} p where ?1 member of p.categories")
Iterable<T> findByCategory(String category);
Iterable<T> findByName(String name);
}
This will allow you to use the repository on the client side like this:
class MyClient {
#Autowired
public MyClient(ProductRepository<Car> carRepository,
ProductRepository<Wine> wineRepository) { … }
}
and it will work as expected. However there are a few things to notice:
This only works if the domain classes use single table inheritance. The only information about the domain class we can get at bootstrap time is that it will be Product objects. So for methods like findAll() and even findByName(…) the relevant queries will start with select p from Product p where…. This is due to the fact that the reflection lookup will never ever be able to produce Wine or Car unless you create a dedicated repository interface for it to capture the concrete type information.
Generally speaking, we recommend creating repository interfaces per aggregate root. This means you don't have a repo for every domain class per se. Even more important, a 1:1 abstraction of a service over a repository is completely missing the point as well. If you build services, you don't build one for every repository (a monkey could do that, and we're no monkeys, are we? ;). A service is exposing a higher level API, is much more use-case drive and usually orchestrates calls to multiple repositories.
Also, if you build services on top of repositories, you usually want to enforce the clients to use the service instead of the repository (a classical example here is that a service for user management also triggers password generation and encryption, so that by no means it would be a good idea to let developers use the repository directly as they'd effectively work around the encryption). So you usually want to be selective about who can persist which domain objects to not create dependencies all over the place.
Summary
Yes, you can build generic repositories and use them with multiple domain types but there are quite strict technical limitations. Still, from an architectural point of view, the scenario you describe above shouldn't even pop up as this means you're facing a design smell anyway.
This is very possible! I am probably very late to the party. But this will certainly help someone in the future. Here is a complete solution that works like a charm!
Create BaseEntity class for your entities as follows:
#MappedSuperclass
public class AbstractBaseEntity implements Serializable{
#Id #GeneratedValue
private Long id;
#Version
private int version;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
public AbstractBaseEntity() {
this.createdAt = LocalDateTime.now();
this.updatedAt = LocalDateTime.now();
}
// getters and setters
}
Create a generic JPA Repository interface for your DAO persistence as follows:
NB. Remember to put the #NoRepositoryBean so that JPA will not try to find an implementation for the repository!
#NoRepositoryBean
public interface AbstractBaseRepository<T extends AbstractBaseEntity, ID extends Serializable>
extends JpaRepository<T, ID>{
}
Create a Base Service class that uses the above base JPA repository. This is the one that other service interfaces in your domain will simply extend as follows:
public interface AbstractBaseService<T extends AbstractBaseEntity, ID extends Serializable>{
public abstract T save(T entity);
public abstract List<T> findAll(); // you might want a generic Collection if u prefer
public abstract Optional<T> findById(ID entityId);
public abstract T update(T entity);
public abstract T updateById(T entity, ID entityId);
public abstract void delete(T entity);
public abstract void deleteById(ID entityId);
// other methods u might need to be generic
}
Then create an abstract implementation for the base JPA repository & the basic CRUD methods will also be provided their implementations as in the following:
#Service
#Transactional
public abstract class AbstractBaseRepositoryImpl<T extends AbstractBaseEntity, ID extends Serializable>
implements AbstractBaseService<T, ID>{
private AbstractBaseRepository<T, ID> abstractBaseRepository;
#Autowired
public AbstractBaseRepositoryImpl(AbstractBaseRepository<T, ID> abstractBaseRepository) {
this.abstractBaseRepository = abstractBaseRepository;
}
#Override
public T save(T entity) {
return (T) abstractBaseRepository.save(entity);
}
#Override
public List<T> findAll() {
return abstractBaseRepository.findAll();
}
#Override
public Optional<T> findById(ID entityId) {
return abstractBaseRepository.findById(entityId);
}
#Override
public T update(T entity) {
return (T) abstractBaseRepository.save(entity);
}
#Override
public T updateById(T entity, ID entityId) {
Optional<T> optional = abstractBaseRepository.findById(entityId);
if(optional.isPresent()){
return (T) abstractBaseRepository.save(entity);
}else{
return null;
}
}
#Override
public void delete(T entity) {
abstractBaseRepository.delete(entity);
}
#Override
public void deleteById(ID entityId) {
abstractBaseRepository.deleteById(entityId);
}
}
How to use the above abstract entity, service, repository, and implementation:
Example here will be a MyDomain entity. Create a domain entity that extends the AbstractBaseEntity as follows:
NB. ID, createdAt, updatedAt, version, etc will be automatically be included in the MyDomain entity from the AbstractBaseEntity
#Entity
public class MyDomain extends AbstractBaseEntity{
private String attribute1;
private String attribute2;
// getters and setters
}
Then create a repository for the MyDomain entity that extends the AbstractBaseRepository as follows:
#Repository
public interface MyDomainRepository extends AbstractBaseRepository<MyDomain, Long>{
}
Also, Create a service interface for the MyDomain entity as follows:
public interface MyDomainService extends AbstractBaseService<MyDomain, Long>{
}
Then provide an implementation for the MyDomain entity that extends the AbstractBaseRepositoryImpl implementation as follows:
#Service
#Transactional
public class MyDomainServiceImpl extends AbstractBaseRepositoryImpl<MyDomain, Long>
implements MyDomainService{
private MyDomainRepository myDomainRepository;
public MyDomainServiceImpl(MyDomainRepository myDomainRepository) {
super(myDomainRepository);
}
// other specialized methods from the MyDomainService interface
}
Now use your `MyDomainService` service in your controller as follows:
#RestController // or #Controller
#CrossOrigin
#RequestMapping(value = "/")
public class MyDomainController {
private final MyDomainService myDomainService;
#Autowired
public MyDomainController(MyDomainService myDomainService) {
this.myDomainService = myDomainService;
}
#GetMapping
public List<MyDomain> getMyDomains(){
return myDomainService.findAll();
}
// other controller methods
}
NB. Make sure that the AbstractBaseRepository is annotated with #NoRepositoryBean so that JPA does not try to find an implementation for the bean.
Also the AbstractBaseServiceImpl must be marked abstract, otherwise JPA will try to autowire all the children daos of the AbstractBaseRepository in the constructor of the class leading to a NoUniqueBeanDefinitionException since more than 1 daos (repository) will be injected when the bean is created!
Now your service, repository, and implementations are more reusable. We all hate boilerplate!
Hope this helps someone.
I am working a project to create the generic repository for cassandra with spring data.
Firstly create a repository interface with code.
StringBuilder sourceCode = new StringBuilder();
sourceCode.append("import org.springframework.boot.autoconfigure.security.SecurityProperties.User;\n");
sourceCode.append("import org.springframework.data.cassandra.repository.AllowFiltering;\n");
sourceCode.append("import org.springframework.data.cassandra.repository.Query;\n");
sourceCode.append("import org.springframework.data.repository.CrudRepository;\n");
sourceCode.append("\n");
sourceCode.append("public interface TestRepository extends CrudRepository<Entity, Long> {\n");
sourceCode.append("}");
Compile the code and get the class, I use org.mdkt.compiler.InMemoryJavaCompiler
ClassLoader classLoader = org.springframework.util.ClassUtils.getDefaultClassLoader();
compiler = InMemoryJavaCompiler.newInstance();
compiler.useParentClassLoader(classLoader);
Class<?> testRepository = compiler.compile("TestRepository", sourceCode.toString());
And initialize the repository in spring data runtime. This is a little tricky as I debug the SpringData code to find how it initialize a repository interface in spring.
CassandraSessionFactoryBean bean = context.getBean(CassandraSessionFactoryBean.class);
RepositoryFragments repositoryFragmentsToUse = (RepositoryFragments) Optional.empty().orElseGet(RepositoryFragments::empty);
CassandraRepositoryFactory factory = new CassandraRepositoryFactory(
new CassandraAdminTemplate(bean.getObject(), bean.getConverter()));
factory.setBeanClassLoader(compiler.getClassloader());
Object repository = factory.getRepository(testRepository, repositoryFragmentsToUse);
Now you can try the save method of the repository and you can try other methods such as findById.
Method method = repository.getClass().getMethod("save", paramTypes);
T obj = (T) method.invoke(repository, params.toArray());
A full sample code and implementation I have put in this repo
https://github.com/maye-msft/generic-repository-springdata.
You can extend it to JPA with the similar logic.