HiveBrain v1.2.0
Get Started
← Back to all entries
principlejavaMinor

Enum vs lookup table for temporary and permanent teeth

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
temporaryenumteethforpermanentandlookuptable

Problem

I'm implementing a solution in Java using Ebean and I'm having some issues choosing between using enums or simply look up tables.

I have a table "Tooth". A tooth can be "Temporary" or "Permanent".

I could create a simple enum:

@EnumMapping(nameValuePairs = "TEMPORARY=T, PERMANENT=P")
public enum DentitionType { TEMPORARY, PERMANENT; }


However, if I want to do a direct SQL query, I have to convert "T" and "P", so a solution would be to use a lookup table as below:

@Entity
public class DentitionType {

   @Column(length = 15)
   public String name;

    private static DentitionType permanent;

    public boolean isTemporary() {
        return !this.equals(getPermanent());
    }

    public boolean isPermanent() {
        return this.equals(getPermanent());
    }

    public static DentitionType getPermanent() {
        if (permanent == null) {
            permanent = DentitionType.FIND.byId(2L);
        }

        return permanent;
    }
}


This feels kind of hardcoded and for larger tables a lot of isSomething functions are required.

Is there a better solution?

Solution

I would recommend making an enum with properties, such as:

public enum DentitionType {
    TEMPORARY(1), PERMANENT(2);

    private final int id;
    private DetentionType(int id) {
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public static DententionType forId(int id) {
        for (DententionType dentention : DetentionType.values()) {
            if (dentention.getId() == id) {
                return dentention;
            }
        }
        return null;
    }
}


This is an easy way of mapping your enum to an int (you can also use a 'char' or 'String' or whatever you feel like). Then you can inside your @Entity class use some JPA events to transform to/from enum and int.

Another solution is of course to simply use the @Enumerated annotation and automatically use the ordinal of the enum. Be aware however that there has been incidents where someone accidentally switched the order of the enums, which caused DIAMONDS to become black.

Code Snippets

public enum DentitionType {
    TEMPORARY(1), PERMANENT(2);

    private final int id;
    private DetentionType(int id) {
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public static DententionType forId(int id) {
        for (DententionType dentention : DetentionType.values()) {
            if (dentention.getId() == id) {
                return dentention;
            }
        }
        return null;
    }
}

Context

StackExchange Code Review Q#72118, answer score: 2

Revisions (0)

No revisions yet.