Integrated spring boot mybatis (1)


Spring Boot Integration Tutorial


Outline

MyBatis is an open source persistence framework, the project now use the Internet more, MyBatis simplifies Java application access to the database, such as to achieve a dynamic SQL, the result set mapping, efficient yet flexible, simply put, it JDBC and Hibernate are alternatives, individuals tend to use mybatis in the project. This article describes the process of integration mybatis in spring boot project.

Prepare data

We use the previous section [spring boot connected mysql] the same data, no data such as text refer to the preparation of data, which describes in detail the process by the graphics client mysql workbench generated data. If you tend to use the mysql command-line client, the following statement is to create a sql database and insert data.

sql statement

mysql command-line client connect to the database:

mysql -h localhost -u root -p

Create a database

CREATE DATABASE qikegu_demo CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Create a table of sql statement:

CREATE TABLE `qikegu_demo`.`user` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `nickname` VARCHAR(50) NULL COMMENT '昵称',
  `mobile` VARCHAR(20) NULL COMMENT '手机号',
  `password` CHAR(60) NULL COMMENT '密码hash值',
  `role` VARCHAR(100) NULL DEFAULT 'user' COMMENT '角色,角色名以逗号分隔',
  PRIMARY KEY (`id`),
  UNIQUE INDEX `mobile_UNIQUE` (`mobile` ASC))
COMMENT = '用户表';

Insert data sql statement:

INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc1', '13512345678', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc2', '13512345677', '123');

Create a project

Create a spring boot project

Open the Eclipse, creating spring starter project of spring boot program, dependent upon the configuration, check the web, jdbc, mysql, mybatis, as clear how to create a spring boot program, referring to the section: [spring boot hello world (restful Interface) Examples]

image

pom.xml file

Auto-generated content file as 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>

Classic project structure

Add some directory, create a classic project structure (mvc), as shown below:

image

src / main / java / com / qikegu / demo folder to add directory:

  • common - common code
  • config - spring java profiles
  • controller - control layer
  • model - Object Layer
  • repository - a database access layer, save mybatis mapping class
  • service - service layer

src / main / resources folder add the directory:

  • mapper - mybatis sql mapping xml file

Configuration

application.properties Configuration

## 服务器端口,如果不配置默认是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

Database configuration is not described, reference may be unclear [spring boot connected mysql].

mybatis configuration explain, typeAliasesPackage: parameter type of package alias, set this value after the xml mapping files in parameterType would not have written a full path name, parameterType = "com.qikegu.demo.model.User" can be written parameterType = " User ".

@MapperScan comment

@MapperScan role is to specify the path to be scanned mybatis mapped classes, on the front of the application classes:

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

Add code

We realize an id query interface user information through the user.

Add the file as shown below:

image

Call the procedure: 用户访问 > UserController > UserService > UserMapper.java > UserMapper.xml > 数据库return to User objects

The following lists the contents of each file, important places are comments

User.java - object classes

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 - Service interface class

package com.qikegu.demo.service;

import com.qikegu.demo.model.User;

public interface UserService {
    
    public User getUserById(long userId);
   
}

UserServiceImpl - service interface implementation class

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

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 mapping class, database access layer

package com.qikegu.demo.repository;

import com.qikegu.demo.model.User;

public interface UserMapper {

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

}

UserMapper.xml - mybatis xml mapping file

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

Project context menu, select: run as -> spring boot app to run the program, browser access for user information:

image

to sum up

This document describes the process of integration mybatis spring boot, the integration process is summarized as follows:

  1. Check mybatis rely on when creating a project set dependencies
  2. Set application.properties
  3. @MapperScan comment settings
  4. Write xml mapping file and mapped java classes
  5. Call controller class in the mapping method or service

After testing, integration success.

The complete code

Guess you like

Origin www.cnblogs.com/jinbuqi/p/11008881.html