我们可以在使用 @RepositoryRestResource 的同时使用 Spring Data REST 创建自定义查询吗?
我是 Spring Boot 的新手,我试图使用 Spring-boot JPA 创建一个简单的 REST 服务.首先,我使用简单的 @Repository
工作正常,我可以为我的类中定义的属性编写自定义 Query 方法.但是当我使用 @RepositoryRestResource
时,我无法创建自定义 Query 方法.主键和其他操作的基本发现正在发生,但我无法创建任何自定义查询.
I am new to spring boot, I was trying to create a simple REST service using Spring-boot JPA. First I used simple @Repository
which works fine, I can write custom Query method for the properties defined in my class. But when I use @RepositoryRestResource
I am not able to create custom Query methods. Basic finding on primary key and other operations are happening but I can not create any custom Query.
package com.example.demo.Model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue
int id;
int isbn;
String name;
String author;
double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getIsbn() {
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
这是仓库
package com.example.demo.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;
import com.example.demo.Model.Book;
@RepositoryRestResource(collectionResourceRel = "books", path = "books")
public interface BookRepo extends JpaRepository<Book, Integer> {
//I want this query to work same as it does for primary Key id.
public Book findByName(@Param("name") String name);
//Same for this
public Book findByIsbn(@Param("isbn") String isbn);
}
由于我没有映射任何用于按名称搜索的 url,我正在尝试这样搜索 localhost:8080/books/?name=java
是否正确?对于上面的 url,它的行为就像 localhost:8080/books
并忽略后续部分并提供所有书籍的详细信息.我只想有两个类并执行所有基本的休息操作并创建自定义查询.
Since I am not mapping any url for searching by name, I am trying to search like this localhost:8080/books/?name=java
Is it correct?
For above url it simply behaves like localhost:8080/books
and ignore subsequent part and provides all books details.
I just want to have two classes and perform all basic rest operation and create custom Query.
提前致谢.
你需要在你的uri中添加thermsearch"和方法名,像这样:
you need add the therm "search" and the method name in yout uri, like this:
localhost:8080/books/search/findByName?name=java
localhost:8080/books/search/findByName?name=java