java - 在 Spring Data JPA 存储库中的 JPQL 查询中返回 ManyToOne 列表

标签 java spring jpql

我有一个相对简单的域模型,涉及带有 PostgreSQL 的 Spring Boot 2 应用程序中的书籍。

简单的情况是多本书属于一个系列(有顺序),例如指环王 1、指环王 2 等

我的域实体是

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

    @NotNull
    @Column(nullable = false)
    private String title;

    @OneToMany(mappedBy = "series")
    @OrderColumn(name = "series_index")
    private List<BookEntity> books;

    //Getters and Setters left out
}

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

    @NotNull
    @Column(nullable = false)
    private String title;

    @ManyToOne
    @JoinColumn(name="series_id")
    private SeriesEntity series;

    //Getters/setters and other unimportant properties left out
}

有一个“DTO”,我想直接从数据库中检索它,然后我可以在前端使用它:

public class SeriesDto {
    private Long id;
    private String title;
    private Locale locale;
    private List<Book> books;

    public SeriesDto(Long id, String title, Locale locale, List<Book> books) {
        this.id = id;
        this.title = title;
        this.locale = locale;
        this.books = books;
    }

    public static class Book {
        private Long id;
        private String title;

        public Book(Long id, String title) {
            this.id = id;
            this.title = title;
        }
    }
}

在没有书籍的情况下创建 dto(在 IntelliJ 的 JPA 控制台中测试):

从 SeriesEntity s WHERE s.id = :id 中选择新的 series.query.SeriesDto(s.id, s.title, s.locale)

但是如何映射 OneToMany 关系呢?

选择不同的 s.id 作为 series_id、s.title、s.locale、books FROM SeriesEntity s INNER JOIN s.books books WHERE s.id = :id

这会返回多行,例如:

1   Lord of the Rings   de  46  Der Herr der Ringe Band 1: Die Gefährten    1   Lord of the Rings   de
1   Lord of the Rings   de  47  Der Herr der Ringe Band 2: Die zwei Türme   1   Lord of the Rings   de

另一个问题是它会再次返回系列信息,因为它链接到 Book 实体。

有没有办法在 JPQL 中自动聚合它,这样我就不必编写 Java 方法?或者我至少可以提供一个映射函数吗?

谢谢!

最佳答案

您应该使用:

SELECT new series.query.SeriesDto(s.id, s.title, s.locale, s.books)
FROM SeriesEntity s 
WHERE s.id = :id

可以看到查询日志:cross join(你的是inner join)

关于java - 在 Spring Data JPA 存储库中的 JPQL 查询中返回 ManyToOne 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57901343/

相关文章:

java - 带有字符串的 JPQL LIKE 语法

java - 在 JPQL 查询中设置可选参数

java - 在 SpringMVC 中启用日志记录,而不是使用 Spring-boot

java - 无法在 Spring 3.2.8 和 junit 4.4 中 Autowiring 现场执行 Junit 测试

hibernate - 带枚举的 JPQL in 子句

Java - 同步块(synchronized block)的工作方式与方法不同

Java路径: Build and absolute path

java - 在 EclipseLink 中的正常查找操作中批量获取

java - 有没有办法从异步方法绘制到 JPanel 上?

java - 如何使用 .htaccess 来加速 Spring 网站为不同类型的文件自定义浏览器缓存