rockstar_77 rockstar_77 - 3 months ago 11
Java Question

REST not returning all the values in my DB

Hello all i am not getting all the values of the in the db while returning a rest reponse.

Below is my DAO

public class BooksDAO {

public List<Book> getAllBooks() throws SQLException, ClassNotFoundException {

List<Book> arrBook = null;
Book e = null;
Class.forName("com.mysql.jdbc.Driver");
JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:mysql://localhost:3306/books");
rowSet.setUsername("xxxx");
rowSet.setPassword("xxxx");
rowSet.setCommand("select * from books.library");
rowSet.execute();

while (rowSet.next()) {

e = new Book(rowSet.getInt(1), rowSet.getString(2), rowSet.getString(3), rowSet.getString(4));
arrBook = new ArrayList<Book>();
arrBook.add(e);

}

return arrBook;

}


Below is my Service

public class BookService {

BooksDAO booksDao = new BooksDAO();

//private Map<Integer, Book> books = Database.getBooks();

/*public BookService() {
books.put(1, new Book(1, "The Adventures of Tom Sawyer", "$28", "Mark Twain"));
books.put(2, new Book(2, "The Adventures of Sherlock Holmes", "$17", "Arthur Conan Doyle"));
}*/

public List<Book> getAllBooks() throws SQLException, ClassNotFoundException {

return new ArrayList<Book>(booksDao.getAllBooks());

}


Below is my resource

@GET
@Produces({MediaType.APPLICATION_JSON + ";charset=UTF-8",MediaType.APPLICATION_XML + ";charset=utf-8"})
public Response getBooks(@QueryParam("format") String format) throws SQLException, ClassNotFoundException {

return Response.status(Status.OK).entity((new GenericEntity<List<Book>>(bookService.getAllBooks()) {
})).header(HttpHeaders.CONTENT_TYPE, "XML".equalsIgnoreCase(format)
? MediaType.APPLICATION_XML + ";charset=UTF-8" : MediaType.APPLICATION_JSON + ";charset=UTF-8").build();

}


I am getting the below REST response

[
{
"author": "Arthur Conan Doyle",
"id": 2,
"links": [],
"name": "The Adventures of Sherlock Holmes",
"price": "$17"
}
]


It is returning the last one but not the whole list...

Where did I do the mistake?

Thank you

Answer

Within your BookDao#getAllBooks method implementation, your are reconstructing the ArrayList holding your results for each element within the same loop traversing your ResultSet:

while (rowSet.next()) {
  e = new Book(rowSet.getInt(1), rowSet.getString(2), rowSet.getString(3),rowSet.getString(4));
  arrBook = new ArrayList<Book>();
  arrBook.add(e);
}

The list should be initialized once before looping through the ResultSet elements:

arrBook = new ArrayList<Book>();
while (rowSet.next()) {
  e = new Book(rowSet.getInt(1), rowSet.getString(2), rowSet.getString(3),rowSet.getString(4));
  arrBook.add(e);
}