2015-06-20 31 views
3

我是Spring JPA和Repository的新手。我有一個拍賣類,其中有一堆字段,其中一個字段是類別。我想要一個CrudRepository中的自定義方法來過濾Category.name的結果;如何編寫自定義的CrudRepository方法(@Query)來過濾我的結果

@XmlRootElement 
@Entity(name="AUCTION") 
public class Auction implements Serializable{ 

    private static final long serialVersionUID = 1L; 

    @Id 
    String id; 

    @Column 
    @Size(min=5, max=200) 
    String title; 

    String description; 

    @OneToOne(cascade={CascadeType.ALL}) 
    Category category; 

    ....} 

類別

@Entity(name="CATEGORY") 
//@NamedQuery(name="Category.findByName", query="select c from Category c where c.name=:name") 
public class Category implements Serializable{ 

    private static final long serialVersionUID = 3L; 

    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private Integer id; 

    private String name; 

    public Category() 
    { 

    } 

在拍賣庫,我添加了一個方法,像這樣

@Repository 
public interface AuctionRepository extends CrudRepository<Auction, String>{ 

    @Query("from Auction a join a.category c where c.name=:categoryName") 
    public Iterable<Auction> findByCategory(String categoryName); 

} 

它拋出一個錯誤。省略此方法,一切正常。有人告訴我這種類型的自定義方法可以在CrudRepository中聲明,並且Spring將使用methodName和我們提供的查詢提示來處理正確的事情。有人能指出我正確的方向請。

回答

12

您需要將@Param註釋添加到方法變量名稱中,以便您可以在查詢中引用它。你寫的代碼非常好。如果您需要訪問EntityManager,那麼您將需要一個自定義存儲庫。

@Query("from Auction a join a.category c where c.name=:categoryName") 
public Iterable<Auction> findByCategory(@Param("categoryName") String categoryName); 

@Param可以使用Java 8,用-parameters編譯時被省略。

希望有所幫助。

提示:每當您發佈問題時,也總是發佈例外詳情。它有助於理解問題。

+0

這是否意味着我需要在Repository Implementation類中手動實現該方法。 – Rajan

+0

不,你很好。只有缺失的部分是'''@Param(「categoryName」)'''。結帳http://docs.spring.io/spring-data/jpa/docs/1.8.0.RELEASE/reference/html/#jpa.named-parameters –

+0

感謝您的幫助,但我認爲我錯過了別的。它拋出以下異常。 org.springframework.beans.factory.BeanCreationException:創建名爲'auctionServiceImpl'的bean時出錯:注入自動裝配依賴失敗;嵌套異常是org.springframework.beans.factory.BeanCreationException:無法自動裝入字段:com.mum.waa.project.repository.AuctionRepository com.mum.waa.project.service.AuctionServiceImpl.auctionRepository;嵌套的異常是org.springframework。 – Rajan

相關問題