Skip to content

Custom Property Converters

btoddb edited this page Feb 12, 2011 · 5 revisions

In the above MyPojo example (listed in Using the EntityManager) you may have noticed the type, Colors, which is an enumeration. (It is in src/test/java/com/mycompany in the code base).

package com.real.hom;

public enum Colors {
    BLUE("Blue"),
    RED("Red"),
    GREEN("Green");

    private final String name;

    Colors(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public static Colors getInstance(String name) {
        Colors[] tidArr = values();
        for (Colors tid : tidArr) {
            if (tid.getName().equals(name)) {
                return tid;
            }
        }

        throw new IllegalArgumentException("No Color with name, " + name);
    }
}

As you probably already know, Cassandra stores all column values as byte[]. So all POJO properties must be converted to a byte[] before sending to Cassandra server. The EntityManager can only convert basic java types "out of the box". However custom converters can be created and registered by using the @me.prettyprint.hom.annotations.Column annotation's "converter" property - note that the standard JPA @Column cannot be used. (This technique is very similar to XStream's converter strategy.) In MyPojo you can see the "colors" property is annotated like this:

   @me.prettyprint.hom.annotations.Column(name = "color", converter = ColorConverter.class)

This tells the EntityManager to use ColorConverter to convert to/from a byte[] for the "color" property in MyPojo:

package com.real.hom;

import com.real.hom.converters.Converter;

public class ColorConverter implements Converter<Colors> {

  @Override
  public Colors convertCassTypeToObjType(Class<Colors> clazz, byte[] value) {
    return Colors.getInstance(new String(value));
  }

  @Override
  public byte[] convertObjTypeToCassType(Colors value) {
    return value.getName().getBytes();
  }
}

When saving a POJO the ColorConverter.ConvertObjTypeToCassType is called. When loading a POJO the ColorConverter.ConvertCassTypeToObjType is called.


Up to Hector Object Mapper (HOM)

Clone this wiki locally