美文网首页
Mybatis-5.注解查询

Mybatis-5.注解查询

作者: Blacol | 来源:发表于2022-04-29 19:17 被阅读0次

    Mybatis提供了一系列的注解,极大地方便了开发人员对数据库的操作。使用注解操作时可以不用编写Mapper映射文件。下面介绍一些常用的注解。
    在正式介绍之前先说明Mybatis配置文件、Mapper、Mapper映射文件之间的区别
    Mybatis配置文件是告诉Mybatis连接哪个数据库用的、要去扫描哪个Mapper和Mapper映射文件的。相当于是Mybatis的总指挥。
    Mapper是封装方法用的接口,这些方法通过Mapper映射文件绑定一些sql语句,执行特定方法就会执行特定sql语句。
    Mapper映射文件是告知mapper什么方法执行哪个sql语句用的。
    这三个文件的作用不要弄混,在后面的章节中这三个文件还会经常出现。

    @Select注解

    相当于Mapper映射文件中的select标签可以在注解中直接写sql语句,就像下面这样:

    @Select("select * from user")
    List<User> selectAllUsers();
    

    有注解在就不需要在Mapper映射文件中为它绑定sql语句了。
    注解也可以写带有where的语句和带有参数的语句如

    @Select("select ID,name from user where name like #{firstname}%")
    List<User> selectUsersByFirstname(String firstname);
    

    但是只用select注解是无法完成一对一、一对多和多对多查询的。同时,无法使用动态SQL。
    对于其他的注解如@Update,@Insert,@Delete使用方法都是一样的,这里就不多说了。
    如果需要完成一对一、一对多、多对多查询的话可以先使用Mapper映射文件。到后面章节会有注解方法的关联映射。

    实操-小银行

    功能:

    1. 可以开户
    2. 可以存款、取款
    3. 可以转账、导出指定账户的账户日志

    项目类型:Maven项目(控制台)
    使用的技术:

    1. Mybatis
    2. Maven

    开始制作:

    1. 创建maven项目(创建过程省略)
    2. 导入依赖
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.5.9</version>
      </dependency>
      <dependency><dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis</artifactId>
              <version>3.5.9</version>
          </dependency>
          <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>8.0.28</version>
          </dependency>
      </dependency>
      
    3. 创建数据表-bank_user,bank_action_log
      create table bank_user
      (
      id         varchar(20)                         not null comment '银行卡号(规则:1001-开户日期-开户用户身份证号后4位-4位随机数)'
          primary key,
      name       varchar(20)                         not null comment '用户姓名',
      idNumber   varchar(18)                         not null comment '身份证号',
      createDate timestamp default CURRENT_TIMESTAMP null comment '开户时间',
      state      int                                 null comment '用户状态: 0-被锁定 1-正常',
      money decimal(20,2) default '0.00',
      constraint bank_user_id_uindex
          unique (id),
      constraint IdNumberCheck
          check (length(`idNumber`) = 18),
      constraint stateCheck
          check ((`state` = 0) or (`state` = 1))
      );
      create table bank_action_log
      (
      time   timestamp default CURRENT_TIMESTAMP not null,
      actor  varchar(20)                         not null,
      action text                                not null,
      state  int                                 null,
      constraint bank_action_log_bank_user_id_fk
          foreign key (actor) references bank_user (id),
      constraint actionStateCheck
          check ((`state` = 0) or (`state` = 1))
      );
      
    4. 创建软件包并创建实体类BankUser和BankActionLog
      public class BankUser {
        private String id;
        private String name;
        private String idNumber;
        private java.sql.Timestamp createDate;
        private long state;
        private BigDecimal money;
        
        //Getter,Setter
      }
      
      public class BankActionLog {
        private java.sql.Timestamp time;
        private String actor;
        private String action;
        private long state;
        //Getter,Setter
      }
      
    5. 编写mybatis配置文件(略)
    6. 创建Mapper。
      @Mapper
      public interface BankUserMapper {
        @Insert("insert into bank_user values(#{id},#{name},#{idNumber},#{createDate},1,default )")
        boolean createUser(BankUser user);
        @Update("update bank_user set money=money+#{money} where id=#{id}")
        boolean actMoney(@Param("id") String id,@Param("money") BigDecimal money);
        @Select("select * from bank_user where id=#{id}")
        BankUser selectUser(String id);
      }
      
      public interface BankActionLogMapper {
        @Select("select * from mybatisLesson.bank_action_log where actor=#{userId}")
        List<BankActionLog> selectLogsByUserId(String userId);
        @Select("select * from mybatisLesson.bank_action_log where actor=#{userId} and (time>=#{dateFrom} and time<=#{dateTo})")
        List<BankActionLog> selectLogsByDateAndUserId(@Param("userId") String userId,@Param("dateFrom") Date dateFrom
              ,@Param("dateTo") Date dateTo);
        @Insert("insert mybatisLesson.bank_action_log values(#{time},#{actor},#{action},#{state})")
        boolean insertLog(BankActionLog log);
      }
      
    7. 创建数据库工具类
      public class DBUtil {
          public static SqlSession getSqlSession() throws IOException {
              SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
              InputStream is = Resources.getResourceAsStream("mybatis.xml");
              SqlSessionFactory factory = builder.build(is);
              return factory.openSession();
          }
      }
      
    8. 创建服务类BankActioinLogService、BankUserService。(在Main中直接调用service类就可以实现数据库的操作)
      Service类封装了session和mapper,直接调用特定方法会自动操作session和mapper对象并根据是否成功自动回滚或者提交。
      (代码太长,我放在后面的源代码中,自行下载)
    9. 创建主类(代码省略,在源代码中,自行下载)

    项目源代码:
    https://blacol.lanzouf.com/i7qMq0407i7c
    密码:ssefr[


    MyBatis的教程就告一段落,下一部分是Spring。

    相关文章

      网友评论

          本文标题:Mybatis-5.注解查询

          本文链接:https://www.haomeiwen.com/subject/gizjyrtx.html