JPA合并似乎不起作用 [英] JPA merge does not appear to work

查看:82
本文介绍了JPA合并似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行以下代码,根据从CSV文件读取的数据来更新数据库.我尝试调试,并检查控制台,它正在整个800条记录中运行.我没有收到任何错误,但是只插入了第一条记录.如果我使用persist而不是merge,则会出现无法持久分离对象"错误.

I'm running the following code to update the database according to the data I read from CSV file. I've tried to debug, and check the console and it's running through the whole 800 records. I don't get any error, but only the first record is inserted. If I'm using persist instead of merge, I got "Cannot persist detached object" error.

        for (String[] data : dataList) {
            log.debug("Reading data no " + (i++));
            EntityManager em = PersistenceUtil.getAgisDbEntityManager();
            EntityTransaction tr = em.getTransaction();
            tr.begin();

            try {
                AddressEntity address = new AddressEntity();
                updateAddress(data, address);
                em.merge(address);
                //em.persist(address);

                em.flush();
                tr.commit();
            } catch (Exception exc) {
                log.error(exc.getMessage(), exc);
                if (tr.isActive())
                    tr.rollback();
            }
        }

这是我的updateAddress方法,基本上是在更新某些字段.

And here is my updateAddress method, basically it's updating some of the fields.

private void updateAddress(String[] data, AddressEntity address) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    //setting the column data
    for (int i = 0; i < data.length; i++) {
        final String column = dataColumns.get(i);
        if (!column.equals("#IGNORE#")) {
            setProperty(address, column, data[i]);
        }
    }
    for (String field : this.defaultColumns.keySet()) {
        if (!field.startsWith("#"))
            setProperty(address, field, this.defaultColumns.get(field));
    }        
}

这是我的persistence.xml供您参考.

Here is my persistence.xml for your reference.

<persistence-unit name="agisdb-PU">
    <class>com.agis.livedb.domain.AddressEntity</class>
    <properties>
        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/agisdb"/>
        <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="toplink.jdbc.user" value="root"/>
        <property name="toplink.jdbc.password" value="password"/>
    </properties>
</persistence-unit>

您认为我错过了什么吗? 非常感谢! 罗伯特

Do you think I missed out something? Thanks a lot! Robert

推荐答案

好,问题出在我的地址实体对象上,我必须在id字段中添加以下内容. @GeneratedValue(strategy = GenerationType.identity)

Ok, the problem is with my Address Entity object, I have to add the following to the id field. @GeneratedValue(strategy=GenerationType.identity)

感谢dfa! 罗伯特

这篇关于JPA合并似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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