2. MybaitsCRUD操作 总览
参考狂神说MyBatis课程笔记
参考黑马程序员MyBaits课程笔记
MyBatis笔记思维导图:
思维导图笔记链接
问题扩展与汇总:
1.通过多个字段条件查询
1.1 使用@Param(“字段属性”),
-
多个参数,必须用注解进行指定 -
因有多个字段属性,需要在方法中传递参数
代码展示:
User getUserByNP(@Param("name") String name, @Param("pwd") String password);
<select id="getUserByNP" resultType="com.sheng.entity.User">
select <include refid="selectFields"></include>
from mybatis.user
where name = #{name} and pwd = #{pwd}
</select>
@Test
public void testGetUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
System.out.println(user);
User user2 = userMapper.getUserByNP("张三","abcdef");
System.out.println(user2);
sqlSession.close();
}
1.2 使用Map结构封装多个字段数据
- 接口中传递参数时,直接传map对象
- 配置sql语句时,map非基础类型,故需要传入
代码展示:
User getUserByNP2(Map<String, Object> map);
<select id="getUserByNP2" parameterType="map" resultType="com.sheng.entity.User">
select <include refid="selectFields"></include>
from mybatis.user
where name = #{name} and pwd = #{pwd}
</select>
@Test
public void testGetUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
System.out.println(user);
User user2 = userMapper.getUserByNP("张三","abcdef");
System.out.println(user2);
Map<String, Object> map = new HashMap<>();
map.put("name", "张三");
map.put("pwd", "abcdef");
User user3 = userMapper.getUserByNP2(map);
System.out.println(user3);
sqlSession.close();
}
|