JAVA快餐 4 spring boot集成mybatis(1)

作者: gavin 分类: Java,Java 快餐 发布时间: 2020-10-31 20:44

概述

MyBatis是一个开源的持久层框架,现在互联网项目使用比较多,MyBatis简化了Java应用程序中对数据库的访问,实现了诸如动态SQL、结果集映射等,高效又不失灵活,简单地说,它是JDBC和Hibernate的替代品,个人在项目中倾向使用mybatis。本文介绍在spring boot项目中集成mybatis过程。

创建一个SpringBoot项目,添加依赖包JDBC、web、mysql、mybatis

pom.xml文件

自动生成的pom.xml文件内容如下

<?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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.qikegu</groupId>
    <artifactId>springboot-mybatis-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mybatis-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

经典项目结构

添加一些目录,创建经典的项目结构(mvc),如下图:

image

src/main/java/com/qikegu/demo 文件夹下添加目录:

  • common – 公用代码
  • config – spring java配置文件
  • controller – 控制层
  • model – 对象层
  • repository – 数据库访问层,保存mybatis的映射类
  • service – 服务层

src/main/resources文件夹下添加目录:

  • mapper – mybatis sql映射xml文件

配置

application.properties配置

## 服务器端口,如果不配置默认是8080端口
server.port=8096 

## 数据库设置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/qikegu_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=你的密码

## mybatis配置
# 参数类型的包别名设置
mybatis.typeAliasesPackage=com.qikegu.demo.model
# 指向映射xml文件目录
mybatis.mapperLocations=classpath:mapper/*.xml

数据库配置不作说明了,不清楚可以参照 [spring boot 连接 mysql]。

mybatis配置说明一下,typeAliasesPackage:参数类型的包别名设置,设置这个以后xml映射文件在parameterType的值就不用写成全路径名了,parameterType=”com.qikegu.demo.model.User”可以写成parameterType = “User”。

@MapperScan注解

@MapperScan的作用是指定要扫描的mybatis映射类的路径,放在应用类的前面:

package com.qikegu.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//指定要扫描的mybatis映射类的路径
@MapperScan("com.qikegu.demo.repository")
public class SpringbootMybatisDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
    }
}

添加代码

我们实现一个通过用户id查询用户信息的接口。

添加的文件如下图:

image

调用过程:用户访问 > UserController > UserService > UserMapper.java > UserMapper.xml > 数据库,返回User对象

下面列出每个文件内容,重要地方都已注释

User.java – 对象类

package com.qikegu.demo.model;

public class User {
    private long id;
    private String nickname;
    private String mobile;

    @JsonProperty(access = Access.WRITE_ONLY) //在输出的Json数据中隐藏密码,只能输入不输出
    private String password;

    private String role;

    public User(long id, String nickname, String mobile, String password, String role) {
        this.id = id;
        this.nickname = nickname;
        this.mobile = mobile;
        this.password = password;
        this.role = role;
    }

    public User() {
        super();
    }

    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
}

UserService.java – 服务接口类

package com.qikegu.demo.service;

import com.qikegu.demo.model.User;

public interface UserService {

    public User getUserById(long userId);

}

UserServiceImpl – 服务接口实现类

package com.qikegu.demo.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qikegu.demo.model.User;
import com.qikegu.demo.repository.UserMapper;
import com.qikegu.demo.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

    // 注入mapper类
    @Resource
    private UserMapper userMapper;

    @Override
    public User getUserById(long userId) {
        return userMapper.selectByPrimaryKey(userId);
    }
}

UserController – 控制类

package com.qikegu.demo.controller;

import javax.annotation.Resource;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.qikegu.demo.model.User;
import com.qikegu.demo.service.UserService;

@RestController
@EnableAutoConfiguration
@RequestMapping("/user")
public class UserController {

    // 注入mapper类
    @Resource
    private UserService userService;

    @RequestMapping(value="{id}", method=RequestMethod.GET, produces="application/json")
    public User getUser(@PathVariable long id) throws Exception {

        User user = this.userService.getUserById(id);

        return user;
    }

}

UserMapper.java – mybatis映射类,数据库访问层

package com.qikegu.demo.repository;

import com.qikegu.demo.model.User;

public interface UserMapper {

    // 对应xml映射文件元素的ID
    User selectByPrimaryKey(long id);

}

UserMapper.xml – mybatis xml映射文件

<?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.qikegu.demo.repository.UserMapper">
  <resultMap id="BaseResultMap" type="com.qikegu.demo.model.User">
    <constructor>
      <idArg column="id" javaType="_long" jdbcType="BIGINT" />
      <arg column="nickname" javaType="java.lang.String" jdbcType="VARCHAR" />
      <arg column="mobile" javaType="java.lang.String" jdbcType="VARCHAR" />
      <arg column="password" javaType="java.lang.String" jdbcType="CHAR" />
      <arg column="role" javaType="java.lang.String" jdbcType="VARCHAR" />
    </constructor>
  </resultMap>

  <sql id="Base_Column_List">
    id, nickname, mobile, password, role
  </sql>
  <select id="selectByPrimaryKey" parameterType="_long" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=BIGINT}
  </select>
</mapper>

运行

项目的右键菜单,选择:run as -> spring boot app 运行程序,浏览器访问获取用户信息:

image

总结

本文件介绍了spring boot集成mybatis的过程,集成过程总结如下:

  1. 创建项目设置依赖时勾选mybatis依赖
  2. application.properties设置
  3. @MapperScan注解设置
  4. 写映射xml文件与映射java类
  5. 在controller或service中调用映射类的方法

经过测试,集成成功。

完整代码

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注