Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MyBatis: underscore not mapped to camelcase

My problem is simple. I have a column name product_name in my product table in my mysql database but in my Product class (java), camelcase is used in productName. MyBatis is not mapping product_name to productName. Any solution for this? I had no problem in Hibernate before but right now I need to use mybatis for development

like image 691
rhandom Avatar asked Sep 29 '14 07:09

rhandom


3 Answers

I know this is old but for those that may come across this, MyBatis supports mapping underscores to camel case

config.xml

<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    ...
</configuration>

Then your sql can look like:

select product_name, product_description, ...
from products

or even just

select *
from products
like image 72
rimsky Avatar answered Oct 21 '22 23:10

rimsky


Underscore to camel case mapping can be enabled in spring-based configuration 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;
}
like image 38
Dariusz Avatar answered Oct 21 '22 21:10

Dariusz


You have to use <resultMap> tag in MyBatis to return the result. For example:

<resultMap id="result" type="userModel">
        <result property="id" column="USER_ID"/>
</resultMap>

In the above code, in type="userModel" userModel is defined in a config file where there is a mapping of userModel with a model java class which will have the corresponding setter/getter method for id. For more info on this, refer the following Doc:

MyBatis Doc

like image 30
Akhil Avatar answered Oct 21 '22 21:10

Akhil