如何使用的createQuery弹簧引导

问题描述:

通常我使用annotiations:@Query("SELECT c FROM Country c")JpaRepository或预先定义的方法,如findAll如何使用的createQuery弹簧引导

但对我来说我要生成动态查询。

String baseQuery =SELECT c FROM Country c` 

if(age!=null) 
    baseQuery+="WHERE c.age=20" 

我需要从代码级这样进行相同的查询:

查询Q1 = em.createQuery( “选择C来自国家C”);

,但我不使用EntityManager春季启动

怎样才能从代码级的查询?关于语法

@Repository 
public interface CountryRepository extends JpaRepository<Country, Long> { 

} 

不是100%,但应该是类似的东西:

+1

对不起,但是什么阻止你调用你的仓库的findAll()方法?您是否在不使用Spring Data JPA时询问如何执行JPA查询?如果是这样,你尝试了什么,你面临的具体问题是什么? –

+0

我不能使用findAll(),因为我想生成动态查询。 查询必须取决于输入值 – user3871754

+0

您面临什么问题?您是否阅读过spring-data-jpa文档以了解如何创建自定义存储库方法? http://docs.spring.io/spring-data/jpa/docs/1.7.2.RELEASE/reference/html/#repositories.single-repository-behaviour –

由于您使用的春天启动,你可以使用Spring的数据存储库中的创建查询。 现在你可以自动装配这个类:

@Autowired 
public CountryRepository countryRepo; 

而且所有的基本方法已经提供给你喜欢:

countryRepo.findOne(id); 
countryRepo.find(); 

如果你想更高级的查询,你可以使用Spring数据如:

@Repository 
public interface CountryRepository extends JpaRepository<Country, Long> { 

    public Country findByNameAndContinent(String name, String continent); 
} 

这仅仅是一个例子(一个愚蠢的一个),当然,同时假定您Country类公顷字段名称'name'和'continent',两者都是字符串。更多可在此处获得: http://docs.spring.io/spring-data/jpa/docs/current/reference/html/ 更具体的5.3节。

PS:请确保您的Country类有@Entity注释

+0

我很抱歉,但我严重制定了这个问题,问题是如何创建自定义查询。现在我知道我可以通过实现定制存储库功能来完成它:http://docs.spring.io/spring-data/jpa/docs/1.7.2.RELEASE/reference/html/#repositories.single-repository-behaviour – user3871754

如果你想创建你可以在代码中利用Spring的JdbcTemplate的优势动态查询。使用spring引导就像将JdbcOperations bean注入到存储库类中一样简单(假设您已为您的项目提供了spring-boot-starter-jdbc模块)。

但请记住!该解决方案使用SQL,而不是JPQL。这就是为什么你必须在查询中使用适当的表和列名称,并正确地将结果映射到对象(即使用RowMapper

这个简单的例子对我来说工作得很好(用不同的实体,但以相同的方式 - 我已经调整它以你为例):

@Repository 
public class CountryRepository { 

    @Autowired 
    private JdbcOperations jdbcOperations; 

    private static String BASIC_QUERY = "SELECT * FROM COUNTRY"; 

    public List<Country> selectCoutry(Long age){ 
     String query = BASIC_QUERY; 
     if (age != null){ 
      query += " WHERE AGE = "; 
      query += age.toString(); 
     } 

     //let's pretend that Country has constructor Conutry(String name, int age) 
     return jdbcOperations.query(query, (rs, rowNum) -> 
      { return new Country(rs.getString("NAME"), rs.getInt("AGE");} 
     ); 
    }; 

} 

然后在服务或任何你注入CountryRepository和调用方法。