mybatis 一个基本增删改查的mapper示例

本示例基于SpringBoot:2.1.6.RELEASE

基本增删改查mapper示例



<mapper namespace="cn.lenchu.learn.springboot.learnspringbootmybatis.mapper.UserMapper">
    <insert id="saveUser" >
        insert into m_user (id, username, password, createTime) values (
        #{id}, #{username}, #{password}, #{createTime}
        )
    insert>

    <select id="selectUserById" resultType="UserEntity">
        select * from m_user where id = #{id}
    select>

    <select id="selectUserByUsername" resultType="UserEntity">
        select * from m_user where username = #{username}
    select>

    <update id="updateUser">
        update m_user
        <set>
            <if test="username != null">username = #{username},if>
            <if test="password != null">password = #{password}if>
        set>
        where id = #{id}
    update>

    <delete id="deleteUserById">
        delete from m_user
        where id = #{id}
    delete>

    <select id="selectUserWithRole" resultMap="UserWithRoles">
        select u.*,
               r.id r_id, r.name r_name
        from m_user u, m_role r, m_user_role ur
        where u.id = ur.uid and ur.rid = r.id and u.id = #{uid}
    select>

    <resultMap id="UserWithRoles" type="UserWithRolesEntity" autoMapping="true">
            <id column="id" property="id"/>



        <collection property="roles" ofType="RoleEntity">
            <id column="r_id" property="id" />
            <result column="r_name" property="name" />
        collection>
    resultMap>
mapper>

mapper接口示例

package cn.lenchu.learn.springboot.learnspringbootmybatis.mapper;

import cn.lenchu.learn.springboot.learnspringbootmybatis.entity.UserEntity;
import cn.lenchu.learn.springboot.learnspringbootmybatis.entity.UserWithRolesEntity;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserMapper {

    void saveUser(UserEntity user);

    Optional<UserEntity> selectUserById(String id);

    Optional<UserEntity> selectUserByUsername(String username);

    void updateUser(UserEntity user);

    void deleteUserById(String id);

    Optional<UserWithRolesEntity> selectUserWithRole(String uid);
}

application.yml中简单配置

mybatis:
  type-aliases-package: cn.lenchu.learn.springboot.learnspringbootmybatis.entity
  mapper-locations: classpath:mapper/*.xml

启动类上添加mapperScan注解

@MapperScan(basePackages = {"cn.lenchu.learn.springboot.learnspringbootmybatis.mapper"})

你可能感兴趣的:(Mybatis)