由于工作上的需要,今天使用intellij搭建了SpringBoot+MyBatis+Gradle工程,借此机会记录一下搭建的步骤以及犯的一些错误。
示例代码:
https://github.com/lixiaodongisme/springboot_mybatis_gradle.git

一、搭建步骤

1.使用intellij新建一个工程
使用intellij搭建SpringBoot+MyBatis+Gradle工程
新建工程时选择Spring Initializr,然后点击next。

2.填写项目信息
使用intellij搭建SpringBoot+MyBatis+Gradle工程
Group和Artifact自己起名字填上就好。Type注意需要选Gradle Project,如果你是用Maven构建项目,那就选Maven对应的选项即可。打包方式记得选war包。然后点击Next。

3.选择依赖
使用intellij搭建SpringBoot+MyBatis+Gradle工程
根据你的需要选择依赖,选择的依赖会在右边显示,选好之后点击Next。

4.填写项目路径
使用intellij搭建SpringBoot+MyBatis+Gradle工程
这里没什么好说的,自己选择项目名称和路径即可。然后点击Finsh。

5.配置Gradle
使用intellij搭建SpringBoot+MyBatis+Gradle工程
上一步点击Finsh后,会出现Gradle的配置界面。勾选Use auto-import后,以后添加了依赖后,gradle会自动下载,比较方便。Gradle home选择Gradle在本地的安装位置即可。之后点击OK。

6.项目构建
使用intellij搭建SpringBoot+MyBatis+Gradle工程
进入之后我们会看到IDEA的Build窗口,里面显示正在构建Gradle项目,同时也会去下载依赖。但是如果不开v*n,可能会失败,这时我们需要修改build.gradle文件,找到如下代码块:

