Mybatis基础+增删改查(代码示例)

2023-05-16

目录

Mybatis基础+增删改查(代码示例)

首先什么是MyBatis?

MyBatis中文文档(学习参考资料):

MyBatis 基础框架搭建源码:

MyBatis 基础框架详解:

项目基本结构:

项目依赖:

数据库配置文件(dp.properties):

日志配置文件(log4j.properties):

Mybatis核心配置文件:

(POJO)实体类Blog:

(POJO)实体类Student:

(POJO)实体类Teacher:

(POJO)实体类User:

Mybatis核心配置文件解析工具:

UUID生成器(全局唯一ID生成器):

UserMapper.java  接口(增删改查CRUD):

UserMapper.xml对应接口的SQL信息:

StudentMapper.java  接口:

StudentMapper.xml对应接口的SQL信息:

TeacherMapper.java  接口:

TeacherMapper.xml对应接口的SQL信息:

BlogMapper.java  接口:

BlogMapper.xml对应接口的SQL信息:

StudentAnnotationMapper.java  接口:

UserMapperTest 测试代码:(此处采用  Junit  进行查询,没有用到Spring注解的单测)

UserMapperTest.java

StudentMapperTest 测试代码:(此处采用  Junit  进行查询,没有用到Spring注解的单测)

StudentMapperTest.java

StudentAnnotationMapperTest 测试代码:(此处采用  Junit  进行查询,没有用到Spring注解的单测)

StudentAnnotationMapperTest.java

TeacherMapperTest 测试代码:(此处采用  Junit  进行查询,没有用到Spring注解的单测)

TeacherMapperTest.java

BlogMapperTest测试代码:(此处采用  Junit  进行查询,没有用到Spring注解的单测)

BlogMapperTest.java


Mybatis基础+增删改查(代码示例)

首先什么是MyBatis?

MyBatis 是一流的持久性框架,支持自定义 SQL、存储过程和高级映射。MyBatis 消除了几乎所有的 JDBC 代码和手动设置参数和检索结果。MyBatis 可以使用简单的 XML 或 Annotations 进行配置和映射原语、映射接口和 Java POJO(普通旧 Java 对象)到数据库记录。

MyBatis中文文档(学习参考资料):

mybatis – MyBatis 3 | Introduction

MyBatis 基础框架搭建源码:

https://gitee.com/aaron1996/mybatis

MyBatis 基础框架详解:

项目基本结构:

项目依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>RocketDemo</artifactId>
        <groupId>org.cainiao</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>demo-mybatisJDBC</artifactId>

    <dependencies>
        <!--    springboot项目启动器    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!--    spring项目测试依赖    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
            <scope>provided</scope>
        </dependency>
        <!--    mybatis    -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <!--    junit    -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!--    mysql    -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <!-- 可选: log4j日志设置 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

    <!--  防止资源过滤问题  -->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

注意:父pom.xml文件中还有:

数据库配置文件(dp.properties):

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=root123456

日志配置文件(log4j.properties):

# log配置文件如下可以在任意项目中使用,属于可以写死的代码

# 将等级为DEBUG的日志信息输出到console和file这两个目的地
log4j.rootLogger=DEBUG,console,file

# 控制台输出的相关设置
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

# 文件输出的相关设置
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/log.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-mm-dd}][%c]%m%n

# 日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

Mybatis核心配置文件:

<?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配置文件中,对每个标签的位置有严格的规定  -->
<configuration>

    <!--  引入外部配置文件  -->
    <properties resource="dp.properties" />

    <!--  别名:便于在XXXMapper.xml文件中不用com.cainiao.xxxx
      直接使用xxxx-->
    <typeAliases>
        <package name="com.cainiao.pojo"/>
    </typeAliases>

    <!--  此处可以配置多套环境,默认使用development环境  -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--  配置多个映射器  -->
    <mappers>
