anotheruser15564654

Author entity

Nov 7th, 2025
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. import com.fasterxml.jackson.annotation.JsonManagedReference;
  2.  
  3. import jakarta.persistence.*;
  4.  
  5. import java.util.List;
  6.  
  7. @Entity
  8. @Table(name = "authors")
  9. public class Author {
  10. @Id
  11. @GeneratedValue(strategy = GenerationType.IDENTITY)
  12. // @Column(name = "id")
  13. private long id;
  14.  
  15. @Column
  16. private String name;
  17.  
  18. @ManyToMany
  19. @JsonManagedReference // This is to avoid infinite loop. This is forward part of reference.
  20. @JoinTable(
  21. name = "AUTHOR_BOOK_MAPPING",
  22. joinColumns = @JoinColumn(name = "author_id"),
  23. inverseJoinColumns = @JoinColumn(name = "book_id"))
  24. private List<Book> books; // no need to specify implementation, Hibernate will use its own
  25.  
  26. public Author() {
  27. }
  28.  
  29. public Author(String name) {
  30. this.name = name;
  31. }
  32.  
  33. public Long getId() {
  34. return id;
  35. }
  36.  
  37. public void setId(long id) {
  38. this.id = id;
  39. }
  40.  
  41. public String getName() {
  42. return name;
  43. }
  44.  
  45. public void setName(String name) {
  46. this.name = name;
  47. }
  48.  
  49. public List<Book> getBooks() {
  50. return books;
  51. }
  52.  
  53. public void setBooks(List<Book> books) {
  54. this.books = books;
  55. }
  56.  
  57. public void addBook(Book book) {
  58. books.add(book);
  59. book.getAuthors().add(this);
  60. }
  61.  
  62. public void removeBook(Book book) {
  63. books.remove(book);
  64. book.getAuthors().remove(this);
  65. }
  66. }
  67.  
  68.  
Advertisement
Add Comment
Please, Sign In to add comment