Mybatis(四):实战

准备工作

pom.xml

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${springboot-mybatis.version}</version>
        </dependency>
        
         <!--mysql连接-->
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <scope>runtime</scope>
         </dependency>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer"/>
        <typeAlias alias="Long" type="java.lang.Long"/>
        <typeAlias alias="Map" type="java.util.Map"/>
        <typeAlias alias="HashMap" type="java.util.HashMap"/>
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/>
        <typeAlias alias="ArrayList" type="java.util.ArrayList"/>
        <typeAlias alias="LinkedList" type="java.util.LinkedList"/>
    </typeAliases>
</configuration>
mybatis:
    config-location: classpath:mybatis/mybatis-config.xml
    mapper-locations: classpath:mybatis/mapper/*.xml
    type-aliases-package: love.ning.yangxuyue.domain

Mybatis使用

XML版

返回自增ID

// 方式一
// 元素设置 useGeneratedKeys 和 keyProperty 属性
// useGeneratedKeys="true" 表示给主键设置自增长
// 当数据写入到数据表时,其自增主键自动地填充到实体参数的 id 属性
<insert id="insert" 
    parameterType="User" 
    useGeneratedKeys="true" 
    keyProperty="id">
    INSERT INTO User(username, password) VALUES (#{username}, #{password});
</insert>

// 方式二
<insert id="insert" parameterType="User" >
    <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="productId">
       // MySQL语法
       SELECT LAST_INSERT_ID()
    </selectKey>
    INSERT INTO User(username, password) VALUES (#{username}, #{password});
</insert>

批量处理

collection:指定要遍历的集合:
list类型的参数会特殊处理封装在map中,map的key就叫list
item:将当前遍历出的元素赋值给指定的变量
separator:每个元素之间的分隔符
open:遍历出所有结果拼接一个开始的字符
close:遍历出所有结果拼接一个结束的字符
index:索引。
1、遍历list的时候是index就是索引,item就是当前值
2、遍历map的时候index表示的就是map的key,item就是map的值
{变量名}就能取出变量的值也就是当前遍历出的元素

插入

<insert id="insert" parameterType="List" >
  INSERT INTO tableName(id, name)
  VALUES 
    <foreach collection="list" item="item" index="index" separator=",">
        (#{item.id},#{item.name})
    </foreach>
</insert>

查询

<select id="getByIds" parameterType="List" resultType="User">
  SELECT * FROM tableName 
  WHERE id IN
    <foreach collection="list" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
</select>

更新

<update id="update" parameterType="List">
  <foreach collection="list" item="item" separator=";"  index="index">
        UPDATE tableName
        SET name = #{item.name}
            email = #{item.email}
         WHERE xxx
  <foreach>
</update>

注解版

增删改查

    // 查询
    @Select("SELECT * FROM user WHERE name = #{name}")
    User findByName(@Param("name") String name);

    // 返回结果的绑定
    @Select("SELECT * FROM users WHERE id = #{id}")
    @Results({
        @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
        @Result(property = "nickName", column = "nick_name")
    })
    UserEntity getOne(Long id);

    @Select("SELECT * FROM users")
    @Results({
        @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
        @Result(property = "nickName", column = "nick_name")
    })
    List<UserEntity> getAll();

    // 新增
    @Insert("INSERT INTO USER(NAME, AGE) VALUES(# {name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
    int insertByMap(Map<String, Object> map);

    @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
    int insertByUser(User user);

    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    // 修改
    @Update("UPDATE user SET age=#{age} WHERE name = #{name}")
    void update(User user);

    // 删除
    @Delete("DELETE FROM user WHERE id = #{id}")
    void delete(Long id);
原文地址:https://www.cnblogs.com/yang21/p/9826318.html