简体   繁体   English

如何使用@Query Spring JPA批注执行查询

[英]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. 我正在尝试使用SpringData Jpa在接口方法声明上使用@Query注释编写查询。

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. 我不确定此查询执行将如何工作,以及如何在实现类中为getEmployeesWorkingOnAProject方法提供实现。

Thanks 谢谢

In your Interface, you should extend JpaRepository (or any other spring data repository). 在您的界面中,您应该扩展 JpaRepository(或任何其他spring数据存储库)。 Then you can just autowire your interface in any spring bean class and call getEmployeesWorkingOnAProject(). 然后,您可以在任何Spring bean类中自动装配接口并调用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能够为您构建查询,因此在此示例中没有理由编写自己的查询。

Spring Data way: Spring Data方式:

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 . 您的界面必须扩展某种Spring Data Repository,例如JpaRepository

Second thing, in the Query annotation, you can put two types of query. 第二件事,在查询批注中,您可以放置​​两种类型的查询。 JPQL or native SQL query. JPQL或本机SQL查询。 This can be controlled by a flag on the query annotation (nativeQuery). 这可以通过查询注释(nativeQuery)上的标志来控制。

In JPQL, your query should look like the following: 在JPQL中,您的查询应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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