文章目录
本博客项目结构
将UserMapper.xml
中的namespace改为为UserMapper的路径 .
将UserDaoTest测试类
中,定义的UserDao改为UserMapper
1. 在UserMapper接口上定义增删改查
2. 在UserMapper.xml编写对应的配置文件SQL
其中:resultType
:代表结果集的元素类型
parameterType
:代表传参数进来的元素类似,int可省略不写
<select id="selectUserById" resultType="com.pojo.User" parameterType="int">
select * from user where id = #{id}
</select>
<insert id="addUser" parameterType="com.pojo.User" >
insert into 2mybatis_first.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.pojo.User">
update 2mybatis_first.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from 2mybatis_first.user where id=#{id};
</delete>
3. 编写测试类CRUD
所有的增删改操作(查询不用)
都需要提交事务!即最后要有:(否则失败)
session.commit();
public class CURD {
//根据id查询
@Test
public void tsetSelectUserById() {
SqlSession session = MybatisUtils.getSqlSession(); //获取SqlSession连接
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);
System.out.println(user);
session.close();
}
//增删改需要提交事务,查不用
@Test
public void addUser(){
SqlSession session = MybatisUtils.getSqlSession(); //获取SqlSession连接
UserMapper mapper = session.getMapper(UserMapper.class);
int flag = mapper.addUser(new User(4, "hhhhhh", "1234567"));
if(flag>0) System.out.println("插入成功");
//提交事务
session.commit();
session.close();
}
@Test
public void updateUser(){
SqlSession session = MybatisUtils.getSqlSession(); //获取SqlSession连接
UserMapper mapper = session.getMapper(UserMapper.class);
int flag = mapper.updateUser(new User(4, "xxxxx", "1234567"));
if(flag>0) System.out.println("修改成功");
//提交事务
session.commit();
session.close();
}
@Test
public void deleterUser(){
SqlSession session = MybatisUtils.getSqlSession(); //获取SqlSession连接
UserMapper mapper = session.getMapper(UserMapper.class);
int flag = mapper.deleteUser(4);
if(flag>0) System.out.println("删除成功");
//提交事务
session.commit();
session.close();
}
}