I have two tables : One is the users table and another is the posts table. Users table stores user's information and posts table stores relevant posts of the corresponding user, so user's id is now a foreign key in posts table .
In User.java
@OneToMany(mappedBy = "user")
private List<Post> posts;
and in Post.java
@ManyToOne()
@JoinColumn( name = "user_id")
private User user;
Here, everything is working well, tables have been structured as expected.
Now, when I hit a particular endpoint , "/posts" I need to retrieve all the posts from the posts table but this time not the user_id but the corresponding username from that id which is in users table. How to achieve that ?
Endpoint for retrieving all the posts(PostController.java).
@GetMapping("/posts")
public String getPosts(Model model) {
List<Post> postList = postService.getPosts();
model.addAttribute("posts", postList);
return "Post";
}
PostService.java
public List<Post> getPosts() {
return postRepository.findAllByOrderByIdDesc();
}
I am retrieving posts in Post.html using Thymeleaf.
Any informations regarding this would be helpful. Thanks :)