1 简介
1.1 单参数
在 Mybatis 中, 很多时候, 我们传入接口的参数只有一个。 对应接口参数的类型有两种, 一种是基本的参数类型, 一种是 JavaBean。
例如在根据主键获取对象时, 我们只需要传入一个主键的参数即可。 而在插入, 更新等操作时, 一般会涉及到很多参数, 我们就使用 JavaBean。
1.2 多参数
但是, 在实际的情况中, 我们遇到类似这样的情况可能:
- 接口需要使用的参数多于一个;
- 接口需要使用的参数又远少于对应 JavaBean 的成员变量, 或者需要多个 JavaBean 对象;
- 或者需要使用的参数对应 JavaBean 没有相应的成员变量。
比如 获取一段时间产生的日志信息, 日志对应的 JavaBean 只有一个日期, 那我们使用该 JavaBean 就无法满足我们的要求。
又比如我们进行模糊搜索, 搜索条件只有两个, 但对应的 JavaBean 有 50+ 个成员变量, 那创建对应的 JavaBean 就过于浪费了。
对此, 我知道的有如下几种方法
2 多个接口参数的两种使用方式
2.1 Map 方法(不推荐)
Map 方法的使用很简单, 就是将对应的参数以 key-value 的方式存储, key 对应 SQL 中的参数名字, value 对应需要传入的参数值。
以获取一段时间内存储的用户为例
2.1.1 创建接口方法
/** * 获取一段时间内的用户 * @param params * @return */ List<Student> selectBetweenCreatedTime(Map<String, Object> params);该方法返回的是多个记录, 因此使用 List 作为返回值。
2.1.2 配置对应的SQL
<select id="selectBetweenCreatedTime" parameterType="java.util.Map" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from student where gmt_created > #{bTime, jdbcType=TIMESTAMP} and gmt_created < #{eTime, jdbcType=TIMESTAMP} </select>id 与 之前创建的方法名一样。
2.1.3 调用
@Test public void testSelectBtweenCreatedTimeMap() { Map<String, Object> params = new HashMap<>(); Calendar bTime = Calendar.getInstance(); // month 是从0~11, 所以9月是8 bTime.set(2018, Calendar.AUGUST, 29); params.put("bTime", bTime.getTime()); Calendar eTime = Calendar.getInstance(); eTime.set(2018,Calendar.SEPTEMBER,2); params.put("eTime", eTime.getTime()); SqlSession sqlSession = null; try { sqlSession = sqlSessionFactory.openSession(); StudentMapper studentMapper = (StudentMapper) sqlSession.getMapper(StudentMapper.class); List<Student> students = studentMapper.selectBetweenCreatedTime(params); for (int i = 0; i < students.size(); i++) { System.out.println(students.get(i)); } } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } }调用方法很简单, 传入相应的 Map 参数即可。 此时, Map 中的 key 对应。 因此, 在此例子中传入的参数
- 传入一个 key 为 btime 的时间, 作为开始时间;
- 传入一个 key为 etime 的时间, 作为结束时间;
2.2 @Param 方法(推荐)
@Param 方法就是使用注解的方式,
2.2.1 创建接口方法
/** * 获取指定时间内的对象 *
