我有一个 post class 并且它有点工作,但是有一个问题:主键没有增加。
@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;
}
}
当我第一次在一个空表上调用它时,它工作正常,但第二次,我得到了 PersistenceException occurred : org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
post_id 列始终为 0。知道如何解决这个问题吗?我有 @Id 注释..
我的 Controller 是这样的:
Post p = new Post("Midden in het middenoosten.", new Date()).save();
知道是什么导致了这个问题吗?
最佳答案
您似乎希望自动生成主键值。如果是这种情况,除了 @Id
注释之外,您还需要将 @GeneratedValue
注释添加到 id
属性.因此,您的代码应该是:
@Id
@Column(name="post_id")
@GeneratedValue
public int id;
There are several strategies可用于生成 ID。您必须阅读这些内容才能决定是选择基于 TABLE
的策略、基于 SEQUENCE
的策略还是基于 IDENTITY
的策略(这取决于您的数据库支持什么)。如果您明确选择策略,将使用定义策略,而不是默认的 AUTO 策略。明确的战略决策,在代码中传达为:
@Id
@Column(name="post_id")
@GeneratedValue(strategy=SEQUENCE, generator="POST_SEQ")
public int id;
如果没有生成值,Java 中整数的默认值,即 post_id
列将保留为 0。由于主键约束,您不能有第二行具有相同的键,从而导致所描述的失败。
关于java - JPA 主键值始终为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6259699/