1. 程式人生 > 其它 >Mybatis(crud)

Mybatis(crud)

namespace

namespace中包名要和Dao/mapper介面的包名一致

xml標籤配置

選擇,查詢語句:
id:就是對應的namespace中的方法名:
resultType:Sql語句執行的返回值!
parameterType:引數型別!

select

編寫介面

List<User> getUserList();

編寫mapper中的sql語句

<select id="getUserList" resultType="com.my.pojo.User">
   select * from mybatis.user
</select>

測試

@Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userDao=sqlSession.getMapper(UserMapper.class);
        List<User> userlist =userDao.getUserList();
        for (User user : userlist) {
            System.out.println(user);
        }
        //關閉SqlSession
        sqlSession.close();
    }

insert

編寫介面

    //insert 一個使用者
    int addUser(User user);

編寫mapper中的sql語句

<insert id="addUser" parameterType="com.my.pojo.User">
        insert  into mybatis.user(id,name,pwd)values (#{id},#{name},#{pwd})
</insert>

測試

//增刪改查需要提交事務
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //MAPPER.就是物件
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
         int res = mapper.addUser(new User(4,"哈哈哈","12333"));
        if(res>0)
        {
            System.out.println("插入成功");
        }
        sqlSession.commit();
        //關閉sql流物件
        sqlSession.close();
    }

update

編寫介面

int updateUser(User user);

編寫mapper中的sql語句

<update id="updateUser" parameterType="com.my.pojo.User">
        update mybatis.user set name =#{name},pwd =#{pwd}  where id=#{id}
</update>

測試

@Test
    public void  updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(4,"HEHE","12345"));
        sqlSession.commit();

        sqlSession.close();
    }

Delete

編寫介面

    //刪除一個使用者
    int deleteUser(int id);

編寫mapper中的sql語句

<delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id =#{id};
</delete>

測試

public void delteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(4);
        sqlSession.commit();
        sqlSession.close();
    }