mybatis-@Mapper接口用法

mybatis支持的映射方式有基于xml的mapper.xml文件、基于java的使用Mapper接口class,简单学习一下mybatis使用接口来配置映射的方法。

接口方法注解主要是四个:@Insert、@Delete、@Update、@Select

具体代码

package com.example.springbootspringmvcdemo.mapper;

import com.example.springbootspringmvcdemo.entity.User;
import org.apache.ibatis.annotations.*;

@Mapper
public interface MapperDemo {
    /**
     * 插入记录,手动分配主键
     * @param user
     * @return
     */
    @Insert("INSERT INTO tb_user (id, username,password) values (#{id},#{username},#{password})")
    int addUser(User user);

    /**
     * 插入记录,数据库生成主键
     * useGeneratedKeys: 表示要使用自增主键
     * keyProperty: 用来指定主键字段名
     * @param user
     * @return
     */
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into tb_user (username,password) values (#{username},#{password})")
    int addUserGenerateKey(User user);

    /**
     * 删除记录
     * @param id
     * @return
     */
    @Delete("DELETE FROM tb_user WHERE id = #{id}")
    int delete(String id);

    /**
     * 修改记录
     * @param user
     * @return
     */
    @Update("UPDATE tb_user set username=#{username},password=#{password} where id =#{id}")
    int update(User user);

    @Select("SELECT * FROM tb_user WHERE id=#{id}")
    User loadByIdAutoAlias(String id);

    /**
     * 使用ResultMap
     * @param id
     * @return
     */
    @Results(
            id = "userMap", value= {
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "username", property = "username"),
            @Result(column = "password",property = "password")
    }
    )
    @Select("SELECT * FROM tb_user WHERE id=#{id}")
    User loadByIdAutoAlias2(String id);
}

单元测试

package com.example.springbootspringmvcdemo.mapper;

import com.alibaba.fastjson.JSON;
import com.example.springbootspringmvcdemo.entity.User;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.json.JsonbTester;

@SpringBootTest
public class TestMapperDemo {

    private Logger logger = LoggerFactory.getLogger(TestMapperDemo.class);

    @Autowired(required = false)
    MapperDemo mapperDemo;

    @Test
    public void addUser() {
        User user = new User();
        user.setId(6);
        user.setUsername("hahahah");
        user.setPassword("99999");
        mapperDemo.addUser(user);
    }

    @Test
    public void addUserGenerateKey() {
        User user = new User();
        user.setUsername("ewrewrwefsd");
        user.setPassword("ieruwe222222");
        mapperDemo.addUserGenerateKey(user);
    }

    @Test
    public void delete() {
        mapperDemo.delete("8");
    }

    @Test
    public void update() {
        User user = new User();
        user.setId(5);
        user.setUsername("22211122222222222");
        user.setPassword("333333333333333");
        mapperDemo.update(user);
    }

    @Test
    public void loadByIdAutoAlias() {
        User user = mapperDemo.loadByIdAutoAlias("41");
        if (user != null) {
            String string = JSON.toJSON(user).toString();
            logger.info(string);
        } else {
            logger.info("没有查询到数据!");
        }

    }

    @Test
    public void loadByIdAutoAlias2() {
        User user = mapperDemo.loadByIdAutoAlias2("4");
        if (user != null) {
            String string = JSON.toJSON(user).toString();
            logger.info(string);
        } else {
            logger.info("没有查询到数据!");
        }
    }
}

使用的依赖

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.49</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>

 

 

 

 

上一篇:Spring 与 Mybatis 中的 @Repository 与 @Mapper与@Mapperscan


下一篇:12.7日学习笔记