1

I am trying to write a query using SpringData Jpa using the @Query annotation on the interface method declaration.

The interface looks like this:

public interface MyService {

    @Query("select * from employee e where e.projectId = ?1")
    public List<Employee> getEmployeesWorkingOnAProject(String projectId) throws MyException;
}

I also have a class that implements this interface:

@Component
public class ProjectServiceImpl implements ProjectService {

}

I am not sure how will this query execution work and how to provide an implementation for getEmployeesWorkingOnAProject method in the imeplementing class.

Thanks

1
  • In this case, you don't need the @Query. Just name your method findByProjectId(String), or even findByProject(Project) if you have a foreign-key relationship. Commented Apr 20, 2017 at 6:29

2 Answers 2

5

In your Interface, you should extend JpaRepository (or any other spring data repository). Then you can just autowire your interface in any spring bean class and call getEmployeesWorkingOnAProject().

So for example:

public interface MyService extends JpaRepository<Employee,Long> {

    @Query("select * from employee e where e.projectId = ?1")
    public List<Employee> getEmployeesWorkingOnAProject(String projectId) throws MyException;

}


@Component
public class ProjectServiceImpl implements ProjectService {

    private final MyService service;

    @Autowire // not necessary in spring 4.3 +
    public ProjectServiceImpl(MyService service) {
        this.service = service;
    }

    public List<Employee> getEmployeesWorkingOnAProject(String projectId) throws MyException {
         return service.getEmployeesWorkingOnAProject();
    }
}

However, Spring Data is able to build a query for you, so is no reason for writing your own query in this example.

Spring Data way:

public interface MyService extends JpaRepository<Employee,Long> {

    public List<Employee> findAllByProjectId(String projectId) throws MyException;

}
Sign up to request clarification or add additional context in comments.

2 Comments

thnx. but what relationships do i need to define between employee and project so that this method name works.
I guess it's the different question, so you need to ask in new threat
0

First things first. Your interface have to extend some kind of Spring Data Repository, for example JpaRepository.

Second thing, in the Query annotation, you can put two types of query. JPQL or native SQL query. This can be controlled by a flag on the query annotation (nativeQuery).

In JPQL, your query should look like the following:

@Query("select e from employee e where e.projectId = ?1")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.