一、关于Mybatis

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

二、简单使用

1、添加依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

2、配置

修改application.yml文件,配置数据源以及mapper.xml位置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: 123456
mybatis:
  type-aliases-package: xyz.lazyrabbit.entity
  mapper-locations: classpath:mapper/*.xml

在启动类加入MapperScan注解,配置mapper.java文件位置

@SpringBootApplication
@MapperScan("xyz.lazyrabbit.mapper")
public class MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }

}

3、使用注解方式

  • 实体类
@Data
public class AccountInfo {
    private Integer id;
    private String username;
    private String email;
    private String password;
    private String memo;
}
  • mapper.java
@Repository
public interface AccountInfoMapper {


    @Options(useGeneratedKeys = true, keyProperty = "id")
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class)
    @Insert("insert into t_account_info(username,email,password,memo) values (#{username},#{email},#{password},#{memo})")
    void insert(AccountInfo accountInfo);

    @Select("select username,email,password,memo from t_account_info where id = #{id}")
    AccountInfo findById(Integer id);

    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "u"),
            @Result(property = "email", column = "e"),
            @Result(property = "password", column = "p"),
            @Result(property = "memo", column = "m")
    })
    @Select("select id id,username u ,email e ,password p ,memo m from t_account_info where username like concat('%',#{name},'%')")
    List<AccountInfo> findByName(String name);

    @Select("select * from t_account_info")
    List<AccountInfo> findAll();

    @Update("update t_account_info set username=#{username},email=#{email},password=#{password},memo=#{memo} where id=#{id}")
    Integer updateById(AccountInfo accountInfo);

    @Delete("delete from t_account_info where id=#{id}")
    Integer deleteById(Integer id);
}

4、使用xml方式

  • 实体类
@Data
public class AccountInfoType {

    private Integer id;
    private String accountType;
    private String memo;
}
  • AccountInfoTypeMapper.java
@Repository
public interface AccountInfoTypeMapper {

    List<AccountInfoType> findAll();

    Integer insert(AccountInfoType accountInfoType);

    Integer updateById(AccountInfoType accountInfoType);

    Integer deleteById(Integer id);
}
  • AccountInfoTypeMapper.xml
<mapper namespace="xyz.lazyrabbit.mapper.AccountInfoTypeMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="xyz.lazyrabbit.entity.AccountInfoType">
        <id column="id" property="id"/>
        <result column="account_type" property="accountType"/>
        <result column="memo" property="memo"/>
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, account_type, memo
    </sql>
    <select id="findAll" resultType="xyz.lazyrabbit.entity.AccountInfoType">
        select <include refid="Base_Column_List"/> from t_account_info_type;
    </select>
    <insert id="insert" parameterType="xyz.lazyrabbit.entity.AccountInfoType">
        insert into t_account_info_type (account_type, memo) values (#{accountType},#{memo});
    </insert>
    <update id="updateById" parameterType="xyz.lazyrabbit.entity.AccountInfoType">
        update t_account_info_type set account_type=#{accountType},memo=#{memo} where id=#{id}
    </update>
    <delete id="deleteById">
        delete from t_account_info_type where id=#{id}
    </delete>
</mapper>

5、测试

@SpringBootTest
@Slf4j
class MybatisApplicationTests {

    @Autowired
    AccountInfoMapper accountInfoMapper;
    @Autowired
    AccountInfoTypeMapper accountInfoTypeMapper;
    @Test
    void testAnnotation() {

        log.info("插入2条数据到数据库");
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setUsername("巴黎圣日尔曼");
        accountInfo.setEmail("admin@lazyrabbit.xyz");
        accountInfo.setPassword("123456");
        accountInfo.setMemo("手机");
        accountInfoMapper.insert(accountInfo);
        AccountInfo accountInfo2 = new AccountInfo();
        accountInfo2.setUsername("拜仁慕尼黑");
        accountInfo2.setEmail("admin@lazyrabbit.xyz");
        accountInfo2.setPassword("123456");
        accountInfo2.setMemo("手机");
        accountInfoMapper.insert(accountInfo2);


        log.info("当前数据库一共有数据:{}条", accountInfoMapper.findAll().size());

        Integer id = accountInfo.getId();
        AccountInfo findById = accountInfoMapper.findById(id);
        log.info("根据ID{}查询数据:{}", id, findById);
        AccountInfo findByName = accountInfoMapper.findByName("拜仁慕尼黑").get(0);
        log.info("根据Name查询数据:{}", accountInfoMapper.findByName("拜仁慕尼黑"));
        findByName.setMemo("今天赌五毛辣条拜仁大胜!!!");
        accountInfoMapper.updateById(findByName);
        log.info("更新 {} 的备注", findByName.getUsername());
        accountInfoMapper.deleteById(findByName.getId());
        log.info("删除数据: {} ", findByName.getUsername());
        log.info("当前数据库一共有数据:{}条", accountInfoMapper.findAll().size());
    }

    @Test
    void testXml() {
        AccountInfoType accountInfoType = new AccountInfoType();
        accountInfoType.setAccountType("视频软件");
        log.info("录入一条数据");
        accountInfoTypeMapper.insert(accountInfoType);
        log.info("查询所有数据:{}", accountInfoTypeMapper.findAll());

    }

}

参考

https://mybatis.org/mybatis-3/zh/index.html

https://github.com/mybatis/spring-boot-starter