<!--        <mapper resource="com/cainiao/mapper/UserMapper.xml"/>-->
        <mapper resource="mapper/UserMapper.xml"/>
        <mapper resource="mapper/StudentMapper.xml"/>
        <mapper resource="mapper/TeacherMapper.xml"/>
        <mapper class="com.cainiao.annotationMapper.StudentAnnotationMapper"/>
        <mapper resource="mapper/BlogMapper.xml" />
    </mappers>
</configuration>

(POJO)实体类Blog:

package com.cainiao.pojo;

import java.util.Date;

public class Blog {

    private String id;
    private String title;
    private String author;
    private Date createTime;
    private String views;

    public Blog() {
    }

    public Blog(String id, String title, String author, Date createTime, String views) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.createTime = createTime;
        this.views = views;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getViews() {
        return views;
    }

    public void setViews(String views) {
        this.views = views;
    }

    @Override
    public String toString() {
        return "Blog{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", createTime=" + createTime +
                ", views='" + views + '\'' +
                '}';
    }
}

(POJO)实体类Student:

package com.cainiao.pojo;

public class Student {

    private Long sid;
    private String sname;
    private Byte sage;
    private String smaster;
    private Teacher teacher;

    public Student() {
    }

    public Student(Long sid, String sname, Byte sage, String smaster, Teacher teacher) {
        this.sid = sid;
        this.sname = sname;
        this.sage = sage;
        this.smaster = smaster;
        this.teacher = teacher;
    }

    public Long getSid() {
        return sid;
    }

    public void setSid(Long sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Byte getSage() {
        return sage;
    }

    public void setSage(Byte sage) {
        this.sage = sage;
    }

    public String getSmaster() {
        return smaster;
    }

    public void setSmaster(String smaster) {
        this.smaster = smaster;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", sage=" + sage +
                ", smaster='" + smaster + '\'' +
                ", teacher=" + teacher +
                '}';
    }
}

(POJO)实体类Teacher:

package com.cainiao.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.List;

public class Teacher {

    private String master;
    private Integer tage;
    private String tmajor;

    private List<Student> studentList;

    public Teacher() {
    }

    public Teacher(String master, Integer tage, String tmajor, List<Student> studentList) {
        this.master = master;
        this.tage = tage;
        this.tmajor = tmajor;
        this.studentList = studentList;
    }

    public String getMaster() {
        return master;
    }

    public void setMaster(String master) {
        this.master = master;
    }

    public Integer getTage() {
        return tage;
    }

    public void setTage(Integer tage) {
        this.tage = tage;
    }

    public String getTmajor() {
        return tmajor;
    }

    public void setTmajor(String tmajor) {
        this.tmajor = tmajor;
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "master='" + master + '\'' +
                ", tage=" + tage +
                ", tmajor='" + tmajor + '\'' +
                ", studentList=" + studentList +
                '}';
    }
}

(POJO)实体类User:

package com.cainiao.pojo;

public class User {

    private Integer id;
    private String userName;
    private String userAge;
    private String userAddress;

    public User() {
    }

    public User(Integer id, String userName, String userAge, String userAddress) {
        this.id = id;
        this.userName = userName;
        this.userAge = userAge;
        this.userAddress = userAddress;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

    public String getUserAddress() {
        return userAddress;
    }

    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userAge='" + userAge + '\'' +
                ", userAddress='" + userAddress + '\'' +
                '}';
    }
}

Mybatis核心配置文件解析工具:

package com.cainiao.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        // 这里设置autoCommit=true,可自动提交,不同在提交中,手动sqlSession.commit;
        return sqlSessionFactory.openSession(true);
    }
}

UUID生成器(全局唯一ID生成器):

package com.cainiao.utils;

import org.junit.Test;

import java.util.UUID;

public class IdUtils {

