【mybatis专题】二:mybatis-spring快速开始

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

参考官网:http://mybatis.org/spring/getting-started.html

1、创建maven项目,项目结构如下图所示,然后引入依赖

项目依赖如下,maven有个优点,依赖传递,只需要引入spring-webmvc的依赖就基本引用了常用的spring依赖了

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.22.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.2</version>
    </dependency>

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

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.22.RELEASE</version>
    </dependency>

2、在mysql选择一个数据库创建一个简单的blog表,建表语句如下(阅读过上一章的可以跳过此步骤,使用的还是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、创建BlogService和BlogServiceImpl

package org.example.service;

import org.example.entity.Blog;

import java.util.List;

public interface BlogService {

    List<Blog> queryAllBlog();
    int addBlog(Blog blog);
    int updateBlogByBlogId(Blog blog, int blogId);
    int deleteBlogByBlogId(int blogId);
}
package org.example.service.impl;

import org.example.entity.Blog;
import org.example.mapper.BlogMapper;
import org.example.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Override
    public List<Blog> queryAllBlog() {
        return blogMapper.queryAllBlog();
    }

    @Override
    public int addBlog(Blog blog) {
        return blogMapper.addBlog(blog);
    }

    @Override
    public int updateBlogByBlogId(Blog blog, int blogId) {
        return blogMapper.updateBlogByBlogId(blog,blogId);
    }

    @Override
    public int deleteBlogByBlogId(int blogId) {
        return blogMapper.deleteBlogByBlogId(blogId);
    }
}

5、准备好mysql连接数据库的基本信息db.properties

datasource.driverClass = com.mysql.jdbc.Driver
datasource.url = jdbc:mysql://localhost:3306/my_test?useSSL=false
datasource.username = root
datasource.password = root

6、根据官网所说spring使用mybatis必须有SqlSessionFactory和一个mapper接口,mapper上面已经创建了,下面通过Java config引入SqlSessionFactory

package org.example.config;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;

@Configuration
@PropertySources({@PropertySource("db.properties")})
public class MybatisConfig {

    @Value("${datasource.driverClass}")
    private String driverClass;
    @Value("${datasource.url}")
    private String url;
    @Value("${datasource.username}")
    private String username;
    @Value("${datasource.password}")
    private String password;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        //此处类似mybatis-config.xml的configuration标签
        org.apache.ibatis.session.Configuration configuration =new org.apache.ibatis.session.Configuration();
        //开启mybatis下划线自动转换驼峰命名
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
        return sqlSessionFactory;
    }

    @Bean
    public DataSource dataSource(){
        PooledDataSource pooledDataSource = new PooledDataSource();
        pooledDataSource.setDriver(driverClass);
        pooledDataSource.setUrl(url);
        pooledDataSource.setUsername(username);
        pooledDataSource.setPassword(password);
        return pooledDataSource;
    }

}

7、app使用main方法启动spring容器,测试是否能够正常使用mybatis

package org.example;

import org.example.entity.Blog;
import org.example.service.BlogService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.*;

import java.util.List;

@ComponentScan(basePackages = {"org.example"})
@MapperScan(basePackages = {"org.example.mapper"})
public class App{

    public static void main( String[] args )
    {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(App.class);
        BlogService blogService = applicationContext.getBean(BlogService.class);
        List<Blog> blogs = blogService.queryAllBlog();
        if(blogs!=null){
            for (Blog blog : blogs) {
                System.out.println(blog);
            }
        }else{
            System.out.println("blogs is null");
        }
    }
}

8、测试结果:

结果表明:BlogMapper成功注入BlogService的实例中

下章讲述mybatis是怎样将BlogMapper接口实例化并且根据@Select、@Insert、@Update、@Delete的注解和value(sql) 实现执行sql的效果,并且将生成的类交给spring容器来管理的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值