views:

64

answers:

2

I have an existing database that I am now connecting to using hibernate. I cannot change the data in it at the moment and have everything working apart from a single column.

I have a status column that has the values:

  • new
  • mailed
  • in
  • out

And the column is mapped as follows:

@Column(name = "STATUS", nullable = false, length = 50)
@Enumerated(EnumType.STRING)
private TeamMemberStatus status;

I would REALLY like (for application reasons) to have this column mapped as a Java Enum (TeamMemberStatus), but due to the fact that 'new' is a keyword in Java I cannot have that as an enum member.

If I have the enum contstants NEW, MAILED, IN and OUT hibernate fails as inside EnumType it does a Enum.valueOf().

Is there any way for me to map this to my Enum without having to write a complex UserType?

-- added content

My Enum like this:

public enum TeamMemberStatus {
    NEW, MAILED, IN, OUT 
}

is a valid Java enum, but not matching the case of the database. If I change it to match the database like:

public enum TeamMemberStatus {
    new, mailed, in, out
}

It won't compile as 'new' is a Java reserved word.

+1  A: 

If your Database values are "new", "mailed", "in" and "out" then your Enum need exactly the same names. - I believe that the problem is, that your Enums are in capital letters but your data base values not.

Ralph
That is exactly the problem, but I cannot have a enum with the value new in lowercase as it is a reserved word in java.
stevemac
+1  A: 

If you can use a SQL UPPER statement at database, It will work without using any UserType

UPDATE

Well, It can not be The nicest solution but it solves what you want

@Entity
public class WrapperEntity {

   private TeamMemberStatus memberStatus;

   @Transient
   private TeamMemberStatus getMemberStatus() {
       return this.memberStatus;
   }

   public void setMemberStatus(TeamMemberStatus memberStatus) {
       this.memberStatus = memberStatus;
   }

   @Column(name="STATUS", nullable=false, length=50)
   public String getMemberStatusAsString() {
       return memberStatus.name().toLowerCase();
   }

   public void setMemberStatusAsString(String memberStatus) {
       this.setsetMemberStatus(TeamMemberStatus.valueOf(memberStatus.toUpperCase()));
   }

}

Arthur Ronald F D Garcia
I'm assuming you mean to change the data in the database? Something like update TABLE set status = upper(status).I can't do that as it will break the existing applications that talk to that data expecting it as a lowercase value.
stevemac
@stevemac Updated
Arthur Ronald F D Garcia
Thats what I worked out in the end, bascially store the string internally and map it from/to the enum when the get/set's are called.It will have to do for the short term, until I can get all the apps updated to use uppercase constants.
stevemac