day63( MYBATIS框架基础1:关于Mybatis框架,创建Mybatis-Spring工程,配置开发环境,基本使用,删除与修改数据)

day63( MYBATIS框架基础1:关于Mybatis框架,创建Mybatis-Spring工程,配置开发环境,基本使用,删除与修改数据)

1.关于Mybatis框架

1.概念:

  • Mybatis的主要作用是快速实现对关系型数据库中的数据进行访问的框架

  • 在原生的Java技术中,需要使用JDBC实现对数据库中的数据访问,执行过程繁琐且相对固定,使用框架可以有效的提高开发效率

2.创建Mybatis-Spring工程

  • 前提: Mybatis可以不依赖于Spring等框架直接使用的,但是,就需要进行大量的配置,前期配置工作量较大,基于Spring框架目前是业内使用的标准之一,所以,通常会整合Spring与Mybatis,以减少配置

  • 在创建工程时,创建普通的Maven工程即可(不需要选择特定的骨架)

1. 在pom.xml中添加几个依赖项

   <dependencies>
       <!--        Mybatis的依赖项:mybatis-->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.5.6</version>
       </dependency>
       <!--        Mybatis整合Spring的依赖项:mybatis-spring-->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis-spring</artifactId>
           <version>2.0.6</version>
       </dependency>
       <!--        Spring的依赖项:spring-context-->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context</artifactId>
           <version>5.3.14</version>
       </dependency>
       <!--        Spring JDBC的依赖项:spring-jdbc-->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-jdbc</artifactId>
           <version>5.3.14</version>
       </dependency>
       <!--        MySQL连接的依赖项:mysql-connector-java-->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>8.0.21</version>
       </dependency>
       <!--         数据库连接池的依赖项:commons-dbcp2-->
       <dependency>
           <groupId>org.apache.commons</groupId>
           <artifactId>commons-dbcp2</artifactId>
           <version>2.8.0</version>
       </dependency>
       <!--        JUnit测试的依赖项:junit-jupiter-api-->
       <dependency>
           <groupId>org.junit.jupiter</groupId>
           <artifactId>junit-jupiter-api</artifactId>
           <version>5.8.2</version>
           <scope>test</scope>
       </dependency>
   </dependencies>

2.创建测试类

  1. 可以在src/test/java下创建测试类,并编写测试方法,例如:

    package cn.tedu.mybatis;
    import org.junit.jupiter.api.Test;
    public class MybatisTests {
    @Test
    public void contextLoads() {
    System.out.println("MybatisTests.contextLoads()");
    }
    }
  2. 由于目前尚未编写实质的代码,以上测试代码也非常简单,应该是可以成功通过测试的,如果不能通过测试,必然是开发工具、开发环境、依赖项、项目创建步骤等问题

3.配置Mybatis的开发环境

1.创建数据库

登录MySQL控制台,创建名为mall_ams的数据库:

CREATE DATABASE mall_ams;

2.在IntelliJ IDEA中配置数据库视图:

  • http://doc.canglaoshi.org/doc/idea_database/index.html

    1. 通过数据库视图的Console面板创建数据表:

      create table ams_admin (
      id bigint unsigned auto_increment,
      username varchar(50) default null unique comment '用户名',
      password char(64) default null comment '密码(密文)',
      nickname varchar(50) default null comment '昵称',
      avatar varchar(255) default null comment '头像URL',
      phone varchar(50) default null unique comment '手机号码',
      email varchar(50) default null unique comment '电子邮箱',
      description varchar(255) default null comment '描述',
      is_enable tinyint unsigned default 0 comment '是否启用,1=启用,0=未启用',
      last_login_ip varchar(50) default null comment '最后登录IP地址(冗余)',
      login_count int unsigned default 0 comment '累计登录次数(冗余)',
      gmt_last_login datetime default null comment '最后登录时间(冗余)',
      gmt_create datetime default null comment '数据创建时间',
      gmt_modified datetime default null comment '数据最后修改时间',
      primary key (id)
      ) comment '管理员' charset utf8mb4;

