Java Collections

btoddb edited this page Sep 19, 2011 · 9 revisions

In previous versions of HOM, a POJO containing a Java Collection property could not be easily mapped to Cassandra columns using HOM. You would have needed to create a custom converter that would handle the mapping ... until now. Now you can annotate a collection property using @Column just like any other property and HOM will do "the right thing".

How does it work? Each element of the collection is mapped to a Cassandra column with a simple naming scheme, "<pojo-property-name>:<index>". There is also an "informational column" persisted, "<pojo-property-name>", that contains the type of the Collection and its size. The elements of the Collection are serialized using Java's Object Serialization, so any type that implements Serializable should work just fine.

A consequence of persisting Collections is that any previously persisted POJO properties are removed and persisted again. This is because HOM tries to keep persisting fast, and for most cases (if not all) simply removing everything and persisting again, saves a read to get the existing Collection information. When reading, all columns are read and the "informational column" tells HOM what Collection to to instantiate and how many columns exist.

Let's look at an example:

public class Desk extends BasicTable {

  @Column(name = "desk_type")
  private String deskType;

  @Column(name = "drawerList")
  private List<Drawer> drawerList = new ArrayList<Drawer>();

  public List<String> getDrawerList() {
    return drawerList;

  public void setDrawerList(List<String> drawerList) {
    this.drawerList = drawerList;

  public String getDeskType() {
    return deskType;

  public void setDeskType(String deskType) {
    this.deskType = deskType;

As you can see above, there is a "List" Collection property, drawerList. Let's assume there are three elements in the list. HOM will persist four columns: drawerList, drawerList:0, drawerList:1, drawerList:2. drawerList contains java.util.ArrayList and size of 3. A custom type, Drawer, is used and will be persisted property using Java Serialization. Pretty simple!

Note that the implementation does not implement relationships between objects, like many-to-one, etc ... at least not yet. If you have a collection of custom typed objects, they will be persisted using Java's Object Serialization and the type must implement

Also don't forget to implement equals and hashCode for your custom types. Since they will be in a Collection, you will probably want this functionality to insure proper handling by the Collection.

(The implementation has been tested with Lists and Sets.)

Up to Hector Object Mapper (HOM)