springjpaspring-dataapplicationcontextspring-orm

Declaring persistent JPA entities in applicationContext.xml?


So, this is what I want to do. Some like so I was already able to find in openerp.

I think, I could simply declare a bean, which were a JPA persistent entity as well, for example:

Example.java:

package my.project;

@Configurable
@Entity
public class Example {
    String a;
    String b;
...
}

Of course, this class already contains the JPA persistence injections, thus it can be handled from java code as a normal JPA-backed persistent class. My goal is to declare some of its instances from the Spring applicationContext.xml:

applicationContext.xml:

<bean class="my.project.Example">
    <property name="a" value="test_a"/>
    <property name="b" value="test_b"/>
</bean>

What I think it were really interesting:

  1. The persist() method of the newly created instance had to be called from the Spring initialization, but only if it doesn't exist in the DB already.
  2. If it exists, the instance should be loaded from the persistent JPA storage.

Is it somehow possible? Is there even example code for the task? :-)


Solution

  • Did you thought about using factory method instead? You could insert Entity manager inside and call find/save inside. Factory method would then returned your bean instance either from database or create a fresh one and persist it. For me this would be better solution, easy to mock in tests also.