views:

167

answers:

3

Hello,

I have an attribute which is annotated with @Id. The ID is going to be generated automatically when persisting the object. That means that the ID-value is not defined before I persist the object. After persisting it, it has an ID (in the database), but unfortunately the field still remains null as long as I don't reload it from the DB. is there any easy way to find out the generated id? Or better: To configure that it will be written into the field?

Thanks in advance

+4  A: 

The id gets assigned after the flush. Assuming the Foo entity has an id attribute annotated with the standard @Id @GeneratedValue annotations, the following code works:

Foo foo = new Foo();
//...
em.persist(foo);
em.flush();
assert foo.getId() != null;
Pascal Thivent
Great. That's exactly what I was looking for. :-)
A: 

Well, unfortunately it does not work. :-( The id-value remains 0.

Could this depend on the JPA-Provider I use? I use apache.openjpa.

Here is my code:

        em.getTransaction().begin();

        if (loadPersonById(p.getId()) != null)
        {
            em.persist(p);
        }
        else
        {
            em.merge(p);
        }

        em.flush();
        em.getTransaction().commit();

Any ideas?

A: 

Ok, you were right. It works.

When using the method persist everything is alright, but somehow the merge sometimes caused a problem.

Anyway, now it works, thank you. However I think, I found a better solution: by calling em.refresh(p) I achieve the same result and supposably more efficient because it refreshes only that one object (and not all managed objects). Is that right?

The question was about a new object. Now, I'm not sure to understand the problem with an existing object. But indeed, `refresh` only refreshes one particular entity.
Pascal Thivent