Reputation:
I have a post class and it kind of works, but there's one problem: the primary key doesn't 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'm getting 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 the @Id annotation in palce..
This is how I have in my controller:
Post p = new Post("Midden in het middenoosten.", new Date()).save();
Any ideas what's causing this problem?
Upvotes: 3
Views: 5760
Reputation: 1803
There are several strategies available to generate id:
GenerationType.AUTO
GenerationType.SEQUENCE
GenerationType.IDENTITY
GenerationType.TABLE
If you want the primary key values to be auto-generated, use GenerationType.AUTO
, it works with MySQL.
Upvotes: 1
Reputation: 76709
It seems that you want the primary key values to be auto-generated. If that is the case, if you'll need to add the @GeneratedValue
annotation to the id
attribute, in addition to the @Id
annotation. Your code should therefore be:
@Id
@Column(name="post_id")
@GeneratedValue
public int id;
There are several strategies available to generate the Ids. You would have to read up on those to decide if you want to choose the TABLE
-based, SEQUENCE
-based or the IDENTITY
-based strategy (which depends on what your database supports). If you choose a strategy explicitly, the define strategy will be used, instead of the default AUTO strategy. Explicit strategy decisions, are communicated in code as:
@Id
@Column(name="post_id")
@GeneratedValue(strategy=SEQUENCE, generator="POST_SEQ")
public int id;
Without generated values, the default value for integers in Java, i.e. 0 will be persisted for the post_id
column. Due to the primary key constraint, you cannot have a second row with the same key, resulting in the described failure.
Upvotes: 5