简体   繁体   English

无法从 JPA Hibernate 的反面看到拥有方

[英]Can't see the owning side from an inverse side JPA Hibernate

I have this piece of code:我有这段代码:

@Entity(name = "Person")
@Table(name = "person")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany( mappedBy = "person", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Post> posts = new ArrayList<Post>();
}

and:和:

@Entity(name = "Post")
@Table(name = "post")

public class Post extends BaseEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(
        fetch = FetchType.LAZY
)
@JoinColumn(name="person_id")
Person person;
@Column(name = "text", nullable = true)
private String text;
}

The issue is that when I connect to my Hibernate database I can see the Person Id in the Post entity, but can't see the Post id in the Person entity.问题是当我连接到我的 Hibernate 数据库时,我可以在 Post 实体中看到 Person Id,但在 Person 实体中看不到 Post id。 There is no person_post table neither.也没有 person_post 表。 How can I see the posts that belong to the person?如何查看属于此人的帖子? I want to list the posts from the person using thymeleaf but something like this doesn't work:我想列出使用百里香叶的人的帖子,但这样的事情不起作用:

  <tr th:each="post : ${person.posts}">
            <td th:text="${post.text}">nothing in here</td>
 </tr>

Error says that thymeleaf can't see the posts in Person.错误说 thymeleaf 无法看到 Person 中的帖子。 Is this how it is supposed to work?这是它应该如何工作? How can I list the posts from person?如何列出来自个人的帖子? Thanks in advance, Tomasz提前致谢,托马斯

You are defining a 1:N relationshop, that means that in the Post table there is the person_id foreign key, but no intermediate table person_post.您正在定义一个 1:N 关系商店,这意味着在 Post 表中有 person_id 外键,但没有中间表 person_post。 However person.posts should give you the result you are looking for - can you add the logic how you add the Person / Post and the controller method of the template?然而 person.posts 应该给你你正在寻找的结果 - 你能添加逻辑你如何添加 Person / Post 和模板的控制器方法吗?

It's recommended to user LAZY fetching, by the way: https://vladmihalcea.com/eager-fetching-is-a-code-smell/顺便推荐给用户 LAZY fetching: https : //vladmihalcea.com/eager-fetching-is-a-code-smell/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM