JPA primary key value is always 0

I have a post class, and it seems to work, but there is one problem: the primary key does not increase.

@Entity
@Table(name="posts")
public class Post extends GenericModel{

    @Id
    @Column(name="post_id")
    public int id;

    @Column(name="post_situation")
    public String situation;

    @Column(name="post_date")
    public Date date;

    @Column(name="post_userid")
    public int userid;

    @OneToMany(mappedBy="post", cascade=CascadeType.ALL)
    public List<Block> blocks;

    public Post addBlock(String content, int position){
        Block b = new Block(this, content, position);
        b.save();

        this.blocks.add(b);

        this.save();
        return this;
    }

    public Post(String situation, Date date){
        this.situation = situation;
        this.date = date;
        this.userid = 2;
    }

}

When I call it the first time on an empty table, it works fine, but the second time I get PersistenceException occured : org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update The post_id column always has 0. Any idea how to fix this? I have @Id annotation in palce ..

This is how I have it in the controller:

    Post p = new Post("Midden in het middenoosten.", new Date()).save();

Any ideas that cause this problem?

+3
source share
2 answers

It seems that you want the primary key values ​​to be automatically generated. If so, you need to add annotation @GeneratedValueto the attribute idin addition to the annotation @Id. Therefore, your code should be:

@Id
@Column(name="post_id")
@GeneratedValue
public int id;

. , , TABLE, SEQUENCE IDENTITY ( , ). , AUTO . :

@Id
@Column(name="post_id")
@GeneratedValue(strategy=SEQUENCE, generator="POST_SEQ")
public int id;

Java, .. 0, post_id. - , .

+6

id:

  • GenerationType.AUTO
  • GenerationType.SEQUENCE
  • GenerationType.IDENTITY
  • GenerationType.TABLE

, , GenerationType.AUTO, MySQL.

+1

All Articles