如何编写自定义 CrudRepository 方法(@Query)来过滤我的结果
How to write a custom CrudRepository method(@Query) to filter the result in my case
我是 Spring JPA 和存储库的新手。我有一个拍卖 class,里面有一堆字段,其中一个字段是类别。我想要 CrudRepository 中的自定义方法按 Category.name 过滤结果;
@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 将负责使用我们提供的方法名称和查询提示做正确的事情。请有人指出我正确的方向。
您需要为方法变量名称添加 @Param
注释,以便您可以在查询中引用它。你写的代码绝对没问题。如果您需要访问 EntityManager
,那么您将需要一个自定义存储库。
@Query("from Auction a join a.category c where c.name=:categoryName")
public Iterable<Auction> findByCategory(@Param("categoryName") String categoryName);
@Param
在使用Java8时可以省略,用-parameters
编译。
希望对您有所帮助。
提示:每当您 post 一个问题总是 post 异常细节也是如此。它有助于理解问题。
我是 Spring JPA 和存储库的新手。我有一个拍卖 class,里面有一堆字段,其中一个字段是类别。我想要 CrudRepository 中的自定义方法按 Category.name 过滤结果;
@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 将负责使用我们提供的方法名称和查询提示做正确的事情。请有人指出我正确的方向。
您需要为方法变量名称添加 @Param
注释,以便您可以在查询中引用它。你写的代码绝对没问题。如果您需要访问 EntityManager
,那么您将需要一个自定义存储库。
@Query("from Auction a join a.category c where c.name=:categoryName")
public Iterable<Auction> findByCategory(@Param("categoryName") String categoryName);
@Param
在使用Java8时可以省略,用-parameters
编译。
希望对您有所帮助。
提示:每当您 post 一个问题总是 post 异常细节也是如此。它有助于理解问题。