Home > Software design >  How do I use Qualifiers in Spring boot
How do I use Qualifiers in Spring boot

Time:01-08

This is my project structure

MODEL

  1. TodoItem.java - this is an interface
  2. TodoType1 - this implements the interface
  3. TodoType2 - this implements the interface

Repo

  1. TodoRepo.java - extends JPA repo with <TodoItem, Integer>

Controller (uses the TodoRepo for CRUD operations)

  1. request 1 - needs to work with todotype1
  2. request 2 - needs to work with todotype2

I am a bit confused, how should i go about using qualifiers here? Should I create different Repositories for each type?

CodePudding user response:

TodoRepo.java - extends JPA repo with <TodoItem, Integer>

Here TodoItem is an interface. Springboot JPA gets confused about which entity it is going to handle(two class implements the TodItem interface). Instead of Interface, declaring a specified entity class won't throw the error.

CodePudding user response:

I think you need to create two different repositories. And then you can use the @Autowired annotation to inject the desired bean into your controller.

This will inject the appropriate repository implementation (TodoType1Repo or TodoType2Repo) into your controller based on the value of the @Qualifier annotation.

more about @Qualifier https://www.baeldung.com/spring-qualifier-annotation

@Qualifier("todoType1Repo")
@Repository
public class TodoType1Repo extends JpaRepository<TodoType1, Integer> {}

@Qualifier("todoType2Repo")
@Repository
public class TodoType2Repo extends JpaRepository<TodoType2, Integer> {}

  
@Autowired
@Qualifier("todoType1Repo")
private TodoRepo todoType1Repo;

@Autowired
@Qualifier("todoType2Repo")
private TodoRepo todoType2Repo;

public void handleRequest1() {
  // Use todoType1Repo to perform CRUD operations on TodoType1 objects
}

public void handleRequest2() {
  // Use todoType2Repo to perform CRUD operations on TodoType2 objects
}
  • Related