SpringBoot+MyBatis+Mysql整合详细步骤

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lihua5419/article/details/81536629

可以通过官网来构建项目,点击https://start.spring.io/,页面可选择所构建的版本号

点击下载-然后导入Idea中,修改一下项目目录结构,如下图所示,(此处省略步骤直接进入正题)

先配置application.yml信息,代码如下:

# DATASOURCE
jdbc:
    dataSourceClassName: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
    url: jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
    databaseName: student
    serverName: 127.0.0.1
    username: root
    password: 123456
    cachePrepStmts: true
    prepStmtsSize: 250
    prepStmtsCacheSqlLimit: 2048
    userServerPrepStmts: true

# MyBatis
mybatis:
        typeAliasesPackage: com.example.api.*.dao
        mapperLocations: classpath:/mappers/*.xml
        configLocation: classpath:/mybatis-config.xml

mybatis-config.xml信息如下:

<?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="dialect" value="mysql" />
    </properties>
    <settings>
        <!-- 这个配置使全局的映射器启用或禁用缓存。系统默认值是true,设置只是为了展示出来 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!--使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="useColumnLabel" value="true" />
        <!--允许 JDBC 支持生成的键。需要适合的驱动。如果设置为 true 则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如
            Derby)。 系统默认值是false,设置只是为了展示出来 -->
        <setting name="useGeneratedKeys" value="false" />
        <!--配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 系统默认值是SIMPLE,设置只是为了展示出来 -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!--设置超时时间,它决定驱动等待一个数据库响应的时间。 系统默认值是null,设置只是为了展示出来 -->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql" />
            <property name="offsetAsPageNum" value="true" />
            <property name="rowBoundsWithCount" value="true" />
            <property name="pageSizeZero" value="true" />
            <property name="reasonable" value="true" />
        </plugin>
    </plugins>
</configuration>

pom.xml增加mybatis相关依赖,需要注意的是,此时我将springboot的版本号2.0.4更新为1.5.13了

<?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.api</groupId>
	<artifactId>SpringBootMybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>SpringBootMybatis</name>
	<description>Demo project for Spring Boot</description>

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

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<!-- myBatis -->
		<mybatis.version>3.2.8</mybatis.version>
		<mybatis-generator-core.version>1.3.2</mybatis-generator-core.version>
		<mybatis-spring.version>1.2.2</mybatis-spring.version>
		<mysql-connector-java.version>5.1.34</mysql-connector-java.version>
		<!-- mybatis pagehelper -->
		<pagehelper.version>3.6.3</pagehelper.version>
	</properties>

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

		<!-- MySql驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- MyBatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>${mybatis-spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>${mybatis-generator-core.version}</version>
		</dependency>
		<!-- mybatis pagehelper 分页查询插件-->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>${pagehelper.version}</version>
		</dependency>
		<!-- datasource  -->
		<dependency>
			<groupId>com.zaxxer</groupId>
			<artifactId>HikariCP-java6</artifactId>
			<version>2.3.13</version>
			<exclusions>
				<exclusion>
					<artifactId>tools</artifactId>
					<groupId>com.sun</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- javax -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
		</dependency>

	</dependencies>

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


</project>

新增java代码用于解析mybatis配置

package com.example.api.mybatis;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Arrays;

@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {

	private RelaxedPropertyResolver propertyResolver;

	private static Logger log = LoggerFactory
			.getLogger(DataBaseConfiguration.class);

	private Environment env;

	@Override
	public void setEnvironment(Environment env) {
		this.env = env;
		this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
	}

	@Bean(destroyMethod = "shutdown")
	public DataSource dataSource() {
		log.debug("Configruing DataSource");
		if (propertyResolver.getProperty("url") == null
				&& propertyResolver.getProperty("databaseName") == null) {
			log.error("Your database conncetion pool configuration is incorrct ! The application "
					+ "cannot start . Please check your jdbc");
			Arrays.toString(env.getActiveProfiles());
			throw new ApplicationContextException(
					"DataBase connection pool is not configured correctly");
		}
		HikariConfig config = new HikariConfig();
		config.setDataSourceClassName(propertyResolver
				.getProperty("dataSourceClassName"));
		if (propertyResolver.getProperty("url") == null
				|| "".equals(propertyResolver.getProperty("url"))) {
			config.addDataSourceProperty("databaseName",
					propertyResolver.getProperty("databaseName"));
			config.addDataSourceProperty("serverName",
					propertyResolver.getProperty("serverName"));
		} else {
			config.addDataSourceProperty("url",
					propertyResolver.getProperty("url"));
		}
		config.setUsername(propertyResolver.getProperty("username"));
		config.setPassword(propertyResolver.getProperty("password"));
		if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
				.equals(propertyResolver.getProperty("dataSourceName"))) {
			config.addDataSourceProperty("cachePrepStmts",
					propertyResolver.getProperty("cachePrepStmts"));
			config.addDataSourceProperty("prepStmtCacheSize",
					propertyResolver.getProperty("prepStmtsCacheSize"));
			config.addDataSourceProperty("prepStmtCacheSqlLimit",
					propertyResolver.getProperty("prepStmtCacheSqlLimit"));
			config.addDataSourceProperty("userServerPrepStmts",
					propertyResolver.getProperty("userServerPrepStmts"));
		}
		return new HikariDataSource(config);
	}

}
package com.example.api.mybatis;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.inject.Inject;
import javax.sql.DataSource;

//import javax.persistence.EntityManager;

@Configuration
@ConditionalOnClass({ EnableTransactionManagement.class})
@AutoConfigureAfter({ DataBaseConfiguration.class })
@MapperScan(basePackages={"com.example.api.*.dao"})
public class MybatisConfiguration implements EnvironmentAware {

	private static Log logger = LogFactory.getLog(MybatisConfiguration.class);

	private RelaxedPropertyResolver propertyResolver;

	@Inject
	private DataSource dataSource;

	@Override
	public void setEnvironment(Environment environment) {
		this.propertyResolver = new RelaxedPropertyResolver(environment,
				"mybatis.");
	}

	@Bean
	@ConditionalOnMissingBean
	public SqlSessionFactory sqlSessionFactory() {
		try {
			SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
			sessionFactory.setDataSource(dataSource);
			sessionFactory.setTypeAliasesPackage(propertyResolver
					.getProperty("typeAliasesPackage"));
			sessionFactory
					.setMapperLocations(new PathMatchingResourcePatternResolver()
							.getResources(propertyResolver
									.getProperty("mapperLocations")));
			sessionFactory
					.setConfigLocation(new DefaultResourceLoader()
							.getResource(propertyResolver
									.getProperty("configLocation")));

			return sessionFactory.getObject();
		} catch (Exception e) {
			logger.warn("Could not confiure mybatis session factory");
			return null;
		}
	}

	@Bean
	@ConditionalOnMissingBean
	public DataSourceTransactionManager transactionManager() {
		return new DataSourceTransactionManager(dataSource);
	}
}

配置文件及依赖导入完成,接下来就是开始验证,如下图所示,请开始你的表演

controller代码如下:

package com.example.api.testMybatis.controller;

import com.example.api.testMybatis.dao.UserMapper;
import com.example.api.testMybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by XieZhiXin on 2018/8/8.
 */
