Notice: This Wiki is now read only and edits are no longer possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.
Difference between revisions of "EclipseLink/Examples/JPA/Dynamic/PropertiesTable"
< EclipseLink | Examples | JPA | Dynamic
(→Using @BasicMap) |
(→Using @BasicMap) |
||
Line 37: | Line 37: | ||
<source lang="java"> | <source lang="java"> | ||
+ | EntityManagerFactory emf = Persistence.createEntityManagerFactory("example"); | ||
+ | EntityManager em = emf.createEntityManager(); | ||
− | + | em.getTransaction().begin(); | |
− | + | ||
− | + | ||
− | + | Person p1 = new Person(1, "Doug", "Clarke"); | |
− | + | p1.setProperty("Work #", "6135551212"); | |
− | + | p1.setProperty("Anniversary", "May 19, 2001"); | |
− | + | p1.setProperty("Wife's Name", "Karla"); | |
− | + | ||
− | + | ||
− | + | em.persist(p1); | |
− | + | em.getTransaction().commit(); | |
+ | |||
+ | em.close(); | ||
+ | emf.close(); | ||
− | |||
− | |||
− | |||
</source> | </source> |
Revision as of 13:04, 23 July 2008
This example illustrates how EclipseLink JPA can enable dynamic or extensible models through the usage of a properties table. the properties table allows the developer to store additional information about an entity in a separate table using key-value pairs and have them reflected in the entity as a Map.
Background
this example makes use of a DirectMapMapping configured using the @BasicMap annotation.
Using @BasicMap
Here is a Person class which enables users to store arbitrary
@Entity public class Person { @Id private int id; @Column(name = "FNAME") private String firstName; @Column(name = "LNAME") private String lasttName; @BasicMap(keyColumn = @Column(name = "PNAME"), valueColumn = @Column(name = "PVALUE")) @CollectionTable(name = "PERSON_PROPERTY", primaryKeyJoinColumns = { @PrimaryKeyJoinColumn(name = "ID") }) private Map<String, String> properties; private Person() { this.properties = new HashMap<String, String>(); }
Example usage of mapping:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("example"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Person p1 = new Person(1, "Doug", "Clarke"); p1.setProperty("Work #", "6135551212"); p1.setProperty("Anniversary", "May 19, 2001"); p1.setProperty("Wife's Name", "Karla"); em.persist(p1); em.getTransaction().commit(); em.close(); emf.close();