@GeneratedValue(策略= GenerationType.AUTO)不像思想一样工作 [英] @GeneratedValue(strategy = GenerationType.AUTO) not working as thought

查看:349
本文介绍了@GeneratedValue(策略= GenerationType.AUTO)不像思想一样工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个对象持久化到一个数据库。继续收到'列ID不能接受空值错误'。我的对象如下所示:

I'm trying to persist an object to a database. Keep getting 'Column ID cannot accept null value error'. My object looks like this:

    @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;
    }

}

我的持久功能:

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;
    }


推荐答案

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

You may use GenerationType.TABLE. That way, jpa uses a sequence table for id assigment and you may never need to generate sequence or auto-increment values or triggers that lowers portability.

另外请注意,在java int类型是由0默认启动,所以你也可以摆脱这一点。

Also note that in java int type is initiated with 0 default, so you may get rid of that also.

这篇关于@GeneratedValue(策略= GenerationType.AUTO)不像思想一样工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