本博客项目结构1. 在UserMapper接口上定义增删改查2. 在UserMapper.xml编写对应的配置文件SQL3. 编写测试类CRUD
本博客项目结构
将UserMapper.xml中的namespace改为为UserMapper的路径 .
将UserDaoTest测试类中,定义的UserDao改为UserMapper
1. 在UserMapper接口上定义增删改查
2. 在UserMapper.xml编写对应的配置文件SQL
其中:
resultType:代表结果集的元素类型
parameterType:代表传参数进来的元素类似,int可省略不写
select * from user where id = #{id} insert into 2mybatis_first.user (id, name, pwd) values (#{id},#{name},#{pwd}); update 2mybatis_first.user set name=#{name},pwd=#{pwd} where id=#{id}; delete from 2mybatis_first.user where id=#{id};
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(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)