如何在mybatis中参数化tablename

时间:2017-03-03 08:11:55

标签: mybatis

我想参数化table_name:t_user_address_book(uid / 500000)。 例如:当uid = 1000时,table_name = t_user_address_book0; 当uid = 500001时,table_name = t_user_address_book1; 怎么写?

public interface UserAddressBookMapper {
    @Insert("insert into t_user_address_book? values(...)")
    int upsert(Long uid, UserAddressBookMsg userAddressBookMsg);
}

2 个答案:

答案 0 :(得分:2)

您可以选择包含Mybatis XML代码的表:

<choose>
  <when test="uid gt 1000000">
    <bind name="tableName" value="t_user_address_book2" />
  </when>
  <when test="uid gt 500000">
    <bind name="tableName" value="t_user_address_book1" />
  </when>
  <otherwise>
    <bind name="tableName" value="t_user_address_book0" />
  </otherwise>
</choose>

或者您可以在java中计算表名并将其作为参数传递。

无论您的选择是什么,查询中的表名参数都必须使用$表示法而不是#引用,因为该值必须替换占位符,因为它是查询的一部分而不是被解释/绑定/转义为参数:

INSERT INTO ${tableName} ...

尽管使用了XML,但您可以使用<script>标记来粘贴查询周围的注释:

@Insert({"<script>", 
         "<choose> ...", 
         "INSERT ..."
         "</script>"
})

当使用带注释的Mapper界面时,您需要将参数命名为多于1:

@Insert("INSERT INTO table VALUES(#{uid}, #{userAddressBookMsg.propertyName1})")
int upsert(upsert(@Param("uid")Long uid, @Param("userAddressBookMsg") UserAddressBookMsg userAddressBookMsg);

但是,似乎您希望将多个表拆分为卷问题,这样处理起来要复杂得多,而最好是保留单个表并在数据库端查看索引和分区。

答案 1 :(得分:-2)

快速回复将是&#34; no&#34;。不能将表名作为参数,因为mybatis使用预准备语句。

我建议使用表名作为变量,并将其赋予语句字符串。 例如:

public interface UserAddressBookMapper { 

static String tableName;
static void setTableName(String name) {
  tableName = name;
}

@Insert({"insert into", tableName, "values(...)"})
int upsert(UserAddressBookMsg userAddressBookMsg);

在调用方法之前,您必须设置tableName