EclipseLink/Examples/JPA/Dynamic/PropertiesTable

From Eclipsepedia

< EclipseLink‎ | Examples‎ | JPA‎ | Dynamic
Jump to: navigation, search

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.

Contents

Background

this example makes use of a DirectMapMapping configured using the @BasicMap annotation.

Example

Here is a Person class which enables users to store arbitrary

Mapping

@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>();
	}

Using the 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();


Querying the Map

At present you can only query the mapping using EclipseLink's classic API in conjunction with JPA. this example queries the value in the map.

ReadAllQuery raq = new ReadAllQuery(Person.class);
raq.setSelectionCriteria(raq.getExpressionBuilder().anyOf("properties").like("May%"));
List<Person> persons = JpaHelper.createQuery(raq, em).getResultList();


In JPA 2.0 additional mapping types and JPQL grammar constructs will be added to query the keys or values