views:

153

answers:

1

Having a hibernate mapping a legacy database I want to use EnumTypes to map certain columns that contain string constants with whitespace to some Enum class.

The mapping:

@Entity
@Table(name = "OPERATOR")
public class Operator {   
    @Id
    @Column(name = "ID")
    private Long id;
    ...

    @Enumerated(EnumType.STRING)
    @Column(name = "STATUS")
    private Status status;
    ...
}

public enum Status {
    OPERATOR_CREATED("Operator created"),
    ACTIVE("Active"),
    END_DATED("End dated");

    private String name;

    Status(String status) {
       name = status;
    }
}

As you can see we can't us the database values straight as the enum names, as there are white spaces in them.

I was wondering if it is possible to use enums for this?

+1  A: 

Look at GenericeEnumUserType described at hibernate.org (Under "Flexible solution")

Modify Status as follows:

public enum Status 
{
    OPERATOR_CREATED("Operator created"),
    ACTIVE("Active"),
    END_DATED("End dated");

    private String name;

    Status(String status) 
    {
       name = status;
    }

    public String toString()
    {
       return name;
    }

    public Status fromString( String value )
    {
        if ( "Operator created".equals( value ) 
        {
            return OPERATOR_CREATED;
        }
        //etc
    }
}

Now use the @Type annotation on your entity.

@Entity
@Table(name = "OPERATOR")
public class Operator {   
    @Id
    @Column(name = "ID")
    private Long id;
    ...

    @Column(name = "STATUS", columnDefinition = "VARCHAR(31)", nullable = false )
    @Type( type = "my.package.GenericEnumUserType",
           parameters = {
        @Parameter( name = "enumClass", value =  "my.package.Status" ),
        @Parameter( name = "identifierMethod", value = "toString" ),
        @Parameter( name = "valueOfMethod", value = "fromString" ) } )
    private Status status;
    ...
}
mtpettyp
You can also look at using a ReversibleEnum (http://www.khanspot.com/2006/12/04/java-wish-a-reversible-enum/) to elegantly implement the fromString() method on Status.
mtpettyp