JPA merge does not appear to work

[亡魂溺海] 提交于 2019-12-23 22:26:39

问题


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

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

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


回答1:


you should use persist(), not merge()




回答2:


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

Thanks dfa! Robert



来源:https://stackoverflow.com/questions/1085794/jpa-merge-does-not-appear-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!