我对你所有的偏执与贪心,都来自我对你二十四小时满满当当的爱。
1、namespace
namespace中的包名要和Dao/mapper接口的包名保持一致
2、select
选择查询语句
- id:就是对应的namespace中的方法名
- resultType:SQL语句执行的返回值
- parameterType:参数类型
编写接口
package com.rui.dao; import com.rui.pojo.User; import java.util.List; public interface UserMapper { //根据id查询用户 User getUserById(int id); }
编写对应的mapper中的sql语句
<select id="getUserById" resultType="com.rui.pojo.User" parameterType="int"> /*定义sql*/ select * from mybatis.user where id = #{id}; </select>
测试
@Test public void getUserById(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); }
3、Insert
4、Update
5、Delete
6、分析错误
- 标签不要匹配错误
- resource绑定mapper,需要使用路径
- 程序配置文件必须符合规范
- NullPointException,没有注册到资源
- 输出的xml文件中存在中文乱码问题
- maven资源没有导出问题
7、万能Map
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map
//万能Map
int addUser2(Map<String,Object> map);
<!--对象中的属性,可以直接取出来 parameterType=传递map中的key-->
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id, name, pwd) values (#{userId},#{userName},#{password});
</insert>
//万能map
@Test
public void addUser2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("userId",4);
map.put("userName","王五");
map.put("password","23333");
mapper.addUser2(map);
//提交事务
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可。【parameterType = "map"】
对象传递参数,直接在sql中取对象的属性即可。【parameterType = "Object"】
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用Map,或者注解
8、模糊查询
Java代码执行的时候传递统配符%%
List<User> userList=mapper.getUserLike("%李%");
在sql拼接中使用通配符
select * from mybatis.user where name like "%"#{value}"%"