    public static String getId(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    @Test
    public void test(){
        System.out.println(getId());
    }
}

UserMapper.java  接口(增删改查CRUD):

注意:凡是基本类型前面都需要加上@Param()方法,开发规范;引用类型可不用@Param()方法;

内容:基于 User 实现了  

(1)查询所有用户;

(2)根据用户Id进行查询;

(3)根据用户 name 进行模糊查询(此处用 concat() 进行字符串拼接,防止SQL注入);

(4)添加用户;

(5)企业级:如果实体类属性过多,可以考虑使用map进行数据库插入操作@param map

(6)根据用户id 删除用户;

(7)根据用户id 修改用户信息;

package com.cainiao.mapper;

import com.cainiao.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public interface UserMapper {

    /**
     * 查询所有用户                (查)
     * @return
     */
    List<User> getUserList();

    /**
     * 根据用户Id进行查询           (查)
     * @param id
     * @return
     */
    User selectUserById(@Param("id") int id);


    /**
     * 根据用户 name 进行模糊查询    (查)
     * @param name
     * @return
     */
    List<User> selectUserByLike(@Param("name") String name);


    /**
     * 添加用户                    (增)
     * @param user
     */
    void addUser(User user);

    /**
     * 企业级:如果实体类属性过多,   (增)
     * 可以考虑使用map进行
     * 数据库插入操作
     * @param map
     */
    void addUserByMap(Map<String, Object> map);


    /**
     * 根据用户id 删除用户          (删)
     * @param id
     */
    void deleteUser(@Param("id") int id);


    /**
     * 根据用户id 修改用户信息       (改)
     * @param user
     */
    void updateUser(User user);


}

UserMapper.xml对应接口的SQL信息:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cainiao.mapper.UserMapper">
    <select id="getUserList" resultType="com.cainiao.pojo.User">
        select * from user;
    </select>

    <select id="selectUserById" parameterType="int" resultType="user">
        select * from user where id=#{id};
    </select>

