java 在JPAQuery中使用select语句获取连接

hgc7kmma  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(133)

我有两个实体:博客文章和博客标签

@Entity
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class BlogArticle {
    private UUID id;
    private String title;

    // other fields...

    @ManyToMany(mappedBy = "articles")
    private List<BlogTag> tags = new ArrayList<>();
}
@Entity
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class BlogTag {
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    @Setter(AccessLevel.NONE)
    private UUID id;

    @Column(nullable = false)
    private String name;

    @ManyToMany(fetch = FetchType.LAZY)
    @Builder.Default
    @ToString.Exclude
    private List<BlogArticle> articles = new ArrayList<>();
}

当我像这样用JPAQuery获取它们时:

Tuple tuple = new JPAQuery<Tuple>(entityManager)
                .from(qBlogArticle)
                .innerJoin(qBlogArticle.tags)
                .fetchJoin()
                .where(qBlogArticle.slug.eq(slug))
                .fetchOne();

它可以工作,但是当我添加一个.select(qBlogArticle.title, qBlogArticle.tags时,它抛出一个错误,说“查询指定了连接获取,但获取的关联的所有者不在选择列表中”
如何只选择我想要的字段,并获取连接标记(以便可以在一个查询中获取它们)?

kqlmhetl

kqlmhetl1#

Hibernate只允许FETCH JOINS,如果fetch关联的所有者被投影到select子句中。因此,使它工作的方法是将qBlogArticle添加到select.select(qBlogArticle,qBlogArticle.title,qBlogArticle.tags)

相关问题