【发布时间】:2021-06-10 15:56:11
【问题描述】:
我知道这个问题的标题不清楚,但在不喜欢之前让我解释一下我的问题。
我有一个使用 JPA 和百里香的 java spring 社交媒体。
用户有 ID、用户名和创建日期。
在帖子表中有一个名为“authorid”的字段,因此当有人发布新帖子时,系统只会写入他的用户 ID,而不是他的用户名。
现在,我在网站上有一个页面,位于“localhost:8080/showAllPosts/”,它显示了从最近到最近的所有应用程序帖子。控制器看起来像这样:
@Controller
public class MyController {
@GetMapping("/showAllPosts")
public String showAllPosts(Model model) {
List<Post> post = new ArrayList<>();
model.addAttribute("post", post);
List<Post> posts = postRepository.findAll();
model.addAttibute("posts", posts);
return "showallposts.html";
}
}
showallposts.html 页面如下所示:
<table>
<tbody>
<tr th:if="${posts.empty}">
<td colspan="2">No Posts Available</td>
</tr>
<tr th:each="post : ${posts}">
<td>
<span th:text="'posted by ' + ${post.authorid}>
<span th:text="${post.postcontent}"></span>
<br>
</td>
<td>
</td>
</tr>
</tbody>
</table>
如您所见,它显示了帖子内容,以及“发布者”加上作者。唯一的问题是 post.authorid 返回发布用户的数字 ID,而我想要用户名。我们可以对用户模型做些什么吗?
请注意,在用户存储库中我有这个方法:
@Query(value = "SELECT u.username FROM Users u WHERE u.userid = ?1")
public String findUsernameById(Long userid);
感谢所有帮助!
【问题讨论】:
标签: java spring jpa data-binding thymeleaf