当前位置:   article > 正文

搭建spring boot集成mybatis项目入门_java springboot+mybatis项目搭建

java springboot+mybatis项目搭建

已经很久没有写过博客了,正好这次趁着公司需要做一个新的项目的机会,我决定在新项目上使用spring boot来代替原来的spring框架。毕竟已经对那一大堆xml配置文件渐渐地产生了厌恶心理,正好spring boot的约定优于配置的理念可以在很大程度上解决我们的这个痛点。那下面我就来写写怎么使用spring boot来简化一个java web项目的开发吧。 对于spring项目的开发个人比较喜欢使用Spring tool suite这个开发工具来开发,下面的示例我也都是使用STS来展示的。

 1.创建spring boot项目,点击File菜单,选择new,然后选择Spring Starter Project 


2.输入项目名,包名,描述等必要信息,packaging选择jar,java版本选择1.8,使用Maven构建,填写完整后点击next进入下一步


3.选择spring boot的版本及相关依赖模块,这里我选择的是1.5.6这个最新的稳定版,开发模块选择了Web模块,前端模板选择Thymeleaf,数据库则选择MySQL及MyBatis模块,选择完成后点击finsh完成一个基本的spring boot项目的创建


OK,创建完成后的项目基本结构如下:


介绍一下,这里自动生成的SpringBootDemoApplication这个类为这个项目的启动类,spring boot项目在平时开发的时候就通过这个类的Main方法来启动。

对应maven的pom.xml文件内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.sm</groupId>
  6. <artifactId>spring-boot-demo</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>spring-boot-demo</name>
  10. <description>Demo project for Spring Boot</description>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>1.5.6.RELEASE</version>
  15. <relativePath/> <!-- lookup parent from repository -->
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.mybatis.spring.boot</groupId>
  25. <artifactId>mybatis-spring-boot-starter</artifactId>
  26. <version>1.3.0</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-web</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>mysql</groupId>
  38. <artifactId>mysql-connector-java</artifactId>
  39. <scope>runtime</scope>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-starter-test</artifactId>
  44. <scope>test</scope>
  45. </dependency>
  46. </dependencies>
  47. <build>
  48. <plugins>
  49. <plugin>
  50. <groupId>org.springframework.boot</groupId>
  51. <artifactId>spring-boot-maven-plugin</artifactId>
  52. </plugin>
  53. </plugins>
  54. </build>
  55. </project>

到这里我们已经把spring-boot项目基础框架搭建好了,是不是很简单,接下来我们要做的就是集成mybatis来做数据库访问层,并编写相应spring mvc接口和使用spring-boot官方推荐的模板引擎Thymeleaf来编写页面完成一个用户登录的过程。

首先我们需要对数据库进行配置,只需要我们在src/main/resources目录下的application.properties文件中配置你所用到的数据库的相应配置就可以了,我的配置如下:

#数据源配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456

#mybatis数据库字段开启驼峰转换
mybatis.configuration.map-underscore-to-camel-case=true

到这里我们就基本把Mybatis的配置都配置完成了,基本不需要多余的配置。

接下来我们需要在templates目录下编写页面(springboot默认使用templates目录存放页面,static目录存放静态资源,如js、css、img等),首选我们来写一个简单的登录页面login.html,代码如下:

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>登录页</title>
  6. <script th:src="@{js/jquery-3.2.1.js}"></script>
  7. </head>
  8. <body>
  9. <span th:text="${errorMessage}"></span>
  10. <form th:action="@{/doLogin}" method="post">
  11. <div><label> 账号 : <input type="text" name="username"/> </label></div>
  12. <div><label> 密码: <input type="password" name="password"/> </label></div>
  13. <div><input type="submit" value="登陆"/></div>
  14. </form>
  15. </body>
  16. </html>
注:这里面使用了一些thymeleaf模板的语法,其实这里的语法和jsp、freemarker以及velocity等模板的语法都大同小异,这里不做展开。

下面我们需要来编写这个登录操作的后台方法,具体代码如下:

  1. @Controller
  2. public class LoginController {
  3. @Autowired
  4. private UserMapper userMapper;
  5. @RequestMapping("/doLogin")
  6. public String login(HttpSession session, String username, String password, Model model) {
  7. if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
  8. model.addAttribute("errorMessage", "请输入用户名和密码");
  9. return "login";
  10. }
  11. UserEntity user = userMapper.queryUser(username, MD5Util.stringMD5(password));
  12. if (user == null) {
  13. model.addAttribute("errorMessage", "用户名或者密码错误");
  14. return "login";
  15. }
  16. session.setAttribute("user", user);
  17. model.addAttribute("user", user);
  18. return "index";
  19. }
  20. }
