1.通过注解实现增删改查的代码

    package com.lixv.dao;
    
    import com.lixv.entity.User;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    import java.util.Map;
    
    public interface UserMapper {
        //通过注解查询
        @Select("select * from mybatis_test.user")
        List<User> getUsersByAnnotate();
    
        //通过注解使用id进行查询
        @Select("select * from mybatis_test.user where id = #{uid}")
        User getUserByIdThroughAnnotate(@Param("uid") int id);
    
        //通过注解使用id进行新增
        @Select("insert into mybatis_test.user (id, name, pwd) values (#{id},#{name},#{pwd})")
        User insertUserThroughAnnotate(User user);
    
        //通过注解使用id进行更新
        @Select("update mybatis_test.user set name=#{name},pwd=#{pwd} where id=#{id}")
        User updateUserThroughAnnotate(User user);
    
        //通过注解使用id进行删除
        @Select("delete from mybatis_test.user where id=#{uid}")
        User deleteUserThroughAnnotate(@Param("uid") int id);
    }

2.代码讲解

  1. 增删改查分别使用@Insert、@Delete、@Update、@Select注解
  2. 方法参数课作为sql语句的参数,使用#{参数}的方式进行使用
  3. 当参数不止一个的时候,一定在前面加上@Param注解进行区分,#{}里面使用@Param中的值
  4. 当参数加上了@Param注解的时候,xml配置文件中的SQL语句,也需要使用@Param中的值
  5. 当参数为多个的时候,@Param的使用如下:
 //通过注解使用id进行查询
@Select("select * from mybatis_test.user where id = #{uid} and name = #{uname}")
User getUserByIdThroughAnnotate(@Param("uid") int id,@Param("uname") String name);
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