17

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.

1
  • 1
    Look into the myBatis @Results and @Result annotations.
    – DwB
    Feb 22, 2011 at 15:30

7 Answers 7

26

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.

3
  • 3
    I think you can mix xml config and annotations. Leave the @Selects in code for the actual SQL but put the <resultMap> part in an xml config file. The result map should be applied the object / class level (based on the namespace) so you wouldn't have to specify @Results on each method.
    – AngerClown
    Feb 23, 2011 at 16:23
  • 4
    This question is now a bit old but, for future reference, maybe take a look at auto-mapping: mybatis.org/core/sqlmap-xml.html#Auto-mapping.
    – lsoliveira
    Jun 14, 2012 at 16:11
  • 1
    You can also use mapUnderscoreToCamelCase setting to convert underscore naming to camelcase, ref: mybatis.github.io/mybatis-3/configuration.html
    – user452425
    Oct 16, 2013 at 20:27
13

Eduardo Macarron has suggested this feature on the following issue:

https://code.google.com/p/mybatis/issues/detail?id=43

According to the documentation of MyBatis 3, now is possible through a setting described in:

http://mybatis.github.io/mybatis-3/configuration.html#settings

Basically you must configure:

<setting name="mapUnderscoreToCamelCase" value="true"/>

Which means:

Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn.

1
  • The accepted answer was right when it was answered in 2011. But for the sake of anyone viewing it in the future, this answer would be the right approach. Nov 3, 2016 at 18:44
5

Define a ResultMap in the UserMapper.xml file, and add these lines:

<resultMap id="BaseResultMap" type="package.for.User">
  <result column="user_name" jdbcType="VARCHAR" property="userName" />
  <!--  other columns -->
</resultMap>

In your Java code, add@ResultMap annotation:

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

You can use MyBatis Generator to generate these base codes automatically.

5

If there is not so much columns you can do it this way and avoid ResultMap.

@Select("SELECT first_name as firstName, last_name as lastName FROM users")
List<User> findUsers();

to make it more readable you can use array of strings, which MyBatis concanate with extra space

@Select({
     "SELECT",
     "  first_name as firstName,",
     "  last_name as lastName",
     "FROM users"})
List<User> findUsers();
5

use MyBatis's Auto-mapping in your config file (sth like application.properties or application.yml), here like:

mybatis.configuration.map-underscore-to-camel-case=true

Reference: http://www.mybatis.org/mybatis-3/sqlmap-xml.html#Auto-mapping

Chinese Reference: http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Auto-mapping

1
4

In spring annotation-based configuration underscore to camel case mapping can be enabled through a customizable SqlSessionFactory, like that:

@Bean
@Primary
public SqlSessionFactory sqlSessionFactory() throws Exception {
    SqlSessionFactory factory = sessionFactoryBuilder().build();
    factory.getConfiguration().setMapUnderscoreToCamelCase(true);
    // other configurations
    return factory;
}
1

My entity of account

@NoArgsConstructor
@AllArgsConstructor
@Setter
public class Account {
    private Integer id;
    private String accountType;
    private String accountNumber;

    public Integer getid() {
        return id;
    }

    public String getAccountType() {
        return accountType;
    }

    /**
     * It takes the account number, hashes it, and returns the hash
     *
     * @return The account number is being returned.
     */
    public String getAccountNumber() throws NoSuchAlgorithmException {
        String plaintext = this.accountNumber;
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.reset();
        m.update(plaintext.getBytes());
        byte[] digest = m.digest();
        BigInteger bigInt = new BigInteger(1,digest);
        String hashtext = bigInt.toString(16);
        // Now we need to zero pad it if you actually want the full 32 chars.
        while(hashtext.length() < 32 ){
            hashtext = "0"+hashtext;
        }
        return hashtext;
    }

    /**
     * The toString() method returns a string representation of the object
     *
     * @return The account id, account type, and account number.
     */
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", accountType='" + accountType + '\'' +
                ", accountNumber='" + accountNumber + '\'' +
                '}';
    }
}

My Database has column names ID, account_number, and account_type

In my mapper class, i used @Results annotation of ibatis

@Mapper
public interface AccountMapper {
    /**
     * Get all accounts from the database.
     *
     * @return A list of all the accounts in the database.
     */
    @Select("SELECT * FROM account")
    @Results({
            @Result(property = "id", column = "ID"),
            @Result(property = "accountNumber", column = "account_number"),
            @Result(property = "accountType", column = "account_type")
    })
    List<Account> getAllAccounts();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.