开始
1. 在接口中增加一个方法
public List<t1Item> getT1ByMap(Map<String,Object> map);2. 在mapper配置文件中编写对应的标签
<select id="getT1ByMap" resultType="com.example.mybatis.t1Item">
select * from t1
<where>
<if test="id!=null">
id = #{id}
</if>
<if test="name!=null">
and name like concat('%',#{name},'%')
</if>
</where>
</select>3. 测试
@Test
void contextLoads() throws IOException, SQLException {
SqlSessionFactory sessionFactory = SessionFactory.getSessionFactory();
try (SqlSession session = sessionFactory.openSession()) {
t1Mapper mapper = session.getMapper(t1Mapper.class);
HashMap<String,Object> map=new HashMap<>();
map.put("name","8");
List<t1Item> t1ByMap = mapper.getT1ByMap(map);
t1ByMap.forEach(System.out::println);
}
}注意
使用map里的数据时需要检查数据是否存在
<if test="id!=null"> id = #{id} </if>使用 like 进行模糊化匹配时,推荐使用name like concat(‘%’,#{name},’%’) ,这样可以避免sql注入
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!