Skip to content

Entity persister

stevenzwu edited this page Jan 4, 2013 · 28 revisions

Astyanax provides entity persister APIs that is similar to Java Persistence API (JPA). Please check out "com.netflix.astyanax.entitystore" package.

Basic put/get/delete opeations

Here is sample code snippet from DefaultEntityManagerTest.java

final String id = "foo";
final SampleEntity origEntity = createRandomEntity(id);
final EntityManager<SampleEntity, String> entityPersister = 
	new DefaultEntityManager.Builder<SampleEntity, String>()
	.withEntityType(SampleEntity.class)
	.withKeyspace(keyspace)
	.withColumnFamily(CF_SAMPLE_ENTITY)
	.build();

entityPersister.put(origEntity);
SampleEntity getEntity = entityPersister.get(id);
entityPersister.delete(id);

custom @Serializer annotation

By default (without @Serializer annotation), astyanax will automatically infer the Serializer type based on entity field's java type. Here are the following inference types supported by entity persister.

  • basic java data types (both primitive and wrapper): byte, short, int, long, boolean, float, double
  • String, byte[], Date, UUID

If you have a field that requires custom Serializer, you can specify it with the @Serializer annotation. Here is the code snippet from SampleEntity.java

public class SampleEntity {
	
	public static class Foo {
		
		public int i;
		public String s;
		
		public Foo(int i, String s) {
			this.i = i;
			this.s = s;
		}
		
		@Override
		public String toString() {		
			try {
				JSONObject jsonObj = new JSONObject();
				jsonObj.put("i", i);
				jsonObj.put("s", s);
				return jsonObj.toString();
			} catch (JSONException e) {
				throw new RuntimeException("failed to construct JSONObject for toString", e);
			}
		}
		
		public static Foo fromString(String str) {
			try {
				JSONObject jsonObj = new JSONObject(str);
				return new Foo(jsonObj.getInt("i"), jsonObj.getString("s"));
			} catch (JSONException e) {
				throw new RuntimeException("failed to construct JSONObject for toString", e);
			}			
		}

		...
	}
	
	public static class FooSerializer extends AbstractSerializer<Foo> {
		
		private static final String UTF_8 = "UTF-8";
		private static final Charset charset = Charset.forName(UTF_8);
		private static final FooSerializer instance = new FooSerializer();

		public static FooSerializer get() {
			return instance;
		}

		@Override
		public ByteBuffer toByteBuffer(Foo obj) {
			if (obj == null) {
				return null;
			}
			return ByteBuffer.wrap(obj.toString().getBytes(charset));
		}

		@Override
		public Foo fromByteBuffer(ByteBuffer byteBuffer) {
			if (byteBuffer == null) {
				return null;
			}
			return Foo.fromString(charset.decode(byteBuffer).toString());
		}

		...
	}

	@Column(name="FOO")
	@Serializer(FooSerializer.class)
	private Foo foo;
	...
}
Clone this wiki locally