0

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 :)

Badri Paudel
  • 1,365
  • 18
  • 19
  • Have you tried `post.getUser().getUserName()` ? Your `Post` entity is having `User` entity and not `user_id`, so when you do `post.getUser()`, you get whole `User` entity. – semicolon Nov 21 '20 at 16:50
  • @LUC1F3R yes I have. It doesn't work. Says exception evaluating expression. – Badri Paudel Nov 21 '20 at 17:00
  • Please post stacktrace then. – semicolon Nov 21 '20 at 17:02
  • @LUC1F3R this is the error ::: Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method getUsername() on null context object – Badri Paudel Nov 21 '20 at 17:08
  • Ok, please check if creating your own implementation of fetching all posts solves this issue, if not go through [this post](https://stackoverflow.com/questions/30173296/cacheevict-sometimes-missing-an-object-in-the-context-el1011e) – semicolon Nov 22 '20 at 16:57

1 Answers1

0

I am not sure if there is a default way to do this by repositories but here is how you can do it using HQL

add a function called getPostsByUsername in the repository and define it like so

@Query("SELECT p from POSTS p inner join p.user u where u.username=?1")
public List<Post> getPostsByUsername(String username);

note that the u.username the username is what the username field in the users table is named and not the actual column in the database.