【mybatis专题】一、快速开始

本文基于Java+mybatis+mysql创建一个简易的mybatis的快速开始的demo

参考官网:https://mybatis.org/mybatis-3/getting-started.html

1、创建一个maven项目,引入maven依赖:

maven项目的目录结构大致如下图,此处只是简单使用,忽略service层,直接在app的main方法获取mapper调用方法:

mybatis和mysql的版本根据自己需要选择:

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>

2、在mysql选择一个数据库创建一个简单的blog表,建表语句如下:

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for blog
-- ----------------------------
DROP TABLE IF EXISTS `blog`;
CREATE TABLE `blog`  (
  `blog_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL,
  `author` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
  `update_time` datetime(0) NULL DEFAULT NULL,
  PRIMARY KEY (`blog_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of blog
-- ----------------------------
INSERT INTO `blog` VALUES (1, 'mybatis快速开始', '参考:https://mybatis.org/mybatis-3/getting-started.html', 'csdn_white', '2020-12-17 10:25:54', NULL);
INSERT INTO `blog` VALUES (2, 'mybatis集成spring', '参考:http://mybatis.org/spring/index.html', 'csdn_white', '2020-12-17 10:26:46', NULL);

SET FOREIGN_KEY_CHECKS = 1;

3、创建基本的Java实体类Blog和BlogMapper接口

package com.example.mybatis.entity;

import java.util.Date;

public class Blog {
    private int blogId;
    private String title;
    private String content;
    private String author;
    private Date createTime;
    private Date updateTime;

    public int getBlogId() {
        return blogId;
    }

    public void setBlogId(int blogId) {
        this.blogId = blogId;
    }

    public String getTitle() {
        return title;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    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 Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    @Override
    public String toString() {
        return "Blog{" +
                "blogId=" + blogId +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                '}';
    }
}
package com.example.mybatis.mapper;

import com.example.mybatis.entity.Blog;
import org.apache.ibatis.annotations.*;

import java.util.Date;
import java.util.List;

public interface BlogMapper {

    @Select("select * from blog")
    List<Blog> queryAllBlog();

    @Insert("insert into blog(title,content,author,create_time) values(#{title},#{content},#{author},#{createTime,jdbcType=TIMESTAMP})")
    int addBlog(Blog blog);

    @Update("update blog set content=#{blog.content},update_time=#{blog.updateTime} where blog_id=#{blogId}")
    int updateBlogByBlogId(@Param("blog") Blog blog, @Param("blogId") int blogId);

    @Delete("delete from blog where blog_id=#{blogId}")
    int deleteBlogByBlogId(@Param("blogId")int blogId);
}

4、创建mybatis-config.xml

本文为了将数据库和Java实体类的字段匹配,setting设置了驼峰命名,其他开启缓存等更多设置请参考:https://mybatis.org/mybatis-3/configuration.html

<?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>
    <properties>
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/my_test?useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </properties>
    <settings>
        <!--更多设置参考:https://mybatis.org/mybatis-3/configuration.html-->
        <!--开启下划线转驼峰命名-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <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 class="com.example.mybatis.mapper.BlogMapper"/>
    </mappers>
</configuration>

5、app中使用junit进行单元测试

package com.example.mybatis;

import com.example.mybatis.entity.Blog;
import com.example.mybatis.mapper.BlogMapper;
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 org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MybatisQuickstartApplication {

    SqlSession sqlSession = null;

    @Before
    public void getSqlSession() {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            //1、SqlSessionFactoryBuilder使用mybatis-config.xml创建SqlSessionFactory
            SqlSessionFactory sqlSessionFactory =
                    new SqlSessionFactoryBuilder().build(inputStream);
            //2、获取SqlSession,设置autoCommit为true,
            // 否则执行insert、update、delete之后需要执行sqlSession.commit();才能在数据持久层生效
//            sqlSession = sqlSessionFactory.openSession(true);
            sqlSession = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testQueryAllBlog(){
        //3、通过SqlSession传入接口类型获取接口实例(此处底层使用的jdk动态代理)
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        //4、mapper调用方法返回结果
        List<Blog> blogList = blogMapper.queryAllBlog();
        if(blogList!=null){
            for (Blog blog : blogList) {
                System.out.println(blog);
            }
        }
    }

    @Test
    public void testAddBlog() {
        //3、通过SqlSession传入接口类型获取接口实例(此处底层使用的jdk动态代理)
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        //4、mapper调用方法返回结果
        Blog blog = new Blog();
        blog.setTitle("测试新增一条blog");
        Date date = new Date();
        blog.setContent(date.toString());
        blog.setAuthor("test");
        blog.setCreateTime(date);
        int i = blogMapper.addBlog(blog);
        System.out.println(i);
        if(i>0){
            System.out.println("添加成功:"+blog);
        }else{
            System.out.println("添加失败:"+blog);
        }
        sqlSession.commit();
        testQueryAllBlog();//此处提交以后再查询,不然可能查到当前session未提交的数据
    }

    @Test
    public void testUpdate(){
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();
        Date date = new Date();
        blog.setContent(date.toString());
        blog.setUpdateTime(date);
        int blogId=16;
        int i = blogMapper.updateBlogByBlogId(blog, blogId);
        System.out.println(i);
        if(i>0){
            System.out.println("修改成功:"+blogId);
        }else{
            System.out.println("修改失败:"+blogId);
        }
        sqlSession.commit();
        testQueryAllBlog();//此处提交以后再查询,不然可能查到当前session未提交的数据
    }


    @Test
    public void testDelete(){
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
        int blogId=16;
        int i = blogMapper.deleteBlogByBlogId(blogId);
        System.out.println(i);
        if(i>0){
            System.out.println("删除成功:"+blogId);
        }else{
            System.out.println("删除失败:"+blogId);
        }
        sqlSession.commit();
        testQueryAllBlog();//此处提交以后再查询,不然可能查到当前session未提交的数据
    }
}

查询方法测试结果:

新增方法测试结果,如果在执行@insert返回了1但是数据库实际没有插入,参考:https://blog.csdn.net/qq_34474324/article/details/98480433

新增前:

新增后:

测试修改:

测试删除:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值