3.创建datasource.properties配置文件

  • 在src/main/resources下创建datasource.properties配置文件,用于配置连接数据库的参数,例如:

    datasource.url=jdbc:mysql://localhost:3306/mall_ams?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    datasource.driver=com.mysql.cj.jdbc.Driver
    datasource.username=root
    datasource.password=root
    • 提示:以上配置中的属性名称应该添加前缀,避免与系统环境变量冲突,例如在Windows操作系统中,username则表示登录系统的用户名

4.创建SpringConfig类

  • 在cn.tedu.mybatis包下(不存在,则创建)创建SpringConfig类,读取以上配置文件:

    @Configuration
    @PropertySource("classpath:datasource.properties")
    public class SpringConfig {
    }
    • 提示:@PropertySource是Spring框架的注解,用于读取properties类型的配置文件,读取到的值将存入到Spring容器的Environment对象中

5. 测试方法中补充测试代码:

@Test
public void contextLoads() {
System.out.println("MybatisTests.contextLoads()");
AnnotationConfigApplicationContext ac
= new AnnotationConfigApplicationContext(SpringConfig.class);ConfigurableEnvironment environment = ac.getEnvironment();
System.out.println(environment.getProperty("datasource.url"));
System.out.println(environment.getProperty("datasource.driver"));
System.out.println(environment.getProperty("datasource.username"));System.out.println(environment.getProperty("datasource.password"));ac.close();
}

6. 在SpringConfig中配置一个DataSource对象:

@Configuration
@PropertySource("classpath:datasource.properties")
public class SpringConfig {
@Bean
public DataSource dataSource(Environment env) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(env.getProperty("datasource.url"));
dataSource.setDriverClassName(env.getProperty("datasource.driver"));dataSource.setUsername(env.getProperty("datasource.username"));dataSource.setPassword(env.getProperty("datasource.password"));return dataSource;
}
}

7.测试方法中补充测试代码:

@Test
public void testConnection() throws Exception {
AnnotationConfigApplicationContext ac
= new AnnotationConfigApplicationContext(SpringConfig.class);DataSource dataSource = ac.getBean("dataSource"
, DataSource.class);Connection connection = dataSource.getConnection();
System.out.println(connection);
ac.close();
}

4.Mybatis的基本使用

1.作用:

  1. 当使用Mybatis实现数据访问时,主要:

    1. 编写数据访问的抽象方法

    2. 配置抽象方法对应的SQL语句

