How to pass an Integer Array to IN clause in MyBatis

前端 未结 4 1328
旧巷少年郎
旧巷少年郎 2020-12-01 05:39

There is a query in my Mybatis containing an IN clause which is basically a set of Id\'s ( Integers)

I am now stuck on how can I pass an Integer array to this IN cla

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 06:17

    You can create a new type handler and use it only for your parameter. The query would change to:

    SELECT ... WHERE FIND_IN_SET(id, #{usrIds, typeHandler=my.pkg.ListTypeHandler}) <> 0
    

    And the type handler:

    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    import org.apache.ibatis.type.JdbcType;
    import org.apache.ibatis.type.ObjectTypeHandler;
    
    import com.google.common.base.Joiner;
    
    public class ListTypeHandler extends ObjectTypeHandler {
        @Override
        public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
            ps.setObject(i, Joiner.on(",").join((Iterable) parameter), JdbcType.OTHER.TYPE_CODE);
        }
    }
    

提交回复
热议问题