    <!--  使用concat进行模糊查询可以有效防止sql注入  -->
    <select id="selectUserByLike" parameterType="String" resultType="user">
        select *
        from user
        where userName like concat('%', #{name}, '%');
    </select>

    <!--  其中插入的User信息中属性名称必须一一对应  -->
    <insert id="addUser" parameterType="user" useGeneratedKeys="true" keyProperty="id">
        insert into user values(#{id},#{userName},#{userAge},#{userAddress})
    </insert>

    <!--  企业级:如果实体类属性过多,可以考虑使用map进行数据库插入操作,后跟map的键值  -->
    <insert id="addUserByMap" parameterType="map" useGeneratedKeys="true" keyProperty="id">
        insert into user(id, userName, userAddress) values(#{defineId},#{defineUserName},#{defineUserAddress})
    </insert>

    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id};
    </delete>

    <update id="updateUser" parameterType="user">
        update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id};
    </update>
</mapper>

StudentMapper.java  接口:

注意:凡是基本类型前面都需要加上@Param()方法,开发规范;引用类型可不用@Param()方法;

内容:基于 Student实现了  

(1)基于简单   <resultMap> 标签   进行查询数据信息;

(2)分页查询;(实质上为 SQL语句 ----  limit)

package com.cainiao.mapper;

import com.cainiao.pojo.Student;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface StudentMapper {

    /**
     * 此处采用 resultMap 来进行查询
     * @return
     */
    List<Student> selectAllStudent();

    /**
     * 分页
     * @param map
     * @return
     */
    List<Student> selectStudentByPage(Map<String,Integer> map);

}

StudentMapper.xml对应接口的SQL信息:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cainiao.mapper.StudentMapper">

    <!--  其中column为数据库中的字段
          property为实体内的属性字段-->
    <resultMap id="studentMap" type="student">
        <id column="sid" property="sid" />
        <result column="sname" property="sname" />
        <result column="sage" property="sage" />
        <result column="smaster" property="smaster" />
    </resultMap>

    <!--  采用 resultMap 来进行查询  -->
    <select id="selectAllStudent" resultMap="studentMap">
        select *
        from student
    </select>

    <!--  分页查询:实质为SQL limit 的编写  -->
    <select id="selectStudentByPage" resultMap="studentMap">
        select *
        from student
        limit #{startPage}, #{pageSize};
    </select>

</mapper>

TeacherMapper.java  接口:

注意:凡是基本类型前面都需要加上@Param()方法,开发规范;引用类型可不用@Param()方法;

内容:基于 Teacher  实现了  

(1)“多对一” 联表查询;

(2)“一对多” 联表查询;

package com.cainiao.mapper;

import com.cainiao.pojo.Student;
import com.cainiao.pojo.Teacher;

import java.util.List;

public interface TeacherMapper {

    /**
     * 通过 联表 查询学生和老师所有信息    (多对一)
     * @return
     */
    List<Student> getStuTeaInfo();


    /**
     * 通过 联表 查询老师和学生所有信息    (一对多)
     * @return
     */
    List<Teacher> getTeaStuInfo();

}

TeacherMapper.xml对应接口的SQL信息:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cainiao.mapper.TeacherMapper">

    <!--  此处采用 “多对一” 联表查询 “学生-老师” 关联信息  -->
    <resultMap id="stuTeaMap" type="student">
        <result property="sid" column="sid" />
        <result property="sname" column="sname" />
        <result property="sage" column="sage" />
        <!--    此处进行联表操作    -->
        <association property="teacher" javaType="Teacher">
            <result property="tmajor" column="tmajor" />
        </association>
    </resultMap>
    <select id="getStuTeaInfo" resultMap="stuTeaMap">
        select s.sid sid, s.sage sage, s.sname sname, t.tmajor tmajor
        from student s, teacher t
        where s.smaster = t.`master`;
    </select>

    
    <!--  此处采用 “一对多” 联表查询 “老师 - 学生” 关联信息  -->
    <resultMap id="teaStuMap" type="Teacher">
        <result property="master" column="tmaster" />
        <result property="tmajor" column="tmajor" />
        <collection property="studentList" ofType="Student">
            <result property="sid" column="sid" />
            <result property="sname" column="sname" />
            <result property="sage" column="sage" />
        </collection>
    </resultMap>
    <select id="getTeaStuInfo" resultMap="teaStuMap">
        select t.`master` tmaster, t.tmajor tmajor, s.sid sid, s.sname sname, s.sage sage
        from student s, teacher t
        where s.smaster = t.`master`
    </select>

</mapper>

BlogMapper.java  接口:

注意:凡是基本类型前面都需要加上@Param()方法,开发规范;引用类型可不用@Param()方法;

内容:基于 Blog  实现了  

(1)插入 Blog 数据;

(2)采用 动态SQL <if> 进行查询;

(3)使用 动态SQL <choose> 进行对属性有选择地执行 SQL语句;

(4) 采用 动态SQL   <set>   进行更新 blog表;

(5)使用  <foreach>   进行 动态SQL 查询;(不常用,最好写成面向对象代码);

package com.cainiao.mapper;

import com.cainiao.pojo.Blog;

import java.util.List;
import java.util.Map;

public interface BlogMapper {

    /**
     * 插入 Blog 数据
     * @param blog
     */
    void addBlog(Blog blog);

    /**
     * 采用 动态SQL 进行查询
     * @return
     */
    List<Blog> selectBlogIF(Map<String, Object> map);

    /**
     * 使用 动态SQL <choose> 进行对属性有选择地执行 SQL语句
     * @param map
     * @return
     */
    List<Blog> selectBlogCHOOSE(Map<String, Object> map);


    /**
     * 采用 动态SQL 进行更新 blog表
     * @param blog
     */
    void updateBlog(Blog blog);


    /**
     * 使用 foreach 进行 动态SQL 查询
     * @param map
     * @return
     */
    List<Blog> selectBlogFOREACH(Map<String, Object> map);

}

BlogMapper.xml对应接口的SQL信息:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cainiao.mapper.BlogMapper">

    <!--  插入 Blog 数据  -->
    <insert id="addBlog" parameterType="blog">
        insert into blog (id, title, author, create_time, views)
        values(#{id}, #{title}, #{author}, #{createTime}, #{views})
    </insert>

    <!--  采用 动态SQL <if> <where> 进行查询
        // 有参数:按照参数进行查询
        // 无参数:查询所有数据
        注意(重点):(1)使用 <where>标签 可以对后面的 <if> 进行检查;
                    (2)有条件就按照条件进行查询;
                    (3)没有条件就全部查询;
     -->
    <select id="selectBlogIF" resultType="blog" parameterType="map">
        select *
        from blog
        <where>
            <if test="title != null">
                title=#{title}
            </if>
            <if test="author != null">
                and author=#{author}
            </if>
        </where>
    </select>

    <!--  动态SQL <choose>...<when>... 可以对属性进行筛选 执行SQL语句
            <choose>标签 对于<when> 从上之下匹配
            匹配成功则停止匹配   只选 <choose> 中的一个 <when> 执行-->
    <select id="selectBlogCHOOSE" parameterType="map" resultType="blog">
        select *
        from blog
        <where>
            <choose>
                <when test="title != null">
                    title=#{title}
                </when>
                <when test="author != null">
                    and author=#{author}
                </when>
                <otherwise>
                    and views=#{views}
                </otherwise>
            </choose>
        </where>
    </select>

    <!--  set 元素会动态地在行首插入 SET 关键字,
            注意:并会删掉额外的逗号
            (这些逗号是在使用条件语句给列赋值时引入的)  -->
    <update id="updateBlog" parameterType="blog">
        update blog
        <set>
            <if test="title != null">title=#{title},</if>
            <if test="author != null">author=#{author},</if>
            <if test="views != null">views=#{views}</if>
        </set>
        <where>
            id=#{id}
        </where>
    </update>

    <!--  采用 动态SQL foreach 进行查询  -->
    <select id="selectBlogFOREACH" parameterType="map" resultType="blog">
        select *
        from blog
        <where>
            <foreach collection="authors" item="author" open="(" close=")" separator="or">
                author = #{author}
            </foreach>
        </where>
    </select>

</mapper>

StudentAnnotationMapper.java  接口:

注意:此处没有采用常规的  XXX.xml  文件进行数据库数据访问,

        采用  注解  的方式进行数据库查询@Select;

        简单查询  可以使用注解进行查询;复杂数据库查询操作  还是需要采用xml文件进行编写查询;

package com.cainiao.annotationMapper;

import com.cainiao.pojo.Student;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface StudentAnnotationMapper {

    /**
     * 使用注解进行 =简单= 的查询操作
     * 注意:使用注解需要保证 实体类属性 一一对应 数据库字段
     * @param sid
     * @return
     */
    @Select("select * from student where sid=#{sid}")
    Student selectStudentByIdAno(@Param("sid") long sid);

}

UserMapperTest 测试代码:(此处采用  Junit  进行查询,没有用到Spring注解的单测)

UserMapperTest.java

package com.cainiao.mapper;

import com.cainiao.pojo.User;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

public class UserMapperTest {

    @Test
    void getUserListTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUserList();

        for (User user : userList) {
            System.out.println(user.getId() + "\t" + user.getUserName() + "\t" +
                    user.getUserAge() + "\t" + user.getUserAddress());
        }

        sqlSession.close();
    }

    @Test
    void selectUserByIdTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectUserById(1);

        System.out.println(user.getId() + "\t" + user.getUserName() + "\t" +
                user.getUserAge() + "\t" + user.getUserAddress());

        sqlSession.close();
    }


    @Test
    void addUserTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = new User();
        user.setUserName("Aaron1");
        user.setUserAge("20");
        user.setUserAddress("Chongqing");

        mapper.addUser(user);

        // 注意:增删改都需要事务提交
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    void deleteUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(8);
        System.out.println("成功删除用户");

        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    void updateUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = new User();
        user.setId(9);
        user.setUserName("Aaron2");
        user.setUserAge("50");
        user.setUserAddress("Shiniapan");

        mapper.updateUser(user);

        // 增删改:都必须进行事务提交
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    void addUserByMap() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> map = new HashMap<>();
        map.put("defineUserName", "User1");
        map.put("defineUserAddress", "Wenquancheng");

        mapper.addUserByMap(map);

        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    void selectUserByLike() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectUserByLike("Aaron");

        for (User user : userList) {
            System.out.println(user.getId() + "\t" + user.getUserName() + "\t" +
                    user.getUserAge() + "\t" + user.getUserAddress());
        }

        sqlSession.close();
    }
}

