在MyBatis中使用注解实现增删改查

在Mybatis.xml中配置

<!--注册接口-->
    <mappers>
        <mapper class="com.Google.Dao.userMapper"/>
    </mappers>

 //增加
    @Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})")
    int insert(@Param("id") int id,@Param("name") String name,@Param("pwd") String Password);
```java
public void insert (){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        userMapper mapper = sqlSession.getMapper(userMapper.class);
        int i = mapper.insert(5, "xixi","23234234");
        if(i>0){
            sqlSession.commit();
        }
        sqlSession.close();
    }

 //删除
    @Delete("delete from user where id = #{id}")
    int Delete (int id);
@Test
    public void Delete (){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        userMapper mapper = sqlSession.getMapper(userMapper.class);
        int i = mapper.Delete(1);
        if(i>0){
            sqlSession.commit();
        }
        sqlSession.close();
    }

//修改
    @Update("update user set name=#{name} where id=#{id}")
    int update (@Param("name") String name,@Param("id") int id);
@Test
    public void update (){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        userMapper mapper = sqlSession.getMapper(userMapper.class);
        int i = mapper.update("haha", 1);
        if(i>0){
            sqlSession.commit();
        }
        sqlSession.close();
    }

//查询
    @Select("select * from user where id=#{id}")
    User getUserByID1(@Param("id") int id);
public void getUserByID(){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        userMapper mapper = sqlSession.getMapper(userMapper.class);
        User user = mapper.getUserByID1(2);
        System.out.println(user);
        sqlSession.close();
    }
posted @ 2022-01-21 21:10  小罗要有出息  阅读(107)  评论(0编辑  收藏  举报