Fabio B.
Fabio B.

Reputation: 9400

about "binary" datatypes

I usually don't post noob questions but.... I am missing something since I began programming.

Let's imagine a pojo entity object, with several properties name, description and so on. One of these is "direction" which can only be "IN" or OUT.

What's the best data type for that property? I could use a Boolean, assuming for example true as in and false as out. Or maybe I can use a single char 'I' and 'o', or an "enum"..

Consider I will use this object with hibernate, the property will go on a table's column. So... What's the best data type for the column, too?

Thank you

Upvotes: 0

Views: 168

Answers (5)

nwinkler
nwinkler

Reputation: 54457

Use an enum. For Hibernate, you can use the following mapping, and it will automatically use the name of the enum value to store/retrieve from the DB:

        <type name="org.hibernate.type.EnumType">
            <param name="enumClass">foo.MyEnum</param>
            <!-- 12 == java.sql.Types.VARCHAR -->
            <param name="type">12</param>
        </type>

Upvotes: 1

Alex
Alex

Reputation: 25613

You can have an enum to represent the direction

public enum Direction {
    IN('i'), OUT('o');

    final char dir;
    Direction(char dir) {
        this.dir = dir;
    }

    public static Direction find(char c) {
        for (Direction d : Direction.values()) {
            if (d.dir == c)
                return d;
        }
        throw new IllegalArgumentException("Not found: " + c);
    }
}

You can bind it to a char column in your db and with Hibernate/JPA within your entity, just set your column with type char, and expose only your enum with the getter/setter.

@Entity
public class MyEntity {
    @Column
    private char direction;

    public Direction getDirection() {
        return Direction.find(direction);
    }

    public void setDirection(Direction dir) {
        this.direction = dir.dir;
    }
}

Upvotes: 1

Kuldeep Jain
Kuldeep Jain

Reputation: 8598

I would use enum and store the enum value converted to String in database table. Read the article on Java Enums for details about it.

Upvotes: 1

jakob
jakob

Reputation: 227

I would suggest Enum.

Advantages:

  • You can extend the set of possible values of the variable later on (should that become necessary).
  • The names of the values contain valuable meaning about the semantics of the values.
  • Your programming language will help you with type checks.

Of course, that means you should use descriptive names for your enum values...

Upvotes: 2

adarshr
adarshr

Reputation: 62593

I think enum is best suited for this purpose.

public enum STATE {IN, OUT}

You can always get the string equivalent for saving to database.

Upvotes: 2

Related Questions