Hectorを使ってみる (2) - Object Mapper -
http://hector-client.github.com/hector/build/html/content/HOM/hector-object-mapper.html をやってみる。そのままある程度はドキュメント通りに
pom.xml
<dependency>
<groupId>org.hectorclient</groupId>
<artifactId>hector-object-mapper</artifactId>
<version>3.1-06</version>
</dependency>
を追加しておく
Sample.java
package sample;
import javax.persistence.Entity;
import javax.persistence.Table;
import me.prettyprint.hom.annotations.Column;
import me.prettyprint.hom.annotations.Id;
@Entity
@Table(name="Sample")
public class Sample {
@Id
private String key;
@Column(name = "name")
private String name;
@Column(name = "color", converter = Color.ColorConverter.class)
private Color color;
public void setKey(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
}
Color.java
package sample;
import me.prettyprint.hom.PropertyMappingDefinition;
import me.prettyprint.hom.converters.Converter;
public class Color {
private String color;
public Color(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public static class ColorConverter implements Converter<Color> {
@Override
public Color convertCassTypeToObjType(PropertyMappingDefinition def, byte[] value) {
return new Color(new String(value));
}
@Override
public byte[] convertObjTypeToCassType(Color color) {
return color.getColor().getBytes();
}
}
}
me.prettyprint.hom.converters.Converterを使ってCassandraに突っ込む際や取ってくる際にシリアライズしたりできるので、これを使ってクラスの状態を突っ込むことができる模様。公式ドキュメントではcom.real.hom.converters.Converterってなってますけど
HectorClient.java
import sample.Color;
import sample.Sample;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hom.EntityManagerImpl;
public class HectorClient2 {
private static long time;
public static void main(String[] args) {
Cluster cluster = HFactory.getOrCreateCluster("Test Cluster", "127.0.0.1");
Keyspace keyspace = HFactory.createKeyspace("sample", cluster);
EntityManagerImpl em = new EntityManagerImpl(keyspace, "sample");
putSample(em);
Sample sample = em.find(Sample.class, String.valueOf(time));
System.out.println(sample.getName());
System.out.println(sample.getColor().getColor());
cluster.getConnectionManager().shutdown();
}
public static void putSample(EntityManagerImpl em) {
time = System.currentTimeMillis();
Sample sample = new Sample();
sample.setKey(String.valueOf(time));
sample.setName("hoge");
sample.setColor(new Color("red"));
em.persist(sample);
}
}
実行後にcassandra-cliからlistしてみると
RowKey: 1348241491638 => (column=color, value=red, timestamp=1348241491656000) => (column=name, value=hoge, timestamp=1348241491647000)
setColorしたオブジェクトでもConverterを介してconvertObjTypeToCassTypeで介したデータがぶち込まれる