继上篇文章:Spring-Boot入门之环境搭建。此次咱们整合SpringBoot-Mybatis实现简单的CRUD业务。html
需求:前端
项目源码请看个人Github仓库:教你优雅的入门Spring Boot框架vue
若是以为不错就点击右上角star鼓励一下笔者吧(#^.^#)java
技术栈mysql
测试环境git
项目设计github
. ├── db -- sql文件 ├── mvnw ├── mvnw.cmd ├── pom.xml -- 项目依赖 └── src ├── main │ ├── java │ │ └── cn │ │ └── tycoding │ │ ├── SpringbootApplication.java -- Spring Boot启动类 │ │ ├── controller -- MVC-WEB层 │ │ ├── entity -- 实体类 │ │ ├── interceptor -- 自定义拦截器 │ │ ├── mapper -- mybatis-Mapper层接口 │ │ └── service -- service业务层 │ └── resources -- Spring Boot资源文件 │ ├── application.yml -- Spring Boot核心配置文件 │ ├── mapper -- Mybatis Mapper层配置文件 │ ├── static -- 前端静态文件 │ └── templates -- Thymeleaf模板引擎识别的HTML页面目录 └── test -- 测试文件
开始实战Spring Boot项目,首先,你须要将Spring Boot工程搭建出来。web
Spring Boot工程搭建请看个人博客:Spring Boot入门之工程搭建redis
Spring Boot提供了不少应用启动器,分别用来支持不一样的功能,说白了就是pom.xml
中的依赖配置,由于Spring Boot的自动化配置特性,咱们并不需再考虑项目依赖版本问题,使用Spring Boot的应用启动器,它能自动帮咱们将相关的依赖所有导入到项目中。spring
咱们这里介绍几个常见的应用启动器:
spring-boot-starter
: Spring Boot的核心启动器,包含了自动配置、日志和YAMLspring-boot-starter-aop
: 支持AOP面向切面编程的功能,包括spring-aop和AspecJspring-boot-starter-cache
: 支持Spring的Cache抽象spring-boot-starter-artermis
: 经过Apache Artemis支持JMS(Java Message Service)的APIspring-boot-starter-data-jpa
: 支持JPAspring-boot-starter-data-solr
: 支持Apache Solr搜索平台,包括spring-data-solrspring-boot-starter-freemarker
: 支持FreeMarker模板引擎spring-boot-starter-jdbc
: 支持JDBC数据库spring-boot-starter-Redis
: 支持Redis键值储存数据库,包括spring-redisspring-boot-starter-security
: 支持spring-securityspring-boot-starter-thymeleaf
: 支持Thymeleaf模板引擎,包括与Spring的集成spring-boot-starter-web
: 支持全栈式web开发,包括tomcat和Spring-WebMVCspring-boot-starter-log4j
: 支持Log4J日志框架spring-boot-starter-logging
: 引入Spring Boot默认的日志框架LogbackSpring Boot项目(即Maven项目),固然拥有最基础的Maven项目结构。除此以外:
Spring Boot项目中不包含webapp(webroot)目录。
Spring Boot默认提供的静态资源目录须要置于classpath下,且其下的目录名称要符合必定规定。
Spring Boot默认不提倡用XML配置文件,主张使用YML做为配置文件格式,YML有更简洁的语法。固然也可使用.properties做为配置文件格式。
Spring Boot官方推荐使用Thymeleaf做为前端模板引擎,而且Thymeleaf默认将templates做为静态页面的存放目录(由配置文件指定)。
Spring Boot默认将resources
做为静态资源的存放目录,存放前端静态文件、项目配置文件。
Spring Boot规定resources
下的子级目录名要符合必定规则,通常咱们设置resources/static
为前端静态(JS,CSS)的存放目录;设置resources/templates
做为HTML页面的存放目录。
Spring Boot指定的Thymeleaf模板引擎文件目录/resources/templates
是受保护的目录,想当与以前的WEB-INF文件夹,里面的静态资源不能直接访问,通常咱们经过Controller映射访问。
建议将Mybatis-Mapper的XML映射文件放于resources/
目录下,我这里设为resources/mapper
目录,且src/main/java/Mapper
下的Mapper层接口要使用@Mapper
注解标识,否则mybatis找不到接口对应的XML映射文件。
SpringBootApplication.java
为项目的启动器类,项目不须要部署到Tomcat上,由SpringBoot提供的服务器部署项目(运行启动器类便可);且SpringBoot会自动扫描该启动器同级和子级下用注解标识的Bean。
Spring Boot不建议使用JSP页面,若是想使用,请自行百度解决办法。
上面说了Spring Boot提供的存放HTML静态页面的目录resources/templates
是受保护的目录,访问其中的HTML页面要经过Controller映射,这就间接规定了你须要配置Spring的视图解析器,且Controller类不能使用@RestController
标识。
首先: 我想特殊强调的是:SpringBoot不是对Spring功能上的加强,而是提供了一种快速使用Spring的方式。必定要切记这一点。
学习SpringBoot框架,只是为了更简便的使用Spring框架,咱们在SSM阶段学习的知识如今放在Spring Boot框架上开发是彻底适用的,咱们学习的大多数是SpringBoot的自动化配置方式。
由于Spring Boot框架的一大优点就是自动化配置,从pom.xml的配置中就能明显感觉到。
因此这里推荐一下我以前的SSM阶段整合项目: SSM详细入门整合案例 SSM+Redis+Shiro+Solr+Vue.js整合项目
本项目的依赖文件请看Github仓库:spring-boot/pom.xml
本项目数据库表设计请看GitHub仓库:spring-boot/db/
请运行项目前,先把数据库表结构建好
以前已经说过:SpringBoot框架不是对Spring功能上的加强,而是提供了一种快速使用Spring的方式
因此说,SpringBoot整合Mybatis的思想和Spring整合Mybatis的思想基本相同,不一样之处有两点:
1.Mapper接口的XML配置文件变化。以前咱们使用Mybatis接口代理开发,规定Mapper映射文件要和接口在一个目录下;而这里Mapper映射文件置于resources/mapper/
下,且置于src/main/java/
下的Mapper接口须要用@Mapper
注解标识,否则映射文件与接口没法匹配。
2.SpringBoot建议使用YAML做为配置文件,它有更简便的配置方式。因此整合Mybatis在配置文件上有必定的区别,但最终都是那几个参数的配置。
关于YAML的语法请自行百度,我这里也仅仅是知足基本的配置需求,不涉及那种不易理解的语法。
本例详细代码请看GitHub仓库:spring-boot/resources/application.yml
在Spring阶段用XML配置mybatis无非就是配置:1.链接池;2.数据库url链接;3.mysql驱动;4.其余初始化配置
spring: datasource: name: springboot type: com.alibaba.druid.pool.DruidDataSource #druid相关配置 druid: #监控统计拦截的filters filter: stat #mysql驱动 driver-class-name: com.mysql.jdbc.Driver #基本属性 url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true username: root password: root #配置初始化大小/最小/最大 initial-size: 1 min-idle: 1 max-active: 20 #获取链接等待超时时间 max-wait: 60000 #间隔多久进行一次检测,检测须要关闭的空闲链接 time-between-eviction-runs-millis: 60000 #mybatis配置 mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: cn.tycoding.entity
注意:空格表明节点层次;注释部分用#
标记
解释
咱们实现的是spring-mybatis的整合,包含mybatis的配置以及datasource数据源的配置固然属于spring配置中的一部分,因此须要在spring:
下。
mapper-locations
至关于XML中的<property name="mapperLocations">
用来扫描Mapper层的配置文件,因为咱们的配置文件在resources
下,因此须要指定classpath:
。
type-aliases-package
至关与XML中<property name="typeAliasesPackase">
别名配置,通常取其下实体类类名做为别名。
datasource
数据源的配置,name
表示当前数据源的名称,相似于以前的<bean id="dataSource">
id属性,这里能够任意指定,由于咱们无需关注Spring是怎么注入这个Bean对象的。
druid
表明本项目中使用了阿里的druid链接池,driver-class-name:
至关于XML中的<property name="driverClassName">
;url
表明XML中的<property name="url">
;username
表明XML中的<property name="username">
;password
表明XML中的<property name="password">
;其余druid的私有属性配置再也不解释。这里注意druid链接池和c3p0链接池在XML的<property>的name中就不一样,在此处SpringBoot的配置中固然名称也不一样。
若是Spring整合Mybtis的配置你已经很熟悉了,那么这个配置你确定也很眼熟,从英文名称上就很容易区分出来。这里须要注意的就是YAML语法规定不一样行空格表明了不一样的层级结构。
既然完成了SpringBoot-Mybatis基本配置下面咱们实战讲解如何实现基本的CRUD。
1.在
src/main/java/cn/tycoding/entity/
下新建User.java
实体类
public class User implements Serializable { private Long id; //编号 private String username; //用户名 private String password; //密码 //getter/setter }
2.在
src/main/java/cn/tycoding/service/
下建立BaseService.java
通用接口,目的是简化service层接口基本CRUD方法的编写。
public interface BaseService<T> { // 查询全部 List<T> findAll(); //根据ID查询 List<T> findById(Long id); //添加 void create(T t); //删除(批量) void delete(Long... ids); //修改 void update(T t); }
以上就是我对Service层基本CRUD接口的简易封装,使用了泛型类,其继承接口指定了什么泛型,T就表明什么类。
3.在
src/main/java/cn/tycoding/service/
下建立UserService.java
接口:
public interface UserService extends BaseService<User> {}
4.在
src/main/java/cn/tycoding/service/impl/
下建立UserServiceImpl.java
实现类:
@Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> findAll() { return userMapper.findAll(); } //其余方法省略 }
5.在
src/main/java/cn/tycoding/mapper/
下建立UserMapper.java
Mapper接口类:
@Mapper public interface UserMapper { List<User> findAll(); }
如上,咱们必定要使用@Mapper
接口标识这个接口,否则Mybatis找不到其对应的XML映射文件。
6.在
src/main/resources/mapper/
下建立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="cn.tycoding.mapper.UserMapper"> <!-- 查询全部 --> <select id="findAll" resultType="cn.tycoding.entity.User"> SELECT * FROM tb_user </select> </mapper>
7.在
src/main/java/cn/tycoding/controller/admin/
下建立UserController.java
@RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/findAll") public List<User> findAll() { return userService.findAll(); } }
8.运行
src/main/java/cn/tycoding/SpringbootApplication.java
的main方法,启动springboot
在浏览器上访问localhost:8080/findAll
便可获得一串JSON数据。
看了上面一步步的讲解。你应该明白了,其实和SSM阶段的CRUD基本相同,这里我就再也不举例其余方法。
下面咱们讲解一下不一样的地方:
由于Thymeleaf指定的目录src/main/resources/templates/
是受保护的目录,其下的资源不能直接经过浏览器访问,可使用Controller映射的方式访问,怎么映射呢?
1.在application.yml中添加配置
spring: thymeleaf: prefix: classpath:/templates/ check-template-location: true suffix: .html encoding: UTF-8 mode: LEGACYHTML5 cache: false
指定Thymeleaf模板引擎扫描resources
下的templates
文件夹中已.html
结尾的文件。这样就实现了MVC中关于视图解析器的配置:
<!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean>
是否是感受方便不少呢?但这里须要注意的是:classpath:
后的目录地址必定要先加/
,好比目前的classpath:/templates/
。
2.在Controller添加映射方法
@GetMapping(value = {"/", "/index"}) public String index() { return "home/index"; }
这样,访问localhost:8080/index
将直接跳转到resources/templates/home/index.html
页面。
首先咱们须要在application.yml中配置pageHelper插件
pagehelper: pagehelperDialect: mysql reasonable: true support-methods-arguments: true
我这里使用了Mybatis的PageHelper分页插件,前端使用了ElementUI自带的分页插件:具体的教程请查看个人博客:SpringMVC+ElementUI实现分页查询
核心配置:
UserServiceImp.java
public PageBean findByPage(Goods goods, int pageCode, int pageSize) { //使用Mybatis分页插件 PageHelper.startPage(pageCode, pageSize); //调用分页查询方法,其实就是查询全部数据,mybatis自动帮咱们进行分页计算 Page<Goods> page = goodsMapper.findByPage(goods); return new PageBean(page.getTotal(), page.getResult()); }
这里涉及的无非就是SpringMVC的文件上传,详细的教程请参看个人博客:SpringMVC实现文件上传和下载
由于本项目中前端使用了ElementUI+Vue.JS技术,因此前端的文件上传和回显教程请看个人博客:SpringMVC+ElementUI实现图片上传和回显
除了代码的编写,这里还要在application.yml中进行配置:
spring: servlet: multipart: max-file-size: 10Mb max-request-size: 100Mb
这就至关于SpringMVC的XML配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="500000"/> </bean>
本项目,咱们先不整合Shiro和Spring Security这些安全框架,使用Spring AOP切面编程思想实现简单的登陆拦截:
@Component @Aspect public class MyInterceptor { @Pointcut("within (cn.tycoding.controller..*) && !within(cn.tycoding.controller.admin.LoginController)") public void pointCut() { } @Around("pointCut()") public Object trackInfo(ProceedingJoinPoint joinPoint) throws Throwable { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); User user = (User) request.getSession().getAttribute("user"); if (user == null) { attributes.getResponse().sendRedirect("/login"); //手动转发到/login映射路径 } return joinPoint.proceed(); } }
解释
关于Spring AOP的切面编程请自行百度,或者你也能够看个人博客:Spring AOP思想。咱们须要注意如下几点
必定要熟悉AspectJ的切点表达式,在这里:..*
表示其目录下的全部方法和子目录方法。
若是进行了登陆拦截,即在session中没有获取到用户的登陆信息,咱们可能须要手动转发到login
页面,这里访问的是login
映射。
基于2,必定要指定Object返回值,若AOP拦截的Controller return了一个视图地址,那么原本Controller应该跳转到这个视图地址的,可是被AOP拦截了,那么原来Controller仍会执行return,可是视图地址却找不到404了。
切记必定要调用proceed()方法,proceed():执行被通知的方法,如不调用将会阻止被通知的方法的调用,也就致使Controller中的return会404。
<br/>
若是你们有兴趣,欢迎你们加入个人Java交流技术群:671017003 ,一块儿交流学习Java技术。博主目前一直在自学JAVA中,技术有限,若是能够,会尽力给你们提供一些帮助,或是一些学习方法,固然群里的大佬都会积极给新手答疑的。因此,别犹豫,快来加入咱们吧!
<br/>
If you have some questions after you see this article, you can contact me or you can find some info by clicking these links.