mybatis的日常使用-注解与xml和yml

71 阅读1分钟

写写mybatis中常见的增删改查

基于上一个user表作为增删改查的对象

使用注解开发

package com.example.demo.Mapper;

import com.example.demo.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    /*
     * 查找用户
     * */
    @Select("select * from test.user")
    public List<User> findAll();

    /*
    * 添加用户
    * */
    @Insert("INSERT INTO test.user(username, password, name, age) values(#{username},#{password},#{name},#{age})")
    public void insert(User user);

    /*
    * 修改用户*/
    @Update("update test.user set username=#{username},password=#{password},name=#{name},password=#{password} where id = #{id}")
    public void updateById(User user);

    /*
    * 删除用户*/
    @Delete("delete from test.user where id=#{id}")
    public void deleteById(Integer id);

}

使用xml

要注意以下几点

  1. XML映射文件和Mapper接口文件的名称一致,XML映射文件和Mapper接口放在相同包下
  2. XML映射文件的namespace属性与Mapper接口限定名一致
  3. XML映射文件中SQL语句的id和Mapper接口中的方法名一致,返回类型一致

image.png

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--此处的namespace对应的是接口的位置-->
<mapper namespace="com.example.demo.Mapper.UserMapper">
<!--    此处的id对应的是这个select方法的名字-->
<!--    此处的resultType对应的是查询所对应的类型-->
    <select id="findAll" resultType="com.example.demo.pojo.User">
        select * from user
    </select>
</mapper>

配置文件不使用properties而使用yml

yml比较清晰

  1. yml大小写比较敏感
  2. 数值前边要有空格,作为分隔符
  3. 缩进标识层级关系,缩进不使用Tab,私用空格
  4. 只需要左侧元素对齐
  5. #此符号标识注释
spring:
  application:
    name: demo
  datasource:
    url: jdbc:mysql://localhost:3306/test
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl