2016-12-03 166 views
-1

通常我使用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 –

回答

0

由於您使用的春天啓動,你可以使用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

0

如果你想創建你可以在代碼中利用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和調用方法。