【问题标题】:Java - Get username from DBJava - 从数据库中获取用户名
【发布时间】:2019-07-16 09:39:20
【问题描述】:

我有一个副项目网站,人们可以在这里评论东西,现在我需要显示用户的 cmets 和评论者的用户名。问题是我无法获得登录用户的用户名。

评论示例:

1) 评论者 - Shelo
测试评论

2) 评论者 - ProGa
测试评论 2

现在,问题是如果我尝试获取“当前登录”用户的用户名,当用户登录时两个 cmet 将具有相同的用户名

Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String name = loggedInUser.getName();

上面的这个代码示例是您如何获取当前登录的用户。因此,如果我使用此代码并尝试通过 String name 显示用户名,并假设某些用户使用用户名 - “Davos” 登录,两个 cmets 将如下所示 - :

1) 评论者 - 达沃斯
测试评论

2) 评论者 - 达沃斯
测试评论 2

我需要的是 - 获取登录用户的用户名,如果他留下评论,则显示他的用户名。当他注销或其他用户登录时,评论的“用户名”应该保持不变,并且不能根据当前登录的人而改变。

My Database Schema

控制器类(仅相关代码):

@GetMapping("/foodDescription/{id}")
public String foodDescriptionPage(Model model, @PathVariable(name = "id") String id){
    menuRepository.findById(id).ifPresent(o -> model.addAttribute("menu", o));


    return "food-description";
}

@PostMapping("/postComment/{id}")
public String postComment(@RequestParam String myComment, Model model, @PathVariable(name = "id") String id){

    Optional<Menu> menu = menuRepository.findById(id);
    menuRepository.findById(id).ifPresent(o -> model.addAttribute("menu", o));
    List<Comments> myCommentsList = menu.get().getComments();
    myCommentsList.add(new Comments(myComment));

    menu.get().setComments(myCommentsList);
    menuRepository.save(menu.get());

    return "food-description";
}

food-description.html(仅限 cmets 部分的相关代码):

    <h3 th:text = "Comments">asd</h3>
<form th:action = "@{/postComment/{myMenuId}(myMenuId=${menu.id})}" method="POST">
    <textarea rows="2" cols="100" name="myComment"></textarea>
    <input type="submit" th:value="Add"/>
</form>

<div class="comment" th:each="com : ${menu.comments}">
    <h3 th:text="Display Commenter's Username here">Commenter's Username</h3>
    <ul>
        <li th:text = "${com.comment}">Comment</li>
    </ul>
</div>

用户实体:

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "username")
    private String userName;

    @Column(name = "password")
    private String password;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinTable(name = "users_role",
    joinColumns = @JoinColumn(name = "user_id"),
    inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Role role;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinTable(name = "users_comments",
    joinColumns = @JoinColumn(name = "user_id"),
    inverseJoinColumns = @JoinColumn(name = "comment_id"))
    private List<Comments> comments = new ArrayList<>();

    // Getters/Setters/Constructor

}

评论实体:

@Entity
@Table(name = "comments")
public class Comments {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "comment")
    private String comment;

    // Getters/Setters/Constructor

【问题讨论】:

  • 这是建模的基础。您需要通过将userId 属性添加到comment 实体来添加对评论的author 的引用。然后每当你需要显示作者的名字时,你从数据库中查询它
  • Manh 说的是正确的。你已经有一个从UserComments@OneToMany 关系,你只需要添加一个从CommentsUser@ManyToOne 关系。

标签: java spring-boot spring-security spring-data-jpa thymeleaf


【解决方案1】:

如 cmets 中所述,您必须更改数据建模。

例如你可以实现这样的东西:

@Entity
public class User {
   @OneToMany()
   public Collection<Comment> comments;
   ...
}

@Entity
public class Comment {
   @ManyToOne
   @JoinColumn(name="user_fk")
   public User user;
   ...
}

在这种情况下,您有一个双向关联,并且您可以在代码中(以及在 html 模板中)获得用户的评论。当然,如果您手动进行,您也必须更改您的数据库模型。

【讨论】:

  • 所以我添加了@ManyToOne 关联,并在创建comment 后正确添加到数据库中。但是,当我尝试通过 -comment.getUser().getUserName() 访问评论的 user - 我得到 nullPointerException
  • 为什么我需要更改数据库模型?
  • 你的数据库的评论表中有user_fk列吗?
  • 是的。我与User-&gt;user_role-&gt;roleMenu-&gt;menu_ingredient-&gt;ingredientsMenu-&gt;menu_comments-&gt;commentsUser-&gt;user_comments-&gt;comments有关联。
  • 我想我找到了获取用户名的正确途径,我会告诉你的:)
猜你喜欢
  • 2011-12-03
  • 2021-01-19
  • 1970-01-01
  • 2016-03-22
  • 2018-06-16
  • 1970-01-01
  • 2011-06-09
  • 1970-01-01
  • 2016-05-01
相关资源
最近更新 更多