namespace
namespcae中的包名要和mapper接口中的方法名一致
- id:就是对应的namespace中的方法名
- resultType: Sql语法执行的返回值
- parameter: 参数类型
1、select(选择、查询语句)
1、编写接口
List<User> getUserList();
2、编写mapper中sql语句
<select id="getUserList" resultType="com.fan.pojo.User">
select * from mybatis.user
</select>
3、测试
@Test
public void text(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for(User user :userList){
System.out.println(user);
}
sqlSession.close();
}
2、Insert
1、编写接口
//添加用户
int addUser(User user);
2、编写mapper中sql语句
<insert id="addUser" parameterType="com.fan.pojo.User">
insert into mybatis.user (id,name,pwd) values(#{id},#{name},#{pwd})
</insert>
3、测试
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(4,"樊**","666666"));
sqlSession.commit();
sqlSession.close();
}
3、修改 select
1、编写接口
//修改用户
int updateUser(User user);
2、编写mapper中sql语句
<update id="updateUser" parameterType="com.fan.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id= #{id}
</update>
3、测试
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(4,"王五","555555"));
sqlSession.commit();
sqlSession.close();
}
4、删除 delete
1、编写接口
//删除用户
int deleteUser(int id);
2、编写mapper中sql语句
<delete id="deleteUser" parameterType="com.fan.pojo.User">
delete from mybatis.user where id =#{id}
</delete>
3、测试
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();
}
注意!!!
添加,删除,修改 都需要提交事务
sqlSession.commit();
-----------------------------
如果表中字段非常多,可以用Map或者 注解
Map传递参数,直接在sql中取出key即可 【parameterType="map"】
对象传递参数,直接在sql中取出对象的属性即可 【parameterType="objiect"】
只有一个基本参数类型的情况下,可以直接在sql中取到
1、编写接口
//万能Map
int addUser2(Map<String,Object> map);
2、编写在对应的mapper中sql语句
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,name,pwd) values(#{UserId},#{UserName},#{password})
</insert>
3、测试
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String,Object>();
map.put("UserId",4);
map.put("password","565656");
map.put("UserName","樊**");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
标签:mapper,UserMapper,练习,CRUD,sqlSession,user,sql,Mybatis,id From: https://www.cnblogs.com/fanstu/p/17573061.html