I am new to Spring JPA and Repository stuff. I have an Auction class with a bunch of fields in it, and one of the field is category. I want a custom method in CrudRepository to filter the results by 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;
....}
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()
{
}
In the auction Repository, I added a method like this
@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);
}
Its throwing an error. Omit this method and everything works fine. Someone told me that this type of custom methods could be declared in CrudRepository and Spring will take care of doing the right thing using the methodName and the query hint we gave. Could someone point me in the right direction Please.
You need to add @Param
annotation to the method variable name so that you can refer it in your query. Code you have written is absolutely fine. In case you need access to EntityManager
, then you will need a custom repository.
@Query("from Auction a join a.category c where c.name=:categoryName")
public Iterable<Auction> findByCategory(@Param("categoryName") String categoryName);
@Param
can be omitted when using Java 8 and compiling with -parameters
.
Hope that helps.
Tip: Whenever you post a question always post the exception details as well. It helps in understanding the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With