StudentMapperTest 测试代码:(此处采用  Junit  进行查询,没有用到Spring注解的单测)

StudentMapperTest.java

package com.cainiao.mapper;

import com.cainiao.pojo.Student;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

class StudentMapperTest {

    @Test
    void selectAllStudentTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.selectAllStudent();

        for (Student student : students) {
            System.out.println(student.getSid() + "\t"
                    + student.getSname() + "\t" + student.getSage()
                    + "\t" + student.getSmaster() + "\t" + student.getTeacher());
        }

        sqlSession.close();
    }

    @Test
    void testLogger(){
        Logger logger = Logger.getLogger(StudentMapperTest.class);
        logger.info("成功进入info级别");
        logger.debug("成功进入debug级别");
        logger.error("成功进入error级别");
    }

    /**
     * 测试分页
     */
    @Test
    void selectStudentByPage() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        Map<String,Integer> map = new HashMap<>();
        map.put("startPage", 0);
        map.put("pageSize", 2);

        List<Student> students = mapper.selectStudentByPage(map);

        for (Student student : students) {
            System.out.println(student.getSid() + "\t"
                    + student.getSname() + "\t" + student.getSage()
                    + "\t" + student.getSmaster());
        }

        sqlSession.close();
    }
}

StudentAnnotationMapperTest 测试代码:(此处采用  Junit  进行查询,没有用到Spring注解的单测)

