集成mybatis的springboot项目和SSM框架的用法差不多,区别在于配置上简化了很多,用好springboot的前提是需要掌握spring,springMVC的用法。
1, 如果是低版本的eclipse或者myeclipse,登陆https://start.spring.io/创建springboot的demo:
如果是使用idea:
选择好之后点击next:
选择完毕之后点击next,再点击finish。
PS:要支持SpringMVC的功能,在选择依赖的时候需要加入Spring Web:
2, spring项目结构:
3, 开发项目,在启动类所在的目录新建对应的controller、service、dao、dto等包:
PS:所有需要托管给spring的类都必须放在启动类所在的目录下,不然springboot无法扫描到。
4, 在controller包下面新建一个类TestController:
启动springboot,访问localhost:8080/hello可以看到:
PS:springboot项目可以打包成jar来单独运行(因为内置了tomcat),也可以打包成war放入tomcat运行。
5, 添加或者覆盖springboot的默认配置:
Springboot配置属性值的方式有多种:包括命令行参数、环境变量、application.properties、application.yml,其中最常用的是application.yml。
我们以application.yml为例。
修改默认监听的端口号为80:
注意port后面冒号紧跟一个空格。
PS:如果配置文件为application.properties,则需要写成server.port=80.
6, 集成mybaitsi,在pom.xml中添加:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.12</version>
<scope>runtime</scope>
</dependency>
在application.yml添加数据库连接的配置信息:
7, 在resource目录下新建一个mapper目录,之后在mapper目录下新建TestMapper.xml
在application.yml添加mybatis相关配置:
,8,在service.impl包下新建一个TestServiceImpl类
8, 在controller包下的TestController类添加如下代码:
启动后在浏览器输入http://localhost/test即可。如下图: