Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast resultset in rowmapper to an enum?

I have my rowmapper like:

private static final class UserRowMapper implements RowMapper<User> {

    User user = new User();

      user.setId(rs.getInt("id"));
      user.setUserType( (UserType)rs.getInt("userType")); // ?????

    return user;

}

So I am trying to cast the integer value in the db for userType to the enumeration UserType.

Why doesn't this work?

like image 852
Blankman Avatar asked Jan 23 '12 02:01

Blankman


2 Answers

Cast it? No, can't be done.

You can call valueOf to get the Enum value from the String, as long as the String is valid.

like image 163
duffymo Avatar answered Sep 18 '22 15:09

duffymo


You can index into Enum.values():

user.setUserType( UserType.values()[rs.getInt("userType")] );

You might want to put in some error checking. :)

like image 24
Ted Hopp Avatar answered Sep 21 '22 15:09

Ted Hopp