简体   繁体   中英

How to execute a query using @Query Spring JPA annotation

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

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;

}

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM