Pages

Persisting multisets (bags) with DataNucleus

Thursday, June 3, 2010
A multiset is a set where you can have a particular object multiple times in the set (a normal java.util Set will remove dups). This is also known by some as a "bag". Google's Collections library has such a container class (Multiset), and fields of this type are now persistable using DataNucleus.

  • Put the datanucleus-googlecollections plugin in the CLASSPATH

  • Develop your model using the Multiset java type.

  • Make sure that your Multiset field uses a join-table when persisting to RDBMS, and that the join-table doesn't have a primary-key defined


So if we have

@PersistenceCapable
public class Sample
{
@Join(extensions=
@Extension(vendorName="datanucleus",
key="primary-key", value="false"))
Multiset elements = null;
...
}

this will create an RDBMS join table as

CREATE TABLE SAMPLE_ELEMENTS
(
ID_OID BIGINT NOT NULL,
ID_EID BIGINT NOT NULL
);

i.e no primary key, and so we can have duplicates of the same element in the Multiset.
Thereafter the persistence just performs as normal (for JDO or JPA).

No comments:

Post a Comment