Search code examples
javaspringpostgresqlspring-data-jdbc

Problem with an entity using just a list of values in Spring Data JDBC


I'm using Spring-Boot 2.5.0, Java 11, a Postgres DB and Lombok. I have e.g. a list of articles as an entity:

@Data
@Builder
@AllArgsConstructor
public class Articles {

    @Id
    private Long id;


    @Builder.Default
    private List<Article> articles = new ArrayList<>();
}

and the Article value:

@Data
@Builder
@AllArgsConstructor
public class Article {
    private String name;
    private Integer price;
}

and the repository:

@Repository
public interface ArticlesRepository extends CrudRepository<Articles, Long> {
}

The db schema looks like this:

CREATE TABLE "articles" (
  "id"                  BIGSERIAL  NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE "article" (
  "name"               VARCHAR(255),
  "price"              INTEGER,
  "articles"           BIGINT,
  "articles_key"       INTEGER
);

And testing it:

var article1 = Article.builder().name("T-Shirt").price(1635).build();
var article2 = Article.builder().name("Shoes").price(5670).build();
var articles = Articles.builder().articles(List.of(article1, article2)).build();
articlesRepository.save(articles);

will cause an exception:

Caused by: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [INSERT INTO "articles" VALUES ()]; nested exception is org.postgresql.util.PSQLException: ERROR: syntax error at or near ")"

If I just add a field to Articles like e.g. name in this case, it works fine:

@Data
@Builder
@AllArgsConstructor
public class Articles {

    @Id
    private Long id;

    private String name;

    @Builder.Default
    private List<Article> articles = new ArrayList<>();
}

Solution

  • This is a current limitation of Spring Data JDBC with some databases.

    Some databases require an insert to have at least one column.

    As a workaround you could either add a dummy column that you don't actually use. Alternatively you could not autogenerate the id.

    Please consider creating an issue so that this gets eventually fixed.