3

I'm very much used to the Django 'choices' option for a model field:

GENDER_CHOICES = (
    ('M', 'Male'),
    ('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

That allows, for a model field, to easily match a database value with a (representation) string. And works with whatever sql type is chosen (Char, Int...)

In JPA that's not possible; you can make an Enum: but only use its ordinal or string. I find that overly limiting and complicated.

Is there in Play! something similar to the Django choices, in particular to be used with the CRUD?

Or at least a pattern for the CRUD than just declare a simple String or int for the model field?

Related:

Community
  • 1
  • 1
Stefano
  • 18,083
  • 13
  • 64
  • 79

2 Answers2

1

I don't understand your problem with Enum, you can map enum with JPA like this

@Enumerated(EnumType.STRING)
public GenderChoice genderChoice;

an use the enum in your code. Is this not enough ?

Seb Cesbron
  • 3,823
  • 15
  • 18
  • well I don't like two things here: 1) store the entire string in the DB 2) I can't change the element of the enums because they would make database entries inconsistent I can live with this, but I like the abstraction layer provided by Django choices. – Stefano Dec 20 '11 at 12:02
  • 1
    In your enum you can add a name field that you can change without breaking the database where you put 'Male' and 'Female' and you set your enum instances as M and F which will be immutable as in Django – Seb Cesbron Dec 21 '11 at 11:59
1

Based on @SebCesbron comment this is the kind of pattern I'm using now...

@Required
@Enumerated(EnumType.STRING)
public MyEnumType myenum;


public enum MyEnumType {

    ENUMONE ("label one", 1),
    ENUMTWO ("label two", 2);

    String label;
    Int value;

    CastType(String label, Int value) {            
        this.value = value;
        this.label = label;
    }

    @Override
    public String toString() {
        return this.label;
    }

    public Int getValue() {
        return this.value;
    }

    public String getLabel()
    {
        return label;
    }

}

Using EnumType.STRING the database will contain the enum item name - overriding toString does not affect that, because JPA uses name() which is final.

So wrt to my precise usecase and question:

@Required
@Enumerated(EnumType.STRING)
public GenderEnum myenum;


public enum GenderEnum {

    M ("Male"),
    F ("Female");

    String label;

    CastType(String label) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.label;
    }
}
Stefano
  • 18,083
  • 13
  • 64
  • 79