StudentAnnotationMapperTest.java

package com.cainiao.mapper;

import com.cainiao.annotationMapper.StudentAnnotationMapper;
import com.cainiao.pojo.Student;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

class StudentAnnotationMapperTest {

    @Test
    void selectStudentByIdTest() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentAnnotationMapper mapper = sqlSession.getMapper(StudentAnnotationMapper.class);
        if(mapper.selectStudentByIdAno(1) == null){
            System.out.println("结果为空");
        }else{
            Student student = mapper.selectStudentByIdAno(1);
            System.out.println(student.getSid() + "\t"
                    + student.getSname() + "\t" + student.getSage()
                    + "\t" + student.getSmaster());

            sqlSession.close();
        }
    }
}

TeacherMapperTest 测试代码:(此处采用  Junit  进行查询,没有用到Spring注解的单测)

TeacherMapperTest.java

package com.cainiao.mapper;

import com.cainiao.pojo.Student;
import com.cainiao.pojo.Teacher;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

class TeacherMapperTest {

    @Test
    void getStuTeaInfoTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        List<Student> stuTeaInfo =
                mapper.getStuTeaInfo();
        for (Student student : stuTeaInfo) {
            System.out.println(String.valueOf(student));
        }
    }

    @Test
    void getTeaStuInfoTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        List<Teacher> teaStuInfo = mapper.getTeaStuInfo();

        for (Teacher teacher : teaStuInfo) {
            System.out.println(teacher);
        }

        sqlSession.close();
    }
}

BlogMapperTest测试代码:(此处采用  Junit  进行查询,没有用到Spring注解的单测)

BlogMapperTest.java

package com.cainiao.mapper;

