stevecross
stevecross

Reputation: 5684

How to use arrays with Spring Data JDBC

I am trying to use Spring Data JDBC for my PostgreSQL database. I defined the following beans

@Data
class Report {

    @Id
    private Long id;

    private String name;

    private Set<Dimension> dimensions;

}

@Data
class Dimension {

    private String name;

    private Long[] filterIds;

}

and the corresponding 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
);

Then I tried to insert a report

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);

where repository is simply a CrudRepository<Report, Long>.

This gave me the following error

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

Can I somehow tell Spring Data JDBC how to map the array types?

Upvotes: 5

Views: 3371

Answers (2)

Jens Schauder
Jens Schauder

Reputation: 81907

As P44T answered this should work from version of 1.1 of Spring Data JDBC onwards just as you used it.

Original answer

It is currently not possible. There are issues for this. A starting point is this one: https://jira.spring.io/browse/DATAJDBC-259

Upvotes: 3

P44T
P44T

Reputation: 1179

With the release of Spring Data JDBC 1.1.0, this became possible. See the documentation here:

The properties of the following types are currently supported:

  • All primitive types and their boxed types (int, float, Integer, Float, and so on)

  • Enums get mapped to their name.

  • String

  • java.util.Date, java.time.LocalDate, java.time.LocalDateTime, and java.time.LocalTime

  • Arrays and Collections of the types mentioned above can be mapped to columns of array type if your database supports that.

  • ...

Upvotes: 5

Related Questions