Reputation: 2836
I have a web component called Select. It's a drop down box in Vaadin framework. I want to construct Select drop down boxes at start up and they are going to contain data from repositories from JPA in Spring Boot.
Here is my example code:
private <T extends UserLoggRepository> void addSelect(Select<Long> select, String placeHolder, T repository) {
List<UserLogg> userLoggers = repository.findAll();
List<Long> items = new ArrayList<Long>();
for(int i = 0; i < userLoggers.size(); i++) {
long value = userLoggers.get(i).getLoggerId();
if(items.contains(value) == false)
items.add(value);
}
if(items.contains((long) 0) == false)
items.add((long) 0);
select.setItems(items);
select.setPlaceholder(placeHolder);
}
This code works! But I have different entities and different repositories. I have the entities:
And I have the repositories:
Question:
How can I change the method addSelect
so they will work with any respository that are connected to an entity? All repositories have the standard function findAll()
and all entities have the field loggerId
.
Focus:
What I have problem with is that this code only works for the entity UserLogg
and repository UserLoggRepository
.
List<UserLogg> userLoggers = repository.findAll();
What need to be done:
This need to change, but I don't know what to write here so it become more general for them all.
private <T extends UserLoggRepository> void addSelect
Update 1:
A repository header in JPA looks e.g like this:
public interface AlarmLoggRepository extends JpaRepository<AlarmLogg, Long>
I could use this, but still, got the UserLogg
class is fixed.
private <T extends JpaRepository<UserLogg, Long>> void addSelect(Select<Long> select, String placeHolder, T repository)
Upvotes: 0
Views: 73
Reputation: 5342
You need a common interface or superclass for all your entities, that ensures they have the getLoggedId()
method.
After that, something like this should work:
private void addSelect(Select<Long> select, String placeHolder, JpaRepository<? extends AbstractLogg, Long> repository) {
List<AbstractLogg> loggers = repository.findAll();
...
}
Upvotes: 1
Reputation: 81
If I understood your problem correctly, you can do inheritance and make a parent class for all your existing entities and change the definition of your addSelect method to return that parent class which could eventually return a type of any of it's subclasses.
For example, looks like your existing entities are all logs, so you can have an Abstract class named LoggRepository and have it extended by all your existing entities like:
public class UserLoggRepository extends LoggRepository
And then, update the method addSelect like below so it can return and of the subclasses of your parent abstract class LoggRepository
private <? extends LoggRepository> void addSelect(Select<Long> select, String placeHolder, T repository)
Hope this helps :)
Upvotes: 1