spring 如何获取JPA实体的外键字段的引用ID?

hzbexzde  于 5个月前  发布在  Spring
关注(0)|答案(3)|浏览(81)

在一个使用Sping Boot 的应用程序中,假设我有两个实体(AuthorPost),如下所示:

@Entity
public class Author
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
}

@Entity
public class Post
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private Author author;
}

字符串
请注意,Author字段上的@ManyToOne注解的fetch设置为LAZY。现在假设我使用findById()从相关的JPARepository<Post,Integer>中通过id获取了一个Post实体,所有相关的字段值都应该是可用的,对吗?如果我只需要这个postauthor_id,我如何才能在不进行另一个数据库调用的情况下获得它?使用post.getAuthor()的示例进行另一个调用,我想避免它。我只需要author_id
抱歉,这个问题说得不好,但找不到好的。
P.S.

  • Spring/JPA/Java新手在这里。
  • 也许这个问题已经在其他地方得到了回答;但找不到一个。
  • 请不要建议EAGER加载。
wz1wpwve

wz1wpwve1#

您可以在实体中保存author_id

@ManyToOne(fetch = FetchType.LAZY, targetEntity = Author.class)
@JoinColumn(name = "author_id")
private Integer authorId;

字符串
你也可以有两个字段:authorIdauthor与相同的JoinColumn,但在这种情况下,你必须标记其中一个与insertable=falseupdatable =false

fcg9iug3

fcg9iug32#

感谢@Anton Kozub提供的答案/线索。虽然我不能让它工作(可能是他部分展示了它),但我得到了一个线索,最后在Post表中做了这个:

@Entity
public class Post
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    @Column(name = "author_id", updatable=false, insertable=false)
    private Integer authorId;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private Author author;
}

字符串
和它的工作.

t1rydlwq

t1rydlwq3#

这是不可能阻止的。最好使用EAGER加载。但如果你想只获得Post和作者的id,我建议使用nativeQuery。

public interface PostAuthorProjection {

   Integer getId();

   Integer getAuthorId();

}

字符串
存储库

public interface PostRepo extends CrudRepository<Post, Integer> {

   @Query(nativeQuery = true, value = "select p.id, p.author_id from post p where p.id = ?1")
   PostAuthorProjection findPostById(Integer id);
}


以上就是使用getAuthorId()获取author. id的全部内容,希望对大家有帮助。

相关问题