14

我正在使用 MyBatis 3.0.3 并且遇到问题:数据库中的某些列的名称带有下划线,这些列应该映射到实体属性(当然是在 camelCase 中)

class User {
  private String first_name;
  ...
}

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

不幸的是,我看不到任何方法可以明确地解决这个问题(就像在 JPA 中所做的那样 - @Column(name = "first_name"))。我可以在 select-clause 中为这些列创建别名(sush as first_name as firstName 等),但这看起来也很蹩脚。

有任何想法吗?谢谢。

4

6 回答 6

24

感谢 DwB。这有助于:

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

ps 但是如果有多个查询,我需要为每个返回实体用户的方法编写@Results/@Result 代码。就我而言,会有很少的地方,所以这不是问题,但总的来说,我仍然想找到更通用的解决方案。

于 2011-02-23T07:06:21.173 回答
13

Eduardo Macarron 在以下问题上建议了此功能:

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

根据 MyBatis 3 的文档,现在可以通过以下描述的设置:

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

基本上你必须配置:

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

意思是:

启用从经典数据库列名 A_COLUMN 到驼峰式经典 Java 属性名 aColumn 的自动映射。

于 2014-05-29T15:13:45.943 回答
5

ResultMap在文件中定义 a UserMapper.xml,并添加以下行:

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

在您的 Java 代码中,添加@ResultMap注释:

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

您可以使用MyBatis Generator自动生成这些基本代码。

于 2013-07-17T06:41:57.703 回答
5

在你的配置文件中使用 MyBatis 的自动映射(比如 application.properties 或 application.yml),比如:

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

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

中文参考: http ://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Auto-mapping

于 2017-08-24T12:56:19.930 回答
4

如果没有那么多列,您可以这样做并避免使用 ResultMap。

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

为了使其更具可读性,您可以使用字符串数组,MyBatis 将其与额外空间连接起来

@Select({
     "SELECT",
     "  first_name as firstName,",
     "  last_name as lastName",
     "FROM users"})
List<User> findUsers();
于 2014-07-18T13:45:01.393 回答
4

在 spring 中基于注释的配置下划线到驼峰式映射可以通过可自定义的 SqlSessionFactory 启用,如下所示:

@Bean
@Primary
public SqlSessionFactory sqlSessionFactory() throws Exception {
    SqlSessionFactory factory = sessionFactoryBuilder().build();
    factory.getConfiguration().setMapUnderscoreToCamelCase(true);
    // other configurations
    return factory;
}
于 2016-06-03T05:57:20.530 回答