2. 关于抽象方法:

  1. 必须定义在某个接口中,这样的接口通常使用Mapper作为名称的后缀,例如AdminMapper

    • Mybatis框架底层将通过接口代理模式来实现

  2. 方法的返回值类型:

    1. 如果要执行的数据操作是增、删、改类型的,统一使用int作为返回值类型,表示“受影响的行数” ,也可以使用void,但是不推荐

    2. 如果要执行的是查询操作,返回值类型只需要能够装载所需的数据即可

  3. 方法的名称:自定义,不要重载,建议风格如下:

    1. 插入数据使用insert作为方法名称中的前缀或关键字

    2. 删除数据使用delete作为方法名称中的前缀或关键字

    3. 更新数据使用update作为方法名称中的前缀或关键字

    4. 查询数据时:

      1. 如果是统计,使用count作为方法名称中的前缀或关键字

      2. 如果是单个数据,使用getfind作为方法名称中的前缀或关键字

      3. 如果是列表,使用list作为方法名称中的前缀或关键字

      4. 如果操作数据时有条件,可在以上前缀或关键字右侧添加by字段名,例如deleteById

  4. 方法的参数列表:取决于需要执行的SQL语句中有哪些参数,如果有多个参数,可将这些参数封装到同一个类型中,使用封装的类型作为方法的参数类型

    1. 例如:假设当需要实现“插入一条管理员数据”,则需要执行的SQL语句大致是

    insert into ams_admin (username, password, nickname, avatar,phone,email, description, is_enable, last_login_ip, login_count,
    gmt_last_login, gmt_create, gmt_modified) values (?,?,? ... ?);
    1. 由于以上SQL语句中的参数数量较多,则应该将它们封装起来,则在cn.tedu.mybatis包下创建Admin类,声明一系列的属性,对应以上各参数值:

    package cn.tedu.mybatis;
    import java.time.LocalDateTime;
    public class Admin {
    private String username; private String password;
    private String nickname; private String avatar;
    private String phone; private String email;
    private String description; private Integer isEnable;
    private String lastLoginIp; private Integer loginCount;
    private LocalDateTime gmtLastLogin; private LocalDateTime gmtCreate;
    private LocalDateTime gmtModified;
    // Setters & Getters // toString()
    }
    1. 在cn.tedu.mybatis包下创建mapper.AdminMapper接口,并在接口中添加“插入1条管理员数据”的抽象方法:

      package cn.tedu.mybatis.mapper;
      import cn.tedu.mybatis.Admin;
      public interface AdminMapper {
      int insert(Admin admin);
      }
    2. 所有用于Mybatis处理数据的接口都必须被Mybatis识别,有2种做法

      1. 在每个接口上添加@Mapper注解

      2. 【推荐】在配置类上添加@MapperScan注解,指定接口所在的根包

        1. 例如,在SpringConfig上添加配置@MapperScan:

          @Configuration
          @PropertySource("classpath:datasource.properties")
          @MapperScan("cn.tedu.mybatis.mapper")
          public class SpringConfig {
          // ... ...
          }
        2. 注意:因为Mybatis会扫描以上配置的包,并自动生成包中各接口中的代理对象,所以,千万不要放其它接口文件

  5. 接下来,需要配置抽象方法对应的SQL语句,这些SQL语句推荐配置在XML文件中

  6. 可以从 http://doc.canglaoshi.org/config/Mapper.xml.zip下载到XML文件。在项目的src/main/resources下创建mapper文件夹,并将下载得到的XML文件复制到此文件夹中,重命名为AdminMapper.xml。

    1. 打开XML文件夹,进行配置

      <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <!-- 根节点必须是mapper -->
      <!-- 根节点的namespace属性用于配置此XML对应哪个接口 -->
      <mapper namespace="cn.tedu.mybatis.mapper.AdminMapper">
      <!-- 根据需要执行的SQL语句的种类选择需要配置的节点名称-->
      <!-- 配置SQL的节点的id属性取值为抽象方法名称 -->
      <!-- 在节点内部配置SQL语句 -->
      <!-- SQL语句中的参数值使用 #{} 格式的占位符表示 -->
      <insert id="insert">
      insert into ams_admin (
      username, password, nickname, avatar,
      phone, email, description, is_enable,
      last_login_ip, login_count, gmt_last_login, gmt_create,
      gmt_modified
      ) values (
      #{username}, #{password}, #{nickname}, #{avatar},
      #{phone}, #{email}, #{description}, #{isEnable},
      #{lastLoginIp}, #{loginCount}, #{gmtLastLogin}, #{gmtCreate},#{gmtModified}
      )
      </insert>
      </mapper>
    2. 最后,还需要将DataSource配置给Mybatis框架,并且,为Mybatis配置这些XML文件的路径,这2项配置都将通过配置SqlSessionFactoryBean来完成

      1. 先在datasource.properties中补充一条配置:

        mybatis.mapper-locations=classpath:mapper/AdminMapper.xml
      2. 在配置类中创建SqlSessionFactoryBean类型的对象:

        @Bean
        public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource,@Value("${mybatis.mapper-locations}") Resource mapperLocations){SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(mapperLocations);
        return sqlSessionFactoryBean;
        }
      3. 在测试类中补充测试方法,以检验是否可以通过调用AdminMapper的insert()方法插入数据:

        @Test
        public void testInsert() {
        AnnotationConfigApplicationContext ac
        = new AnnotationConfigApplicationContext(SpringConfig.class);AdminMapper adminMapper = ac.getBean(AdminMapper.class);
        Admin admin = new Admin();
        admin.setUsername("admin001");
        admin.setPassword("12345678");
        adminMapper.insert(admin);
        ac.close();
        }
        
      4. 如果某数据的id是自动编号,当需要获取新增的数据的id时,需要先使得插入的数据类型中有id对应的属性,则在Admin类中添加id属性:

        public class Admin {
        private Long id;
        // 原有其它属性及Setter & Getter
        // 补充id的Setter & Getter
        // 重新生成toString()
        }
        
      5. 接下来,在节点配置2个属性,分别是useGeneratedKeys和keyProperty:

        <insert id="insert" useGeneratedKeys="true" keyProperty="id">原有代码
        </insert>
        
      6. 当配置完成后,Mybatis执行此插入数据的操作后,会将自动编号的id赋值到参数Admin admin的id属性中,以上keyProperty指的就是将自动编号的值放回到参数对象的哪个属性中!

     

