google-code-export / objectify-appengine

Automatically exported from code.google.com/p/objectify-appengine
MIT License
1 stars 0 forks source link

Add support for value objects #90

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Say my datastore has an entity with a column of type String that represents a 
Credit Card number.

Currently this must be modelled like this:

class MyEntity {
  String creditCard;
}

What I would like is this:

class MyEntity {
  CreditCard creditCard;
}

@ValueObject
class CreditCard {
  String value;

  void setNumber(String number) {
    validate(number);
    this.value = number;
  }
}

This enables a rich domain model with strong typing and validation.

Original issue reported on code.google.com by axel.fontaine.business@gmail.com on 4 Jun 2011 at 11:29

GoogleCodeExporter commented 9 years ago
You can add a Converter for this:

{{{
ofyFactory.getConverters().add(new Converter() {
    public Object forDatastore(Object value, ConverterSaveContext ctx) {
        return ((CreditCard)value).getValue();
    }

    public Object forPojo(Object value, Class<?> fieldType, ConverterLoadContext ctx, Object onPojo) {
        return new CreditCard(value.toString());
    }
});
}}}

Is this an adequate solution?

Original comment by lhori...@gmail.com on 4 Jun 2011 at 5:26

GoogleCodeExporter commented 9 years ago
Doh!  Ignore that last comment, this is the correct way to implement a 
Converter:

ofyFactory.getConverters().add(new Converter() {
    public Object forDatastore(Object value, ConverterSaveContext ctx) {
        if (value instanceof CreditCard)
            return ((CreditCard)value).getValue();
        else
            return null;
    }

    public Object forPojo(Object value, Class<?> fieldType, ConverterLoadContext ctx, Object onPojo) {
        if (CreditCard.class.isAssignableFrom(fieldType))
            return new CreditCard(value.toString());
        else
            return null;
    }
});

Original comment by lhori...@gmail.com on 4 Jun 2011 at 5:30

GoogleCodeExporter commented 9 years ago
This is even easier now in Objectify4 with translators.

Original comment by lhori...@gmail.com on 16 Dec 2011 at 2:32