@RestController
@RequestMapping(value="/mybatis", produces = "application/json; charset=UTF-8")
public class MybatisController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapperDao;

    @GetMapping( "/user/{userid}")
    public String getUserName(@PathVariable(value = "userid") Integer userid) {

        String  name=userService.getUserName(userid);
        //String  nam=userMapperDao.getUserNameById(userid);
        return "获取到的用户姓名为:"+name;
    }

}

dao层代码如下:

package com.example.api.testMybatis.dao;

/**
 * Created by XieZhiXin on 2018/8/8.
 */
public interface UserMapper {

    String getUserNameById(int stu_id);
}

service代码如下:

package com.example.api.testMybatis.service;

/**
 * Created by XieZhiXin on 2018/8/8.
 */
public interface UserService {

    String getUserName(int stu_id);
}

serviceImpl代码如下:

package com.example.api.testMybatis.service.impl;


import com.example.api.testMybatis.dao.UserMapper;
import com.example.api.testMybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by XieZhiXin on 2018/8/8.
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapperDao;

    @Override
    public String getUserName(int stu_id)
    {
        String  name=userMapperDao.getUserNameById(stu_id);
        return name;
    }
}

mapper.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.api.testMybatis.dao.UserMapper" >

<select id="getUserNameById" resultType="String">
    SELECT stu_name from student where stu_id=#{0};
</select>

</mapper>

接下来就是见证奇迹的时刻:右键运行SpringBootMybatisApplication方法,心想着终于大功告成了,噗!!!!!如下图所示

Description:

Field userMapperDao in com.example.api.testMybatis.service.impl.UserServiceImpl required a bean of type 'com.example.api.testMybatis.dao.UserMapper' that could not be found.
Action:

Consider defining a bean of type 'com.example.api.testMybatis.dao.UserMapper' in your configuration.

在满怀希望感觉大功告成的时候突然出现这个问题了,然后一脸懵逼,怎么可能,应该是没有问题的,然后我马上百度这个问题,springboot启动找不到mapper,然后搜索出的结果也是很多,有的是说要在application中增加注解@MapperScan(),然而回首代码,我已经在java代码中增加了@MapperScan(basePackages={"com.example.api.*.dao"}),现在说一下@MapperScan注解,此注解功能是用于扫描package下所有的mapper文件,既然我已经增加这个注解为什么还是扫描加载补到mapper文件呢,一直百度查询也查询无果,也不知道哪来的灵感,看着目录结构总觉得有点不大对劲,如下图所示

application启动方法放在了api内部,然后将此方法移出一层,右键启动,nice!终于启动成功了。

运行结果如下图所示:

至于为什么不能放在第二层目录下,那好,我告诉你,因为它就是不能放在里面,SpringBoot启动类启动后会扫描其包及其子包的,作为springboot的main必须要放在最外层。

虽然按照我的步骤完全可以完成springboot和mybatis的整合,但是实际从开始搭建到测试完成,我中间还是碰到了很多很多的问题,这里面的坑实在是太多了,世上本没有坑,都是自己给自己挖的坑!遇到问题去一步步解决即可,只有遇到问题才能发现问题,通过解决问题才能有所收获!希望文章对大家有所帮助,

源码地址:https://github.com/1419459573/Spring-Boot

今天先到这里了,整理的头大,还有期间遇到的其他问题没来得及整理。后续更新!

新开通一个个人微信公众号,感兴趣的朋友可以扫描点击关注下哦,在接下的工作中的所感所想、优质资源也会在公众号内更新,希望我们可以一起交流共同进步

* 感谢您的阅读。如果感觉文章对您有用,麻烦您动动手指点个赞,以资鼓励。谢谢!

展开阅读全文

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