MyBatis columns mapping

andrii picture andrii · Feb 22, 2011 · Viewed 29.5k times · Source

I am using MyBatis 3.0.3 and have problem: some columns in database have names with underscores and these columns should be mapped to the entity properties (that are of course in camelCase)

class User {
  private String first_name;
  ...
}

public interface UserDao {
  @Select("SELECT * FROM users")
  List<User> findAllUsers();
}

Unfortunately I can't see any way to solve that declaretively (like it is done in JPA - @Column(name = "first_name")). I could make aliases in select-clause for such columns (sush as first_name as firstName and etc.), but that also looks lame.

Any ideas? Thanks.

Answer

andrii picture andrii · Feb 23, 2011

Thanks to DwB. That helped:

    @Select("SELECT * FROM users")
    @Results({
        @Result(property = "firstName", column = "first_name"),
        @Result(property = "lastName", column = "last_name")
    })
    List<User> findUsers();

ps But in case of multiple queries I need to boilerplate @Results/@Result code for each method where entity User is returned. In my case there will be a very few places so it isn't a problem, but in general I would still like to find more general solution.