How to return all the contacts which are all saved in DB?

Viewed 35

I have created a contact-saving app. I am not able to return all the contacts that are all saved in DB, the query did not return a unique result: 2

My Controller

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

My JPA Repository

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

Model class

@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;
    }
}
2 Answers

Your repo assume only ONE entry User getAllContacts();. You load all contacts, you need a list of user ... List<User> getAllContacts()

Hint: Your repo can also inherit from CRUD Repo. There you have some methods out of the box.

You have get list of Contacts e.g

public List<Contact> getAllContact(){
}

In My Case i get book entity

Book.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;
}

BookDao.java

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

BookService.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;
    }
}

BookController.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();
    }
}
Related