xml元素

  • namespace
    xml中的namespace与dao接口的包名一致
  • id
    xml中的id与dao接口的方法名一致
  • resultType
    sql语句执行的返回值
  • parameterType
    参数类型

select

  1. 编写接口
//查询全部用户
List<User> getUserList();
  1. 编写sql语句
<!--select查询语句-->
<select id="getUserList" resultType="com.sunfl.pojo.User">
    select * from mybatis.user
</select>
  1. 测试
@Test
public void test(){
    //获得SqlSession对象
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    //方式一:执行SQL  推荐
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    List<User> userList = userMapper.getUserList();

    //方式二:
//        List<User> userList = sqlSession.selectList("com.sunfl.dao.UserDao.getUserList");

    for (User user : userList) {
        System.out.println(user);
    }

    //关闭sqlSession
    sqlSession.close();
}

insert

  1. 编写接口
//新增一个用户
int addUser(User user);
  1. 编写sql语句
<insert id="addUser" parameterType="com.sunfl.pojo.User">
    insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>
  1. 测试
@Test
public void addUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    mapper.addUser(new User(4, "哈哈哈", "12323"));
    sqlSession.commit();
    sqlSession.close();
}

update

  1. 编写接口
//更新一个用户
int updateUser(User user);
  1. 编写sql语句
<update id="updateUser" parameterType="com.sunfl.pojo.User">
    update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
  1. 测试
@Test
public void updateUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    mapper.updateUser(new User(4,"嘿嘿","1111"));
    sqlSession.commit();
    sqlSession.close();
}

delete

  1. 编写接口
//删除一个用户
int deleteUser(int id);
  1. 编写sql语句
<delete id="deleteUser" parameterType="int">
    delete from mybatis.user where id = #{id};
</delete>
  1. 测试
@Test
public void deleteUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    mapper.deleteUser(4);
    sqlSession.commit();
    sqlSession.close();
}

向日葵
1 声望1 粉丝

« 上一篇
Mybatis简介