您当前的位置: 首页 >  mybatis

ITKEY_

暂无认证

  • 0浏览

    0关注

    732博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

mybatis小示例

ITKEY_ 发布时间:2022-08-06 12:15:00 ,浏览量:0

一般使用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 '提问分类';

测试数据

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');
代码

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

pom.xml

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



    4.0.0

    org.example
    mybatis-demo
    1.0-SNAPSHOT

    
        8
        8
    

    
        
        
            mysql
            mysql-connector-java
            8.0.28
        

        
            org.mybatis
            mybatis
            3.5.10
        

    



实体类

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 +
                '}';
    }
}

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 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);
}

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">

    
        
            
            
                
                
                
                
            
        
    
    
        
    


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">


    
        
        
        
        
        
        
        
    

    
        select category_id, title, sort, create_by, create_time, update_by, update_time from qa_category
    

    
        
        
             and title like concat('%', #{title}, '%')
             and sort = #{sort}
        
    

    
        
        where category_id = #{categoryId}
    

    
        insert into qa_category
        
            title,
            sort,
            create_by,
            create_time,
            update_by,
            update_time,
         
        
            #{title},
            #{sort},
            #{createBy},
            #{createTime},
            #{updateBy},
            #{updateTime},
         
    

    
        update qa_category
        
            title = #{title},
            sort = #{sort},
            create_by = #{createBy},
            create_time = #{createTime},
            update_by = #{updateBy},
            update_time = #{updateTime},
        
        where category_id = #{categoryId}
    

    
        delete from qa_category where category_id = #{categoryId}
    

    
        delete from qa_category where category_id in
        
            #{categoryId}
        
    


测试类

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 list = mapper.selectQaCategoryList(null);
            System.out.println(list);
        }

    }

}

执行结果:

[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}]
源码

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

关注
打赏
1665243900
查看更多评论
立即登录/注册

微信扫码登录

0.0483s