【问题标题】:Spring boot: Access only associated column value in JPA without fetching the complete associated entitySpring boot:仅访问 JPA 中的关联列值而不获取完整的关联实体
【发布时间】:2019-06-14 13:52:00
【问题描述】:

我有两个实体。一个实体与另一个实体相关联。

@Entity
Class Author{
@Id
Long id;

@Column(name = "author_id")
private Ling authorId;
}


@Entity
class Book{
@Id
Long id;

@ManyToOne(fetch = FetchType.LAZY)
@column(name = "author_id", referencedColumnName = "author_id")
Author author;
}

在这里,假设设置了所有的 getter 和 setter。作者的 author_id 被保存在我的 Book 实体表中。

Book book = Book.findById(1);
book.getAuthor().getAuthorId();

当我这样做时,即使 author_id 存储在我的 book 表中,我也无法直接访问它。在这里,它触发另一个 sql 查询来获取作者实体,然后返回 author_id。有没有办法直接访问author_id。

【问题讨论】:

    标签: spring spring-boot jpa spring-data-jpa hibernate-mapping


    【解决方案1】:

    首先AuthorBook 实体中的LAZY 关联。 这意味着它不会成为获取图书的原始查询的一部分:

    Book book = Book.findById(1);
    

    这将通过访问该惰性关联的任何属性来触发:

    book.getAuthor().getAuthorId();
    

    您正在寻找的似乎是 JPQL 的投影:

    select a.id
    from Book b
      inner join b.author a
    where b.id = :id
    

    【讨论】:

    • 这里,我也需要完整的书籍实体。我的疑问是,当我获取书籍实体时,它会获取还包括 author_id 的完整行。所以,我想访问这个 author_id 而不需要对 DB 进行任何额外的查询。
    • JPA 中的 orm 不是这样工作的。您要么获得完整的实体,要么将所有内容投射到查询中。
    猜你喜欢
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多