5.删除与修改数据

1.目标(根据id删除某一条数据 )

根据id删除某一条数据

2.执行

  1. SQL

    delete from ams_admin where id=?
    
  2. 在AdminMapper接口中添加抽象方法:

    int deleteById(Long id);
    
  3. 在AdminMapper.xml中配置以上抽象方法映射的SQL语句:

    <delete id="deleteById">
    delete from ams_admin where id=#{id}
    </delete>
    
  4. 编写并执行测试:

    @Test
    public void testDeleteById() {
    AnnotationConfigApplicationContext ac
    = new AnnotationConfigApplicationContext(SpringConfig.class);
    AdminMapper adminMapper = ac.getBean(AdminMapper.class);
    Long id = 12L;
    int rows = adminMapper.deleteById(id);
    // System.out.println("删除完成,受影响的行数=" + rows);
    if (rows == 1) {
    System.out.println("删除成功");
    } else {
    System.out.println("删除失败,尝试删除的数据(id=" + id + ")不存在!");
    }
    ac.close();
    }
    

    3.目标(根据 id修改某一条数据 )

    4.执行

    1. SQL

      update ams_admin set password=? where id=?
      
    2. 在AdminMapper接口中添加抽象方法:

      int updatePasswordById(@Param("id") Long id,
      @Param("password") String password);
      
      1. 提示:在默认情况下,当Java程序源代码(.java文件)经过编译后,所有局部的量的名称都会丢失,为使得配置SQL语句时可根据指定的名称使用方法中的参数值,需要在方法的各参数前添加@Param以指定名称

        • 如果方法的参数只有1个,则可以不使用@Param指定名称,因为Mybatis可以直接找到此参数的值

    3. 在AdminMapper.xml中配置以上抽象方法映射的SQL语句:

      <update id="updatePasswordById">
      update ams_admin set password=#{password} where id=#{id}</update>
      
      • 提示:以上占位符中的名称是通过@Param注解指定的名称,而不是抽象方法的参数名称

    4. 编写并执行测试:

      @Test
      public void testUpdatePasswordById() {
      AnnotationConfigApplicationContext ac
      = new AnnotationConfigApplicationContext(SpringConfig.class);
      AdminMapper adminMapper = ac.getBean(AdminMapper.class);
      Long id = 12L;
      String password = "000000";
      int rows = adminMapper.updatePasswordById(id, password);
      if (rows == 1) {
      System.out.println("修改密码成功");
      } else {
      System.out.println("修改密码失败,尝试访问的数据(id=" + id + ")不存在!");
      }
      ac.close();
      }
      
    5.  
posted @ 2022-06-01 19:09  约拿小叶  阅读(138)  评论(0编辑  收藏  举报