spring-data-jpa 如何返回所有保存在DB中的联系人?

uoifb46i  于 2022-11-10  发布在  Spring
关注(0)|答案(2)|浏览(159)

我创建了一个保存联系人的应用程序。我无法返回所有保存在数据库中的联系人,查询没有返回唯一的结果:2
我的控制器

public ModelAndView getAllContacts() {
    ModelAndView mav = new ModelAndView("getAllUser.jsp");
    User user = userda.getAllContacts();
    mav.addObject(user);
    return mav;

我的JPA储存库

@Query(value ="SELECT * from USER", nativeQuery = true)
User getAllContacts();

模型类别

@Entity(name = "USER")
@Table(name = "USER")
public class User {

    @Id
    private long id;
    private String name;

    public String toString() {
        return "Person Name is " + " : " + name + " and " + " Mobile Number is " + " : " + id;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
gk7wooem

gk7wooem1#

您的存储库假设只有一个条目User getAllContacts();。您加载所有联系人,需要一个用户列表... List<User> getAllContacts()
提示:您的repo也可以从CRUD Repo继承。这里有一些现成的方法。

yquaqz18

yquaqz182#

您已获得联系人列表,例如

public List<Contact> getAllContact(){
}

在“我的案例”中,我获得图书实体

图书.java

@Entity
@Table(name = "books")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String bookname;
    @OneToOne(cascade = CascadeType.ALL)
    @JsonManagedReference
    private Author author;
}

书道.java

public interface BookDao extends CrudRepository<Book, Integer> {
    public Book findById(int id);
}

图书服务.java

@Component
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    //get all lists
    public List<Book> getAllBooks(){
        List<Book> list = (List<Book>) this.bookRepository.findAll();
        return list;
    }

    //get book by id
    public Book getBookById(int id){
        Book book = this.bookRepository.findById(id);
        return book;
    }
}

图书控制器.java

@RestController
// @RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    //get all books handler
    @GetMapping("/books")
    public List<Book> getBook(){
       List<Book> list =  this.bookService.getAllBooks();
    }
}

相关问题