Persisting multisets (bags) with DataNucleus

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).

Advertisements
This entry was posted in JDO, JPA, Persistence. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s