@GeneratedValue(strategy = GenerationType.AUTO)没有像想象的那样工作

Nul*_*x00 19 jboss hibernate jpa derby

我正在尝试将对象持久化到数据库.继续获取'列ID不能接受空值错误'.我的对象看起来像这样:

    @Entity
public class TestTable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id = 0;

    @Column(nullable=false, length=256)
    private String data = "";

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

}
Run Code Online (Sandbox Code Playgroud)

我的坚持功能:

public static synchronized boolean persistObject(Object obj){
        boolean success = true;
        EntityManager em = null;
        EntityTransaction tx = null;
        try{
            em = getEmf().createEntityManager();
            tx = em.getTransaction();
            tx.begin();
            em.persist(obj);
            tx.commit();

        } catch (Exception e){
            success = false;
        } finally{
            try{
                em.close();
            } catch(Exception e){
                //nothing
            }
        }
        return success;
    }
Run Code Online (Sandbox Code Playgroud)

Cem*_*ler 22

您可以使用GenerationType.TABLE.这样,jpa使用序列表进行id分配,您可能永远不需要生成序列或自动递增值或触发器,从而降低可移植性.

还要注意,在java int类型中启动时默认为0,所以你也可以摆脱它.

  • @ChristianVielma的一点是,AUTO默认为IDENTITY.您可能需要显式尝试GenerationType.IDENTITY并查看它是否有效以查看它是否与AUTO设置有关.但可能您的数据库配置不支持它.但是,GenerationType.TABLE会创建一个表并使用它来生成密钥,此设置应适用于所有rdbms.希望这可以帮助 :) (3认同)
  • @cguler 这也对我有用,但我不知道为什么 GenerationType.Table 有效而 Auto 无效。你能解释一下或推荐我吗? (2认同)

小智 6

就我而言,这是关于不好的方言:

hibernate.dialect=org.hibernate.dialect.H2Dialect
Run Code Online (Sandbox Code Playgroud)

代替:

hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect
Run Code Online (Sandbox Code Playgroud)

当我切换到生产数据库时。Hibernate 尝试使用为不同的数据库引擎准备的策略。