【问题标题】:How to use arrays with Spring Data JDBC如何在 Spring Data JDBC 中使用数组
【发布时间】:2019-01-22 15:35:13
【问题描述】:

我正在尝试将 Spring Data JDBC 用于我的 PostgreSQL 数据库。我定义了以下bean

@Data
class Report {

    @Id
    private Long id;

    private String name;

    private Set<Dimension> dimensions;

}

@Data
class Dimension {

    private String name;

    private Long[] filterIds;

}

以及相应的 DDL

CREATE TABLE report (
    id bigserial PRIMARY KEY,
    name text NOT NULL
);

CREATE TABLE dimension (
    id bigserial PRIMARY KEY ,
    report bigint,
    name text,
    filter_ids bigint[],
    FOREIGN KEY (report) REFERENCES report(id) ON DELETE CASCADE ON UPDATE CASCADE
);

然后我尝试插入报告

final Dimension dimension = new Dimension();

dimension.setName("xyz");
dimension.setFilterIds(new Long[]{ 1L, 2L, 3L });

final Report report = new Report();

report.setName("xyz");
report.setDimensions(Collections.singleton(dimension));

repository.save(report);

其中repository 只是一个CrudRepository&lt;Report, Long&gt;

这给了我以下错误

org.postgresql.util.PSQLException: ERROR: column "filter_ids" is of type bigint[] but expression is of type bigint
  Hinweis: You will need to rewrite or cast the expression.
  Position: 116

我能告诉 Spring Data JDBC 如何映射数组类型吗?

【问题讨论】:

    标签: spring-data-jdbc


    【解决方案1】:

    随着 Spring Data JDBC 1.1.0 的发布,这成为可能。参见文档here

    目前支持以下类型的属性:

    • 所有原始类型及其装箱类型(int、float、Integer、Float 等)

    • 枚举被映射到它们的名字。

    • 字符串

    • java.util.Date、java.time.LocalDate、java.time.LocalDateTime 和 java.time.LocalTime

    • 如果您的数据库支持,上述类型的数组和集合可以映射到数组类型的列。

    • ...

    【讨论】:

      【解决方案2】:

      作为P44T answered,这应该可以从 Spring Data JDBC 1.1 版本开始,就像你使用它一样。

      原答案

      目前不可能。这方面存在问题。起点是这个:https://jira.spring.io/browse/DATAJDBC-259

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-18
        • 1970-01-01
        • 2021-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-17
        • 2018-09-29
        相关资源
        最近更新 更多