在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();
    }
上一篇:Mybatis注解学习-增删改查


下一篇:探索云网络技术前沿,Sigcomm 2019 阿里云参会分享