import com.cainiao.pojo.Blog;
import com.cainiao.utils.IdUtils;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class BlogMapperTest {

    @Test
    void addBlogTest() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        mapper.addBlog(new Blog(IdUtils.getId(), "aaaaaaaaaaaaa", "Mary", new Date(), "100"));
        mapper.addBlog(new Blog(IdUtils.getId(), "bbbbbbbbbbbbb", "Tom", new Date(), "200"));
        mapper.addBlog(new Blog(IdUtils.getId(), "ccccccccccccc", "Tony", new Date(), "58"));
        mapper.addBlog(new Blog(IdUtils.getId(), "ddddddddddddd", "Aaron", new Date(), "355"));

        sqlSession.close();
    }

    @Test
    void selectBlogIFTest() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        // 有参数:按照参数进行查询
        // 无参数:查询所有数据
        Map<String, Object> map = new HashMap<>();
//        map.put("title", "bbbbbbbbbbbbb");
        List<Blog> blogs = mapper.selectBlogIF(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

    }

    @Test
    void selectBlogCHOOSE() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Map<String, Object> map = new HashMap<>();
//        map.put("title", "bbbbbbbbbbbbb");
        map.put("author", "Mary");
        map.put("views", "58");

        List<Blog> blogs = mapper.selectBlogCHOOSE(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();

    }

    @Test
    void updateBlog() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Blog blog = new Blog();
        blog.setTitle("ddddddddddddd1");
        blog.setAuthor("Aaron1");
        blog.setId("45a5fa1f5e4f41599b72ae1950257e6c");
        mapper.updateBlog(blog);

        sqlSession.close();

    }

    @Test
    void selectBlogFOREACH() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Map<String, Object> map = new HashMap<>();
        ArrayList<String> authors = new ArrayList<String>();
        authors.add("Tony");

        map.put("authors", authors);
        List<Blog> blogs = mapper.selectBlogFOREACH(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mybatis基础+增删改查(代码示例) 的相关文章

随机推荐

  • config/app.php在哪,找到config

    windows系统下git配置用户名和邮箱 找到你的 git的目录下 xff0c 右键空白位置找到 Git Bash 呼出命令行 xff1a 输入 xff1a git config user name 34 name 34 设置用户名 gi
  • mac 系统安装服务器配置,服务器配置安装 mac os

    服务器配置安装 mac os 内容精选 换一换 本节操作以使用 Microsoft Remote Desktop for Mac 工具远程连接 Windows Server 2012 R2 数据中心版 64位 操作系统云服务器为例 xff0
  • python 波浪号用法_「波浪号」matlab中波浪号~的作用和用法 - 金橙教程网

    波浪号 在Matlab中 xff0c 波浪号 也就是键盘上数字键1 旁边的那个 主要有两个用法 xff1a 第一是代表与或非中的非 xff0c 如在以下代码中 xff1a if flag end只有在flag为0或false时 xff0c
  • 服务器只显示一个登陆用户,远程服务器只允许1个用户登入设置

    远程服务器只允许1个用户登入设置 内容精选 换一换 已成功添加Guardian 如果Guardian处于在线状态 xff0c 只允许修改Guardian名称 如果Guardian处于连接超时状态 xff0c 可以输入登录远程服务器的用户名和
  • 关于mysql联合索引的一道简单笔试题与思考

    最近做了一道关于mysql联合索引的题 具体的题目个人的收获参考的链接索引的那些事 具体的题目 答案 xff1a 1 四个字段均使用了该索引 2 c1 xff0c c2字段使用了该索引 3 c1字段使用该索引 4 c1字段使用该索引 5 c
  • 目前spring阶段一些有用得文章

    自己写给自己看当作笔记 SpringBoot自动配置原理是什么 https www cnblogs com chenweichu p 12663798 html 1 在 64 SpringBootApplication中有一个注解 64 E
  • 面试常问的事情与题目

    随便给份工作我吧 提示 xff1a 面试多总结一下经验 xff0c 抓重点 xff0c 而不是什么都想准备好 其实自己就是一个菜狗 xff0c 备考了半年 xff0c 什么鸡儿都忘记了 xff0c 从零开始 文章目录 前言一 基本流程大概二
  • 我的常用基础指令

    docker相关 run it ubuntu span class token function bash span i 是以交互式的方式启动 t 是以终端的形式启动 p 映射端口号 xff1a 原始端口号 指定端口号启动 例 xff1a
  • vue jqurey 等前端常用

    vue components 注册组件 如 xff1a span class token keyword import span SelectDict span class token keyword from span span clas
  • 《Linux 内核完全注释》阅读笔记

    在阅读源代码之前 xff0c 有必要对Linux内核的体系结构 源代码的目录结构有个宏观地了解 xff0c Linux内核完全注释 非常详细地介绍了这方面的内容 xff0c 所以 这里仅仅进行概述性的讨论 xff0c 以便让所有的笔记构成一
  • 关于Java-stream的一下日常使用

    惰式执行 对 stream的操作并不会立即执行 如果用户真正需要的时候才会执行 span class token class name Stream span span class token punctuation span span c
  • 怎么获取别人服务器信息失败,获取服务器信息失败

    获取服务器信息失败 内容精选 换一换 1 若希望以主席身份入会 xff0c enter code必须传入主席密码 若希望以来宾身份入会 xff0c 当会议要求来宾密码时 xff0c enter code必须传入来宾密码 xff0c 会议不要
  • 我的世界服务器合成表修改,【组件教程】行为包03:修改合成表

    大家好我是那个谁 xff0c 今天为大家带来组件系列教程的第三课 xff0c 在上一课中我们对于掉落物进行了详细的讲解 xff0c 这一课中我们要把目光看向我的世界另一重要玩法组成部分 xff1a 合成 打开原版行为包中recipes文件夹
  • liunx 全盘查找_linux查找文件命令find怎么用

    linux查找文件命令find怎么用 Linux 文件搜索命令find的操作使用方法如下 xff1a 1 全盘搜索 xff0c 也可以指定目录搜索 find 搜索目录 name 目标名字 xff0c find name file 2 这样搜
  • 程序员的成长之路:回顾初心,质疑自我

    经过3 4年的成长期 xff0c 你说日常写代码无压力 xff0c 代码质量也可以 xff0c 完成日常工作后 xff0c 就不知道做什么 xff1f 如果现在的你正好是这么一种状态 xff0c 想提升却不知道往哪走 xff1f 那你一定进
  • CentOS 7中安装Oracle JDK

    1 前往Oracle官网http www oracle com technetwork java javase downloads index html下载JDK xff0c 这里我们选择rpm包 xff08 注意 xff1a 下载前须接受
  • 给android程序添加页面,向 Android 应用中添加闪屏页和启动页

    向 Android 应用中添加闪屏页和启动页 开启 Flutter 的体验需要短暂地等待 Dart 的初始化 一个完整的 Flutter 应用还额外需要 Android 应用程序标准的初始化时间 Flutter 支持在 Android 应用
  • ArchLinux必备命令记录(manjaro)

    1 添加新账户 useradd username新建账户 useradd d home xxx m xxx创建用户 xff0c 并同时生成用户目录 xff0c 不然账户无法正常启用 passwd username修改密码 userdel f
  • js使用lottie读取json文件并修改文件参数后渲染

    js使用lottie读取json文件并修改文件参数后渲染 1 效果图 说明 xff1a 车辆模型是通过json文件渲染的 2 代码 2 1 引入lottie js xff08 如果没有 xff0c 网上资源很多 xff0c 请自行下载 xf
  • Mybatis基础+增删改查(代码示例)

    目录 Mybatis基础 43 增删改查 xff08 代码示例 xff09 首先什么是MyBatis xff1f MyBatis中文文档 xff08 学习参考资料 xff09 xff1a MyBatis 基础框架搭建源码 xff1a MyB