2

I read several similar posts here on SO but nothing has helped so far. I am using Java EE 8, Open Liberty 20.0.0.6 and PostgreSQL 12.

I run my locally using Docker which initializes the schema with:

CREATE TABLE IF NOT EXISTS PUBLIC.tab_todo
(
    col_id     SERIAL PRIMARY KEY,
    col_name   VARCHAR(80) NOT NULL,
    col_desc   VARCHAR(500),
    col_due    TIMESTAMP NOT NULL,
    col_state  BOOLEAN NOT NULL
);

My addTodo method which persists a new element is pretty simple:

public Long addTodo(final Todo todo) {
    LOG.info("Add todo");
    entityManager.persist(todo);
    LOG.info("Created todo: {}", todo);
    return todo.getId();
}

But the id is always null.

This is my Entity:

@Entity
@Table(name = "tab_todo")
public class Todo implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    //@Column(name = "col_id", nullable = false) // This did not have any effect either
    private Long id;

    @Column(name = "col_name")
    private String name;

    @Column(name = "col_desc")
    private String description;

    @Column(name = "col_state")
    private boolean status;

    @Column(name = "col_due")
    private LocalDateTime dueDate;

    // Getter, Setter, etc.

Saving a new to do works fine. When I check the database then I can see that col_id has been set properly. But JPA won't set the id in my entity when persisting.

What am I doing wrong here?

Apollo
  • 1,296
  • 2
  • 11
  • 24
  • 1
    have you tried running `entityManager.commit();` after `entityManager.persist(todo);`? Also, is `GenerationType.IDENTITY` what you want? You could use `GenerationType.AUTO`, I believe. – fjsv Jun 09 '20 at 12:02
  • 2
    @fjsv I think you meant `entityManager.flush()` – crizzis Jun 09 '20 at 12:58
  • @crizzis, yes, you're right. `entityManager.flush()` – fjsv Jun 09 '20 at 13:20
  • 1
    Thanks both of you. I would have never thought about that. It fixed it. – Apollo Jun 09 '20 at 13:39
  • For me it tries to insert it like: "insert into XXX (id,bla,blu) values(null, ?,?)" instead of the expected: "insert into XXX (id,bla,blu) values( default , ?,?)". But I cannot say why this is happening yet – Pwnstar Sep 30 '22 at 13:19

0 Answers0