I have the 3 following Entities in my project.
@Entity
public class Review {
@Id
@GeneratedValue
private int reviewId;
@OneToMany(mappedBy="review", cascade = CascadeType.ALL)
private List<Comment> comments;
@ManyToOne
private User user;
}
@Entity
public class Comment {
@Id
@GeneratedValue
private int commentId;
@ManyToOne
private Review review;
@ManyToOne
private User user;
}
@Entity
public class User {
@Id @GeneratedValue
private Long userId;
@OneToMany(mappedBy="user", cascade = CascadeType.ALL)
private List<Comment> comments;
@OneToMany(mappedBy="user", cascade = CascadeType.ALL)
private List<Review> reviews;
}
I want to use JPA to fetch every Comment
on a particular Review
, such that under the page of each Review
, I can display the name of the User
who commented, along with the actual Comment
. So when I visit the page http://localhost:8080/review/view/5
, I want to be able to see the review in addition to all comments made on it, along with the names of the users who added the comments.
Is this achievable without writing the SQL myself? If yes, how?
By using this annotation, we define a pseudo foreign key relationship between the two entities. Finally, by setting the foreignKey property to @javax.persistence.ForeignKey (value = ConstraintMode.NO_CONSTRAINT), we instruct the JPA provider to not generate the foreign key constraint. 5.
Introduction In this post, we feature a comprehensive Example on Hibernate Foreign Key. Foreign key refers to single column or group of columns in table that link data present in another table through its primary key. A Foreign key can’t exist without its parent key but viceversa is not true. Example – A Menu can have submenus.
JPA finder methods are the most powerful methods, we can create finder methods to select the records from the database without writing SQL queries. Behind the scenes, Data JPA will create SQL queries based on the finder method and execute the query for us.
findByName(String name) To create a finder method for the location field then we need to create a method like this – findByLocation(String location) Behind the scenes, Data JPA will create a SQL query like this – SELECT * FROM employee WHERE name="employee name"; SELECT * FROM employee WHERE location="location name";
Use an entity graph in your spring data jpa Repository:
@EntityGraph(value = "Review.comments", type = EntityGraphType.FETCH)
public Review findByReviewId(int id);
or explicitly define a @Query:
@Query("from Review r inner join fetch r.comments where r.reviewId = :id")
User findByReviewId(@Param("id") int id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With