@GeneratedValue(strategy = GenerationType.AUTO) 不像想象的那样工作 [英] @GeneratedValue(strategy = GenerationType.AUTO) not working as thought

查看:32
本文介绍了@GeneratedValue(strategy = 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(strategy = GenerationType.AUTO) 不像想象的那样工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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