我在这里引用到了UserMapper这个dao接口,代码如下:

  1. public interface UserMapper {
  2. @Select("select * from user where username = #{username} and password = #{password}")
  3. UserEntity queryUser(@Param("username")String username, @Param("password")String password);
  4. }

这里我摒弃了传统的mybatis使用xml来写sql语句的方式,而是采用了注解的方式来写sql,这样可以在一定程度上减少我们去管理xml配置文件的工作量。不过从代码的简洁的角度来看的话,对于一些比较复杂的sql语句我还是比较建议使用xml的形式来编写,spring boot的话可以在application.properties文件中配置mybatis.config-location这个属性来配置mybatis的xml文件路径,这里不做展开。
那么使用注解的方式来编写sql就比较简洁了,可以直接集成在接口代码中。对于使用的注解的话,也很简单,select类型sql就是用@Select注解,insert类型sql就使用@Insert注解,以此类推,对应的括号里面就是相应的sql语句,sql里面参数使用的占位符与使用xml编写一致。
此外,为了能够让spring能够扫描到我们编写的UserMapper这个dao接口,需要我们在Spring boot的启动类上配置一个@MapperScan注解来告诉spring应该扫描的Mapper路径。

SpringBootDemoApplication类代码:

  1. @MapperScan("com.sm.demo.dao")
  2. @SpringBootApplication
  3. public class SpringBootDemoApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(SpringBootDemoApplication.class, args);
  6. }
  7. }

index.html代码:

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>主页</title>
  6. <script th:src="@{js/jquery-3.2.1.js}"></script>
  7. </head>
  8. <body>
  9. <span th:text="${user.realname}"></span><span>,你好,欢迎进入首页</span>
  10. </body>
  11. </html>
接下来我写了一个配置类WebMvcConfig,这个类继承了WebMvcConfiguerAdapter,用于对spring mvc进行配置。

  1. @Configuration
  2. public class WebMvcConfig extends WebMvcConfigurerAdapter {
  3. //路由直接返回页面配置
  4. @Override
  5. public void addViewControllers(ViewControllerRegistry registry) {
  6. registry.addViewController("/").setViewName("login");
  7. registry.addViewController("/login").setViewName("login");
  8. registry.addViewController("/index").setViewName("index");
  9. }
  10. //拦截器配置
  11. @Override
  12. public void addInterceptors(InterceptorRegistry registry) {
  13. registry.addInterceptor(new AuthInterceptor())
  14. .addPathPatterns("/**").excludePathPatterns("/login", "/doLogin");
  15. super.addInterceptors(registry);
  16. }
  17. }
其中@Configuration注解用于表明当前这个类是一个配置类。可以看到我重写了addViewControllers和addInterceptors两个方法。
首先addViewControllers方法就是配置了简单的页面跳转,按照以前传统的方式,我们完成页面的跳转是直接写在controller方法里面的,比如:

  1. @RequestMapping("/login")
  2. public String toLogin() {
  3. return "login";
  4. }

其实单纯页面的跳转是毫无业务逻辑的处理的,只是进行了简单的页面转向,但是我们却需要写四行代码,显得有点冗余。那现在我们通过配置类写在addViewControllers方法里则只需要一行代码,简化了配置。


其次addInterceptors则是配置了一个登陆拦截器,addPathPatterns就是配置需要拦截的路径,excludePathPatterns则是配置不需要拦截的路径。


到这里就基本完成了一个spring boot demo项目的开发工作,接下来我们只需要在SpringBootDemoApplication类上右击run as选择java application或者Spring boot app就可以等待项目运行完成了。
待项目启动成功后在浏览器中输入127.0.0.1:8080就可以得到如下界面(界面丑了点,请忽略)

然后输入用户名和密码就可以登录到主页面了:


备注:spring boot默认使用8080作为默认端口号,项目根路径默认为/,若需要修改可以在application.properties文件中进行配置,例如:

#配置端口
server.port=8081
#配置项目路径
server.context-path=/demo
至此,我们就完成了一个拥有基础功能的spring boot简单项目。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/243590
推荐阅读
相关标签
  

闽ICP备14008679号