Issue
How can I bind author_firstName and author_lastName from class Author with class Book? I work with h2 database, author_id and book_id are primary keys , I use postman
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "book_id")
private int id;
@Column(name = "book_title")
private String title;
@Column(name = "book_genre")
private String genre;
@Column(name = "author")
private String author;
}
@Entity
@Table(name="Author")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="author_id")
private int authorId;
@Column(name="author_firstName")
private String firstName;
@Column(name="author_lastName")
private String lastName;
@Column(name="author_birth")
private Date birth;
}
Solution
Insted of using String arguments to author
, you should convert this as a @ManyToOne relationship:
@Entity
@Table(name="Author")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="author_id")
private int authorId;
@Column(name="author_firstName")
private String firstName;
@Column(name="author_lastName")
private String lastName;
@Column(name="author_birth")
private Date birth;
@OneToMany(mappedBy = "author")
private List<Book> books;
}
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "book_id")
private int id;
@Column(name = "book_title")
private String title;
@Column(name = "book_genre")
private String genre;
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
}
With this model, you will be able to fetch data from any entrypoint, from books from an author (books written by a specific author), or, author who has books (collection of books written by an author).
You can use default implementation of findAll
Spring Data JPA implementation (will join automatically both tables if you use EAGER fetch type), or, build your own JPQL:
FROM Author a FETCH JOIN a.books b WHERE a.id = b.author
.
This will help the legibility of your code and improve your database data normalization.
Answered By - viniciusmfelix