SpringBoot 2.0.2.RELEASE以注解和XML的形式整合 Mybatis (SpringBoot 2.0.2.RELEASE版本)

说明:   

     随着springboot发布了2.0的正式版本,很多同学可能没有注意版本,导致了整合的时候出现了很多很多的问题,这几天刚好有空就试着整合一下springboot2.0 mybatis,发现了很多很多的坑,而且网上的资源也不多,终于在两天的踩坑中成功整合了,并且将翻页功能修复好了,废话不多说了,看代码:

环境/版本一览:

  • 开发工具:Spring Tool Suite   3.9.4.RELEASE
  • springboot: 2.0.1.RELEASE
  • jdk:1.8.0_40
  • maven:3.5.1
  • alibaba Druid 数据库连接池:1.1.0

额外功能:

  • PageHelper 分页插件

开始搭建环境:

  1.  首先创建springBoot项目,我这里就不一一讲解了,不明白的童鞋可以自行百度,网上有详细说明
  2.  接下来就是重点了首先引入相关jar包

    依赖文件:

    按照pom文件补齐需要的依赖:                

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

	<groupId>com.example</groupId>
	<artifactId>demo-1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo-1</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<java.version>1.8</java.version>
		<!-- excel export -->
		<poi.version>3.17</poi.version>
		<!-- impala -->
		<hive.version>2.5.42</hive.version>
		<thrift.version>0.9.3</thrift.version>
	    <!-- mybatis -->
	    <mybatis.version>3.4.6</mybatis.version>  
	    <mybatis.spring.version>1.3.2</mybatis.spring.version>  
        <!-- charset encding -->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>
	
	<dependencies>
		
		<!-- start: spring boot -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>
		<!-- end: spring boot -->
		
		<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>
        
        <!-- springboot分页插件 -->
		<dependency>
		    <groupId>com.github.pagehelper</groupId>
		    <artifactId>pagehelper-spring-boot-starter</artifactId>
		    <version>1.2.3</version>
		</dependency>
	</dependencies>

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

</project>

项目结构:

  • 基于XML形式

  • 基于注解形式


项目启动类:


package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Demo2Application {

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

配置:

application.properties

可以根据个人使用习惯选择使用properties或者yml文件,本项目使用的是yml配置文件,所以把原本application.properties删除,在resource文件夹下创建一个application.yml文件

#application port configuration
server.port=8080

#dataSource configuration
spring.datasource.name=springboots
spring.datasource.url=jdbc\:mysql\://127.0.0.1\:3306/mytest?useUnicode\=true&characterEncoding\=gbk&zeroDateTimeBehavior\=convertToNull
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.filters=stat
spring.datasource.maxActive=20
spring.datasource.initialSize=1
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.maxOpenPreparedStatements=20

创建数据库和数据表


CREATE DATABASE mytest;

CREATE TABLE t_user(
  userId INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  userName VARCHAR(255) NOT NULL ,
  password VARCHAR(255) NOT NULL ,
  phone VARCHAR(255) NOT NULL
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;

创建实体类:UserDomain.java

package com.example.demo.entity;

public class UserDomain {
    private Integer userId;

    private String userName;

    private String password;

    private String phone;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone == null ? null : phone.trim();
    }
}

创建 :controller

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.entity.UserDomain;
import com.example.demo.service.UserService;
import com.github.pagehelper.PageHelper;

/**
 * Created by Administrator on 2017/8/16.
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;


    @ResponseBody
    @GetMapping("/all")
    public Object findAllUser(int pageNum, int pageSize) {
        //开始分页
        PageHelper.startPage(pageNum,pageSize);
        return userService.findAllUser(pageNum,pageSize);
    }
}

创建:service

package com.example.demo.service;

import java.util.List;

import com.example.demo.entity.UserDomain;

/**
 * Created by Administrator on 2018/4/19.
 */
public interface UserService {


    List<UserDomain> findAllUser(int pageNum, int pageSize);
}

创建:serviceImpl

package com.example.demo.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.entity.UserDomain;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.github.pagehelper.PageHelper;

/**
 * Created by Administrator on 2017/8/16.
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;//这里会报错,但是并不会影响


    /*
    * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
    * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
    * pageNum 开始页数
    * pageSize 每页显示的数据条数
    * */
    @Override
    public List<UserDomain> findAllUser(int pageNum, int pageSize) {
        //将参数传给这个方法就可以实现物理分页了,非常简单。
        PageHelper.startPage(pageNum, pageSize);
        return userMapper.selectUsers();
    }
}



创建:Mapper

  • 以注解的形式
package com.example.demo.mapper;


import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.example.demo.entity.UserDomain;

@Mapper
public interface UserMapper {

	@Select(" SELECT\n" + 
			"			user_id  userId,\n" + 
			"			user_name  userName,\n" + 
			"			password  password,\n" + 
			"			phone\n" + 
			"		FROM\n" + 
			"			t_user")
    List<UserDomain> selectUsers();
}

  • 以XML的形式(在这里一定要加上注解)
package com.example.demo.mapper;


import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.example.demo.entity.UserDomain;

@Mapper
public interface UserMapper {
    int insert(UserDomain record);

    List<UserDomain> selectUsers();
}
  • 如果是以XML的形式还要进行一下步骤

  1. resource目录下新建mapper文件夹(文件夹名字可以自定义)
  2. 在配置文件中添加一下代码:(这里主要用于指定mybatis 映射文件路径.classpath后面的文件夹名称一定要和上面自己建的文件夹名称一致)
mybatis.mapper-locations=classpath:mapper/*.xml

映射文件:UserMapper.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.example.demo.mapper.UserMapper" >
  <select id="selectUsers" resultType="com.example.demo.entity.UserDomain">
      SELECT
			user_id  userId,
			user_name  userName,
			password  password,
			phone
		FROM
			t_user
  </select>
</mapper>
到这里所有的配置已经完成.在浏览器中访问:http://localhost:8080/user/all?pageNum=3&pageSize=4

其中参数是为了分页所用分别表示:pageNum:当前页数------pageSize:每页显示数量

测试:


代码资源地址:

  1. SpringBoot 2.0.2基于XML配置形式Mybatis:https://download.csdn.net/download/guokezhongdeyuzhou/10407485
  2. SpringBoot 2.0.2基于注解形式Mybatis:https://download.csdn.net/download/guokezhongdeyuzhou/10407462


展开阅读全文

没有更多推荐了,返回首页