Skip to content

Entity Mapping

stevenzwu edited this page Jan 3, 2013 · 4 revisions

This is deprecated. please check out new implementation at "com.netflix.astyanax.entitystore".

Astyanax provides a basic entity mapping layer.

Basics

A simple method for mapping between a Java bean and a Column Family is available. You need to create a Java bean that maps to columns in a Column Family. Annotations are used to denote persistent columns and the key. E.g.

public class MyBean {
    @Id("ID")
    private int     myKey;

    @Column("NAME")
    private String  myName;

    @Column("TIME")
    private Date    myDate;

    ... getters/setters go here ...
}

Once you have an annotated bean, use the {{Mapping}} class to manage the mapping:

Mapping<MyBean>    mapper = Mapping.make(MyBean.class);
    ...
// reading into a bean
ColumnList<String>  result = keyspace.prepareQuery(columnFamily).getKey(id).execute().getResult();
MyBean              bean = mapper.newInstance(result);

// writing a bean
MutationBatch              mutationBatch = keyspace.prepareMutationBatch();
ColumnListMutation<String> columnListMutation = mutationBatch.withRow(columnFamily, id);
mapper.fillMutation(myBean, columnListMutation);
mutationBatch.execute();

Because there is overhead to creating a Mapping instance, you should use the {{MappingCache}} to access Mapping instances. So, the modified code would be:

MappingCache       cache = ... // usually a static or a field in a class
Mapping<MyBean>    mapper = cache.getMapping(MyBean.class);
    ...

MappingUtil

A high level abstraction for mapping is provided by the {{MappingUtil}} class. It has methods that function like a HashMap except that values are stored/read from Cassandra. E.g.

MappingUtil    mapper = new MappingUtil(keyspace, new MappingCache());
    ...
mapper.put(columnFamily, myBean);
    ...
MyBean         bean = mapper.get(columnFamily, id, MyBean.class);
   ...
List<MyBean>   allBeans = mapper.getAll(columnFamily, MyBean.class);
   ...
mapper.remove(columnFamily, myBean);
Clone this wiki locally