【问题标题】:Mybatis: get name of the column from mapped bean propertyMybatis:从映射的bean属性中获取列的名称
【发布时间】:2012-01-30 11:40:21
【问题描述】:

有什么方法可以从 bean 属性中检索列名?

例如我有一个用户表

user(user_id,user_name)

还有一个班级

class User{
private Integer userId;
private String userName;
//getter setter
}

我的配置文件中有一个 resultMap

 <resultMap id="userMap" type="User">
    <id property="userId" column="user_id" javaType="Integer" jdbcType="INTEGER" />
    <result property="userName" column="user_name" javaType="String" jdbcType="VARCHAR" /> 
 </resultMap>

如果我有字符串 userId

,有什么办法可以得到字符串 user_id

【问题讨论】:

  • 我很好奇,你为什么需要它?
  • 我需要它来动态生成一个sql
  • 我也想知道,但从我目前看到的情况来看,你必须手动编写。不过不确定。使这个想法更普遍并请求一个功能,我会支持它。 code.google.com/p/mybatis/issues/entry

标签: ibatis mybatis


【解决方案1】:

下面的代码sn-p是否满足你的要求?

String propertyName = "userId";
Pattern p = Pattern.compile("([a-z0-9])([A-Z])");
Matcher m = p.matcher(propertyName);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, m.group(1) + "_" + m.group(2).toLowerCase());
}
m.appendTail(sb);

【讨论】:

    【解决方案2】:
    Configuration configuration = sessionFactory.getConfiguration();
        ResultMap resultMap = configuration.getResultMap("User");
        for(ResultMapping resultMapping : resultMap.getResultMappings()) {
            System.out.println(resultMapping.getColumn() + "::"+resultMapping.getProperty());
        }
    

    一一获取column-property映射,就可以得到你的property的列名了。

    【讨论】:

      猜你喜欢
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 2018-11-16
      • 2023-03-20
      相关资源
      最近更新 更多