YN

Yeah, I know, this isn’t rocket science. But it is rather nice 🙂

So, I’m working on this JEE project, backed by an Oracle database. Some of my work involves refactoring CMP 2.1 entities into JPA entities.

Here I’m faced with the issue, that sometimes true/false columns are modeled using CHAR(1) as ‘Y’ vs ‘N’. And at other times they are modeled using INTEGER as 1 vs 0. Sometimes both versions are using in the same table.

The natural datatypes in JPA are String and int. So I’m having code doing “Y”.equals(colum) and column == 1 etc. For the String I’ve generally been using an enum called YN having 2 constants, Y and N. So I can do column == YN.Y. Still a bit annoying though…

Just today I realized I could fix both issues with a simple version of my YN enum below. This works both for the CHAR ‘Y’ / ‘N’ case and the INTEGER 1 / 0 case.

And it’s damn simple containing 2 simple convenience methods that does make life simpler:

/**
 * Being used in JPA entities as @Enumerated(EnumType.STRING) or @Enumerated(EnumType.ORDINAL) (N=0, Y=1)
 */
public enum YN {
    N, Y;
 
    public final boolean bool() {
        return this == Y;
    }
    public static final YN bool(boolean b) {
        return b ? Y : N;
    }
}

Now I can do column.bool() and I can do YN.bool(something) the other way. And the mapping in the JPA entity takes care of the rest.

Nice and simple, definitely not rocket science.

About Jesper Udby

I'm a freelance computer Geek living in Denmark with my wife and 3 kids. I've done professional software development since 1994 and JAVA development since 1998.
This entry was posted in Databases, Java and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.