views:

1384

answers:

3

Hi, 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  A: 

you should use persist(), not merge()

dfa
persist returns me "Cannot persist detached object" error.
Robert A Henru
it works with merge, but it saved only the first record..no exception, but the rest of the records is not saved...
Robert A Henru
persist() without flush() should work out of the box
dfa
A: 

I found something... I've got to set different id for each record before persisting them. Otherwise, they will take it as the same record and will not persist them.

Is there any way round on this?

Robert A Henru
+1  A: 

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

Robert A Henru