So I'm building a simple API in Spring Boot that retrieves specific books and their authors form a database. The book has an id, name, year that it was published and a foreign key for the Author of that book. Here is the model:
@Entity
@Table(name="book", schema = "book_store")
public class Book {
@Id
private long id;
private String name;
private int released;
@ManyToOne
@JoinColumn(name="author_id")
private Author author;
public Book() {
}
public Book(String name, int released, Author author){
this.name=name;
this.released=released;
this.author=author;
}
//And also the getters and setters
Here is the repository:
public interface BookRepository extends JpaRepository<Book, Long> {
}
And the service implementaiton:
@Service
public class BookServiceImplementation implements BookService {
@Autowired
private BookRepository bookRepository;
public List<Book> getAll(){
return bookRepository.findAll();
}
public List<Book> getWithoutAuthor(){
List<Book> newList=bookRepository.findAll();
newList.forEach(p ->p.setAuthor(null));
return newList;
}
}
So when I go to /api/book/noAuthor it calls the getWithoutAuthor() method and returns this JSON response:
[{"id":1,"name":"Anna Karenina","released":1877,"author":null},
{"id":2,"name":"War And Peace","released":1869,"author":null},
{"id":3,"name":"To Kill A Mockingbird","released":1960,"author":null},
{"id":4,"name":"Go Set A Watchman","released":2015,"author":null},
{"id":5,"name":"The Catcher In The Rye","released":1951,"author":null},
{"id":6,"name":"Franny And Zooey","released":1961,"author":null}]
The author is being set to null which is what I want however is there a way to make the response no return "author":null at all?
Because in this case the "author" field is pretty much useless and I want to remove it completely because I want to have a cleaner response.
I also tried to create a custom JSON response by building a list of Maps with keys and values. While the method does work it does not return a List of Books which is what I want for the controller to return in the end.
Does anyone know a different method?