|
| 1 | +package com.bookstore.entity; |
| 2 | + |
| 3 | +import java.io.Serializable; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.Iterator; |
| 6 | +import java.util.List; |
| 7 | +import javax.persistence.CascadeType; |
| 8 | +import javax.persistence.Entity; |
| 9 | +import javax.persistence.GeneratedValue; |
| 10 | +import javax.persistence.GenerationType; |
| 11 | +import javax.persistence.Id; |
| 12 | +import javax.persistence.OneToMany; |
| 13 | + |
| 14 | +@Entity |
| 15 | +public class Author implements Serializable { |
| 16 | + |
| 17 | + private static final long serialVersionUID = 1L; |
| 18 | + |
| 19 | + @Id |
| 20 | + @GeneratedValue(strategy = GenerationType.IDENTITY) |
| 21 | + private Long id; |
| 22 | + |
| 23 | + private String name; |
| 24 | + private String genre; |
| 25 | + private int age; |
| 26 | + |
| 27 | + @OneToMany(cascade = CascadeType.ALL, |
| 28 | + mappedBy = "author", orphanRemoval = true) |
| 29 | + private List<Book> books = new ArrayList<>(); |
| 30 | + |
| 31 | + public void addBook(Book book) { |
| 32 | + this.books.add(book); |
| 33 | + book.setAuthor(this); |
| 34 | + } |
| 35 | + |
| 36 | + public void removeBook(Book book) { |
| 37 | + book.setAuthor(null); |
| 38 | + this.books.remove(book); |
| 39 | + } |
| 40 | + |
| 41 | + public void removeBooks() { |
| 42 | + Iterator<Book> iterator = this.books.iterator(); |
| 43 | + |
| 44 | + while (iterator.hasNext()) { |
| 45 | + Book book = iterator.next(); |
| 46 | + |
| 47 | + book.setAuthor(null); |
| 48 | + iterator.remove(); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public Long getId() { |
| 53 | + return id; |
| 54 | + } |
| 55 | + |
| 56 | + public void setId(Long id) { |
| 57 | + this.id = id; |
| 58 | + } |
| 59 | + |
| 60 | + public String getName() { |
| 61 | + return name; |
| 62 | + } |
| 63 | + |
| 64 | + public void setName(String name) { |
| 65 | + this.name = name; |
| 66 | + } |
| 67 | + |
| 68 | + public String getGenre() { |
| 69 | + return genre; |
| 70 | + } |
| 71 | + |
| 72 | + public void setGenre(String genre) { |
| 73 | + this.genre = genre; |
| 74 | + } |
| 75 | + |
| 76 | + public int getAge() { |
| 77 | + return age; |
| 78 | + } |
| 79 | + |
| 80 | + public void setAge(int age) { |
| 81 | + this.age = age; |
| 82 | + } |
| 83 | + |
| 84 | + public List<Book> getBooks() { |
| 85 | + return books; |
| 86 | + } |
| 87 | + |
| 88 | + public void setBooks(List<Book> books) { |
| 89 | + this.books = books; |
| 90 | + } |
| 91 | + |
| 92 | + @Override |
| 93 | + public String toString() { |
| 94 | + return "Author{" + "id=" + id + ", name=" + name |
| 95 | + + ", genre=" + genre + ", age=" + age + '}'; |
| 96 | + } |
| 97 | + |
| 98 | +} |
0 commit comments