I am new in spring/hibernate technologies, I have tried to find an information about it, but failed, so if you can help I will be so thankful!
I need to display a JSON response in browser of multiple tables, one of the table has primary key for another one.
My entities:
@Entity
@Table
@ToString
public class Book {
@Id
@GeneratedValue(strategy = AUTO)
@JsonView(Views.IdName.class)
private Long book_id;
@JsonView(Views.IdName.class)
private String name;
@Column(length = 1000000)
private String text;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="author_id")
@JsonView(Views.IdName.class)
private Author author;
// ....get/set methods
Another one:
@Entity
@Table
@ToString
public class Page {
@Id
@GeneratedValue(strategy = AUTO)
private Long id;
@Column(length = 1000000)
private String text;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "book_id")
private Book book;
// ...get/set methods
My controllers:
@RestController
@RequestMapping("books")
public class BookController {
private final BookRepo bookRepo;
@Autowired
public BookController(BookRepo bookRepo) {
this.bookRepo = bookRepo;
}
@GetMapping
@JsonView(Views.IdName.class)
public List<Book> getAll() {
return bookRepo.findAll();
}
@GetMapping("{id}")
public Book getOne(@PathVariable("id") Book book) {
return book;
}
}
Another one:
@RestController
@RequestMapping("authors")
public class AuthorController {
private final AuthorRepo authorRepo;
@Autowired
public AuthorController(AuthorRepo authorRepo) {
this.authorRepo = authorRepo;
}
@GetMapping
public List<Author> getAll() {
return authorRepo.findAll();
}
@GetMapping("{id}")
public Optional<Author> getOne(@PathVariable("id") Long id) {
return authorRepo.findById(id);
}
}
And also repo for interaction with DB (they are the similar):
public interface AuthorRepo extends JpaRepository<Author, Long> {
}
So when I make a request for get all books, I take the following JSON:
Bit I want different result, something like:
[
{
"book_id" : 1,
"name": "name 1 book",
"author" :
{
"author_id" : 1,
"name": "some_name"
}
}
]
Also, when I tried to make a request for /authors/1, I will get the following response (something like recursion) :
So any help how can I handle with it? Thank you!