buildscript {
    ext {
        springBootVersion = '2.0.6.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

将其中repositories{}中的内容修改为阿里云的maven仓库地址:

repositories {
        maven {
            url "http://maven.aliyun.com/nexus/content/groups/public/"
        }
    }

这样稍等片刻,等依赖下载完成后,项目就会构建成功。构建成功后的项目结构如图所示:
使用intellij搭建SpringBoot+MyBatis+Gradle工程
7.整合MyBatis
因为当前我使用的是MySql,本次就以MsSql数据库为例。首先在application.properties中配置数据库。

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driverClassName = com.mysql.jdbc.Driver

然后在resource文件夹下新建一个mapper文件夹和mybatis-config.xml文件,分别用来放置mapper.xml文件和配置MyBatis。
使用intellij搭建SpringBoot+MyBatis+Gradle工程
mybatis-confi的内容为:

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

	<!-- 全局参数 -->
	<settings>
		<!-- 使全局的映射器启用或禁用缓存。 -->
		<setting name="cacheEnabled" value="false"/>
		
		<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->
		<setting name="lazyLoadingEnabled" value="false"/>
		
		<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 -->
		<setting name="aggressiveLazyLoading" value="true"/>
		
		<!-- 是否允许单条sql 返回多个数据集  (取决于驱动的兼容性) default:true -->
		<setting name="multipleResultSetsEnabled" value="true"/>
		
		<!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true -->
		<setting name="useColumnLabel" value="true"/>
		
		<!-- 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。  default:false  -->
		<setting name="useGeneratedKeys" value="false"/>
		
		<!-- 指定 MyBatis 如何自动映射 数据基表的列 NONE:不隐射 PARTIAL:部分  FULL:全部  -->  
		<setting name="autoMappingBehavior" value="PARTIAL"/>
		
		<!-- 这是默认的执行类型  (SIMPLE: 简单; REUSE: 执行器可能重复使用prepared statements语句;BATCH: 执行器可以重复执行语句和批量更新)  -->
		<setting name="defaultExecutorType" value="SIMPLE"/>
		
		<!-- 使用驼峰命名法转换字段。 -->
		<setting name="mapUnderscoreToCamelCase" value="true"/>
		
		<!-- 设置本地缓存范围 session:就会有数据的共享  statement:语句范围 (这样就不会有数据的共享 ) defalut:session -->
        <setting name="localCacheScope" value="SESSION"/>
		
        <!-- 设置但JDBC类型为空时,某些驱动程序 要指定值,default:OTHER,插入空值时不需要指定类型 -->
        <setting name="jdbcTypeForNull" value="NULL"/>

		<!-- 设置但JDBC类型为空时,某些-->
        <setting name="logImpl" value="LOG4J" />
	</settings>

	<!-- 类型别名 -->
	<typeAliases>
		<typeAlias alias="User" type="com.example.demo.entity.User" />
	</typeAliases>

	<!-- 插件配置 -->
	<plugins>
		<plugin interceptor="xx.xx..." />
		<plugin interceptor="xx.xx..." />
    </plugins>
	
</configuration>

然后还需要在application.properties文件中配置一下mybatis,添加以下内容:

#mybatis配置文件位置
mybatis.config-location=classpath:mybatis-config.xml
#mapper文件位置
mybatis.mapper-locations=classpath:mapper/*.xml

至此,搭建工作就已经完成了,下来让我们写一些简单的代码来测试一下是否搭建成功。

8.编写代码
我们首先在数据库中准备一些测试数据:

create table user(
	id int(10) auto_increment primary key,
	name varchar(40) not null,
	password varchar(10) not null
)
insert into user values(1, 'Tom', '123456');
insert into user values(2, 'Jack', 'abcdef');

然后创建一个User对象:

public class User {
   private Integer id;
   private String name;
   private String password;

   public Integer getId() {
      return id;
   }

   public void setId(Integer id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }
}

之后我们就可以进行Dao层的开发了,个人还是喜欢使用传统的mapper.xml方式写SQL:

@Mapper
public interface IUserDao {
   List<User> getAll();
}

在刚才创建的mapper文件夹中创建对应的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.demo.dao.IUserDao">

    <resultMap id="userList" type="User">
        <result column="id" property="id" />
        <result column="name" property="name" />
        <result column="password" property="password" />
    </resultMap>
    
    <select id="getAll" resultMap="userList">
      SELECT * FROM USER;
   </select>
</mapper>

这里注意namespace一定要写正确,要和Dao层的接口对应起来。
然后是Controller层:

@RestController
@RequestMapping("/test")
public class UserController {
   @Autowired
   private IUserDao userDao;

   @GetMapping("/1")
   public String index(){
      return "Hello";
   }

   @RequestMapping("/2")
   public List<User> getAll() {
      return userDao.getAll();
   }
}

9.测试
此时我们运行Application类,按照我们的设想,这时候这一套框架应该就可以跑起来了,但是结果确报错了,我们看一下错误信息
使用intellij搭建SpringBoot+MyBatis+Gradle工程
可以很明确的看到,异常信息显示找不到log4j相关的类。查看build.gradle文件后发现,log4j相关的依赖IDEA并没有帮我们自动添加,那么我们在dependencies中手动添加如下依赖:

compile 'log4j:log4j:1.2.17'
compile 'org.slf4j:slf4j-api:1.7.7'

此时重新运行,在控制台看到如下所示,就说明SpringBoot启动成功了!
使用intellij搭建SpringBoot+MyBatis+Gradle工程
然后在浏览器中访问:localhost:8080/test/1和localhost:8080/test/2就可以看到效果了。
使用intellij搭建SpringBoot+MyBatis+Gradle工程
使用intellij搭建SpringBoot+MyBatis+Gradle工程
到此为止,我们的框架就搭建成功了!最终的项目结构如图所示:
使用intellij搭建SpringBoot+MyBatis+Gradle工程

10.遇到的一些问题
在刚开始的时候,由于用SpringMVC的习惯,在Controller层上使用的是@Controller注解,而并非@RequestController注解。这时从浏览器访问时,会出现Whitelabel Error Page错误,出现这个错误的原因是找不到对应的页面。所以应注意,SpringBoot的注解一定要使用正确。

相关文章: