• mybatis小示例


    一般使用mybatis的环境,大多都是别人已经配置好的。直接用就好了,如何自己搭建呢?其实很简单。看官方的文档就可以解决了。主要为了学习mybatis最基础的配置。我文章中的方法不基于spring,一般很少会在真实项目中直接使用。我把我的搭建过程记录下来给有用的人吧。

    什么是 MyBatis?

    MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

    官方文档地址:
    https://mybatis.org/mybatis-3/zh/index.html

    强烈建议自行查看官方文档来操作。

    没有spring如何使用mybatis

    现在我身边基本大部分项目都在使用spring技术了,那么如果没有spring呢?如何用mybatis?

    建表

    mybatis怎么能少的了对表进行操作呢?就以下面的表为例吧!数据库就用mysql吧

    表结构

    create table qa_category
    (
        category_id bigint auto_increment comment '分类ID'
            primary key,
        title       varchar(200)           not null comment '标题',
        sort        int(5)                 null comment '排序',
        create_by   varchar(64) default '' null comment '创建者',
        create_time datetime               null comment '创建时间',
        update_by   varchar(64) default '' null comment '更新者',
        update_time datetime               null comment '更新时间'
    )
        comment '提问分类';
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    测试数据

    INSERT INTO qa_category (title, sort, create_by, create_time, update_by, update_time) VALUES ('Java', 1, 'itkey', '2022-05-09 17:18:50', '', '2022-05-09 17:27:35');
    INSERT INTO qa_category (title, sort, create_by, create_time, update_by, update_time) VALUES ('Vue', 2, 'itkey', '2022-05-09 17:19:09', '', '2022-05-09 17:27:35');
    INSERT INTO qa_category (title, sort, create_by, create_time, update_by, update_time) VALUES ('React', 3, 'itkey', '2022-05-10 10:46:28', '', '2022-05-10 11:05:27');
    INSERT INTO qa_category (title, sort, create_by, create_time, update_by, update_time) VALUES ('mysql', 4, 'itkey', '2022-05-11 14:51:48', '', '2022-05-11 14:51:59');
    INSERT INTO qa_category (title, sort, create_by, create_time, update_by, update_time) VALUES ('MacOS', 5, 'itkey', '2022-05-11 14:53:18', '', '2022-05-11 14:53:24');
    
    • 1
    • 2
    • 3
    • 4
    • 5

    代码

    本来想写细点的,发现也没有什么内容可以说的。我直接上代码吧。

    pom.xml

    mybatis-demo/pom.xml 这个文件的重点就是mysql,mybatis的依赖。

    
    <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">
        <modelVersion>4.0.0modelVersion>
    
        <groupId>org.examplegroupId>
        <artifactId>mybatis-demoartifactId>
        <version>1.0-SNAPSHOTversion>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
    
        <dependencies>
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>8.0.28version>
            dependency>
    
            <dependency>
                <groupId>org.mybatisgroupId>
                <artifactId>mybatisartifactId>
                <version>3.5.10version>
            dependency>
    
        dependencies>
    
    project>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    实体类

    mybatis-demo/src/main/java/cn/ycmit/domain/QaCategory.java

    package cn.ycmit.domain;
    
    
    
    import java.util.Date;
    
    /**
     * 问答分类对象 qa_category
     *
     * @author ycmit
     * @date 2022-05-09
     */
    public class QaCategory
    {
        private static final long serialVersionUID = 1L;
    
        /** 分类ID */
        private Long categoryId;
    
        /** 标题 */
        private String title;
    
        /** 排序 */
        private Integer sort;
    
        /**
         * 创建者
         */
        private String createBy;
    
        /**
         * 创建时间
         */
        private Date createTime;
    
        /**
         * 更新者
         */
        private String updateBy;
    
        /**
         * 更新时间
         */
        private Date updateTime;
    
        public void setCategoryId(Long categoryId)
        {
            this.categoryId = categoryId;
        }
    
        public Long getCategoryId()
        {
            return categoryId;
        }
        public void setTitle(String title)
        {
            this.title = title;
        }
    
        public String getTitle()
        {
            return title;
        }
        public void setSort(Integer sort)
        {
            this.sort = sort;
        }
    
        public Integer getSort()
        {
            return sort;
        }
    
        public String getCreateBy() {
            return createBy;
        }
    
        public void setCreateBy(String createBy) {
            this.createBy = createBy;
        }
    
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    
        public String getUpdateBy() {
            return updateBy;
        }
    
        public void setUpdateBy(String updateBy) {
            this.updateBy = updateBy;
        }
    
        public Date getUpdateTime() {
            return updateTime;
        }
    
        public void setUpdateTime(Date updateTime) {
            this.updateTime = updateTime;
        }
    
        @Override
        public String toString() {
            return "QaCategory{" +
                    "categoryId=" + categoryId +
                    ", title='" + title + '\'' +
                    ", sort=" + sort +
                    ", createBy='" + createBy + '\'' +
                    ", createTime=" + createTime +
                    ", updateBy='" + updateBy + '\'' +
                    ", updateTime=" + updateTime +
                    '}';
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119

    mapper

    mybatis-demo/src/main/java/cn/ycmit/mapper/QaCategoryMapper.java

    package cn.ycmit.mapper;
    
    
    
    import cn.ycmit.domain.QaCategory;
    
    import java.util.List;
    
    /**
     * 问答分类Mapper接口
     *
     * @author ycmit
     * @date 2022-05-09
     */
    public interface QaCategoryMapper
    {
        /**
         * 查询问答分类
         *
         * @param categoryId 问答分类主键
         * @return 问答分类
         */
        public QaCategory selectQaCategoryByCategoryId(Long categoryId);
    
        /**
         * 查询问答分类列表
         *
         * @param qaCategory 问答分类
         * @return 问答分类集合
         */
        public List<QaCategory> selectQaCategoryList(QaCategory qaCategory);
    
        /**
         * 新增问答分类
         *
         * @param qaCategory 问答分类
         * @return 结果
         */
        public int insertQaCategory(QaCategory qaCategory);
    
        /**
         * 修改问答分类
         *
         * @param qaCategory 问答分类
         * @return 结果
         */
        public int updateQaCategory(QaCategory qaCategory);
    
        /**
         * 删除问答分类
         *
         * @param categoryId 问答分类主键
         * @return 结果
         */
        public int deleteQaCategoryByCategoryId(Long categoryId);
    
        /**
         * 批量删除问答分类
         *
         * @param categoryIds 需要删除的数据主键集合
         * @return 结果
         */
        public int deleteQaCategoryByCategoryIds(Long[] categoryIds);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    mybatis-config.xml

    mybatis-demo/src/main/resources/mybatis/mybatis-config.xml
    这是主配置文件:

    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://127.0.0.1:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true"/>
                    <property name="username" value="root"/>
                    <property name="password" value="itkey123456"/>
                dataSource>
            environment>
        environments>
        <mappers>
            <mapper resource="mybatis/QaCategoryMapper.xml"/>
        mappers>
    configuration>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    QaCategoryMapper.xml

    mybatis-demo/src/main/resources/mybatis/QaCategoryMapper.xml
    内容如下:

    
    DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="cn.ycmit.mapper.QaCategoryMapper">
    
        <resultMap type="cn.ycmit.domain.QaCategory" id="QaCategoryResult">
            <result property="categoryId"    column="category_id"    />
            <result property="title"    column="title"    />
            <result property="sort"    column="sort"    />
            <result property="createBy"    column="create_by"    />
            <result property="createTime"    column="create_time"    />
            <result property="updateBy"    column="update_by"    />
            <result property="updateTime"    column="update_time"    />
        resultMap>
    
        <sql id="selectQaCategoryVo">
            select category_id, title, sort, create_by, create_time, update_by, update_time from qa_category
        sql>
    
        <select id="selectQaCategoryList" parameterType="cn.ycmit.domain.QaCategory" resultMap="QaCategoryResult">
            <include refid="selectQaCategoryVo"/>
            <where>
                <if test="title != null  and title != ''"> and title like concat('%', #{title}, '%')if>
                <if test="sort != null "> and sort = #{sort}if>
            where>
        select>
    
        <select id="selectQaCategoryByCategoryId" parameterType="Long" resultMap="QaCategoryResult">
            <include refid="selectQaCategoryVo"/>
            where category_id = #{categoryId}
        select>
    
        <insert id="insertQaCategory" parameterType="cn.ycmit.domain.QaCategory" useGeneratedKeys="true" keyProperty="categoryId">
            insert into qa_category
            <trim prefix="(" suffix=")" suffixOverrides=",">
                <if test="title != null and title != ''">title,if>
                <if test="sort != null">sort,if>
                <if test="createBy != null">create_by,if>
                <if test="createTime != null">create_time,if>
                <if test="updateBy != null">update_by,if>
                <if test="updateTime != null">update_time,if>
             trim>
            <trim prefix="values (" suffix=")" suffixOverrides=",">
                <if test="title != null and title != ''">#{title},if>
                <if test="sort != null">#{sort},if>
                <if test="createBy != null">#{createBy},if>
                <if test="createTime != null">#{createTime},if>
                <if test="updateBy != null">#{updateBy},if>
                <if test="updateTime != null">#{updateTime},if>
             trim>
        insert>
    
        <update id="updateQaCategory" parameterType="cn.ycmit.domain.QaCategory">
            update qa_category
            <trim prefix="SET" suffixOverrides=",">
                <if test="title != null and title != ''">title = #{title},if>
                <if test="sort != null">sort = #{sort},if>
                <if test="createBy != null">create_by = #{createBy},if>
                <if test="createTime != null">create_time = #{createTime},if>
                <if test="updateBy != null">update_by = #{updateBy},if>
                <if test="updateTime != null">update_time = #{updateTime},if>
            trim>
            where category_id = #{categoryId}
        update>
    
        <delete id="deleteQaCategoryByCategoryId" parameterType="Long">
            delete from qa_category where category_id = #{categoryId}
        delete>
    
        <delete id="deleteQaCategoryByCategoryIds" parameterType="String">
            delete from qa_category where category_id in
            <foreach item="categoryId" collection="array" open="(" separator="," close=")">
                #{categoryId}
            foreach>
        delete>
    mapper>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78

    测试类

    mybatis-demo/src/main/java/cn/ycmit/MybatisTest.java

    package cn.ycmit;
    
    
    
    import java.io.InputStream;
    import java.util.List;
    
    import cn.ycmit.domain.QaCategory;
    import cn.ycmit.mapper.QaCategoryMapper;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    public class MybatisTest {
        public static void main(String[] args) throws Exception {
            test();
        }
    
        public static void test() throws Exception{
            String resource = "mybatis/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
            try (SqlSession session = sqlSessionFactory.openSession()) {
                QaCategoryMapper mapper = session.getMapper(QaCategoryMapper.class);
                List<QaCategory> list = mapper.selectQaCategoryList(null);
                System.out.println(list);
            }
    
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    执行结果:

    [QaCategory{categoryId=1, title='Java', sort=1, createBy='itkey', createTime=Mon May 09 17:18:50 CST 2022, updateBy='', updateTime=Mon May 09 17:27:35 CST 2022}, QaCategory{categoryId=2, title='Vue', sort=2, createBy='itkey', createTime=Mon May 09 17:19:09 CST 2022, updateBy='', updateTime=Mon May 09 17:27:35 CST 2022}, QaCategory{categoryId=3, title='React', sort=3, createBy='itkey', createTime=Tue May 10 10:46:28 CST 2022, updateBy='', updateTime=Tue May 10 11:05:27 CST 2022}, QaCategory{categoryId=4, title='mysql', sort=4, createBy='itkey', createTime=Wed May 11 14:51:48 CST 2022, updateBy='', updateTime=Wed May 11 14:51:59 CST 2022}, QaCategory{categoryId=5, title='MacOS', sort=5, createBy='itkey', createTime=Wed May 11 14:53:18 CST 2022, updateBy='', updateTime=Wed May 11 14:53:24 CST 2022}]
    
    • 1

    源码

    其实所有用到的源码我已经全部写到文章中了。为了方便给有用的人,我把我的项目打包分享如下:
    https://download.csdn.net/download/lxyoucan/86336480

  • 相关阅读:
    Hive 动态分区向表插入数据报错 GC overhead limit exceeded (分区过多场景)
    机房环境监控什么意思?机房环境监控系统作用
    Day06-filebeat,logstash多实例,pipline,ElasticStack项目架构梳理及实战案例
    【MySQL高级】Mysql的体系结构概览及存储引擎以及索引的使用
    港联证券:“保险+期货”快速落地生花 涉及品种累计达18个
    lvs+keepalived
    第4季4:图像sensor的驱动源码解析
    eBPF理解 (四)
    firefox浏览器添加自定义搜索引擎方法
    别人做跨境电商都月入过万了,真这么好做吗?
  • 原文地址:https://blog.csdn.net/lxyoucan/article/details/126162493