1.namespace
namespace中的包名要和Dao/Mapper接口的包名一致!
2.select
选择,查询语句
id:对应namespace中的方法名
resultType:sql执行的返回类型
parameterType:参数的类型
1.编写接口
//查询
List<User> getUserList();
2.在对应Mapper.xml中实现接口(编写sql语句)
<mapper namespace="com.zuo.dao.userMapper">
<select id="getUserList" resultType="com.zuo.entity.User" >
select * from mybatis.user
</select>
</mapper>
3.测试
@Test
public void test(){
//1.获取sqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//获取对应的接口
userMapper mapper = sqlSession.getMapper(userMapper.class);
List<User> userList = mapper.getUserList();
for (User user:userList) {
System.out.println(user);
}
//关闭sqlSession对象
sqlSession.close();
}
3.Insert
userMapper.java
//添加
int addUser(User user);
userMapper.xml
<insert id="addUser" parameterType="com.zuo.entity.User">
Insert into mybatis.user values(#{id},#{name},#{pwd})
</insert>
UserDaoTest.java
@Test
public void addUser(){
//获取执行sql的对象 sqlSession
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//获取接口
userMapper mapper = sqlSession.getMapper(userMapper.class);
mapper.addUser(new User(4, "haha", "123456"));
//提交事务
sqlSession.commit();
//关闭sqlSession
sqlSession.close();
}
4.Update
5.Delete
6.万能的Map
假设,实体类的或数据库中的表,字段和参数过多,考虑使用Map!
当进行修改某一些字段时,考虑使用Map!
int updateUser2(Map<String,Object> map);
<update id="updateUser2" parameterType="map">
update mybatis.user set name=#{name} where id=#{id}
</update>
@Test
public void updateUser2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("id",3);
map.put("name","wangwu");
int i = mapper.updateUser2(map);
System.out.println("受影响的行数:"+i);
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可!
对象传递参数,直接在sql中取对象的属性即可!
只有一个基本类型参数的情况下,可以直接在sql中取到!
多个参数用Map,或者是注解!!
7.模糊查询
1.Java代码执行的时候,传递通配符%%
List<User> userList = mapper.getUserLike("%李%");
2.在sql拼接中使用通配符!(防止sql注入问题)
select * from mybatis.user where name Tike "%#{value}%"
注意:
(1)增删改需要提交事务 ---> sqlSession.commit();
(2)其中#{参数名}是提取数据的作用,参数是对象#{对象的属性名}
标签:mapper,Map,--,userMapper,CRUD,sqlSession,user,sql,改查 From: https://www.cnblogs.com/zuok/p/17023804.html