Persisting An Annotation-Less POJO With JPA 📎
To persist an annotation-less POJO with JPA:
public class Workshop {
private long id;
private String name;
public Workshop() {
}
public Workshop(long id, String name) {
this.id = id;
this.name = name;
}
}
you will have to provide the lacking metadata in a XML descriptor instead of annotations:
<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0">
<entity class="com.airhacks.jpa.orm.Workshop">
<table name="T_WORKSHOP"/>
<attributes>
<id name="id">
<generated-value strategy="AUTO"/>
</id>
<basic name="name">
<column name="w_name" length="100"/>
</basic>
</attributes>
</entity>
</entity-mappings>
The persistence.xml
file has to point to the location of the orm.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="it" transaction-type="RESOURCE_LOCAL">
<mapping-file>META-INF/orm.xml</mapping-file>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:./airhacksDB;create=true"/>
<property name="javax.persistence.jdbc.driver"
value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
Now an annotation-less POJO can be stored using JPA:
import com.airhacks.rulz.em.EntityManagerProvider;
import org.junit.Rule;
import org.junit.Test;
public class WorkshopIT {
@Rule
public EntityManagerProvider provider = EntityManagerProvider.persistenceUnit("it");
@Test
public void crud() {
provider.tx().begin();
provider.em().merge(new Workshop());
provider.tx().commit();
}
}
The idea for this post came from 16th airhacks.tv Q&A. Big thanks to Eddy Young for asking this question.
See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting