最全面的springBoot集成mybatis+mysql项目搭建经验分享

 

大家都知道,现在Spring框架几乎无处不用,目前最新版本据说是Spring5,现在常用的基本还是Spring4.X,很多公司甚至用的还是Spring3.x,而Spring领域其中最好用的莫过于SpringBoot,这是从SpringMVC衍变出来的,本质还是SpringMVC,但是要比SpringMVC好用的多,因为很好用,所以笔者闲暇之际用SpringBoot从头至尾摸索着搭建了一个案例,分享出来,希望对感兴趣的朋友有所帮助。废话不说了,进入主题,直接分享案例搭建全流程。

本项目使用的环境:

  • 开发工具:Intellij IDEA 2017.1.3
  • jdk:1.8.0_51
  • maven:3.5.2

额外功能

  • mybatis generator 自动生成代码插件

步骤: 

 

  • 1.创建一个springboot项目: 
  • 2.创建项目的文件结构以及jdk的版本 
  • 3.选择项目所需要的依赖
  • 选择持久化框架的依赖
  • 然后点击finish
  • 5.项目结构如下:
  • 6.查看文件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.  
    6. <groupId>com.ocean</groupId>

    7. <artifactId>springboot-mybatis-demo</artifactId>

    8. <version>0.0.1-SNAPSHOT</version>

    9. <packaging>jar</packaging>

    10.  
    11. <name>springboot-mybatis-demo</name>

    12. <description>Demo project for Spring Boot</description>

    13.  
    14. <parent>

    15. <groupId>org.springframework.boot</groupId>

    16. <artifactId>spring-boot-starter-parent</artifactId>

    17. <version>1.5.10.RELEASE</version>

    18. <relativePath/> <!-- lookup parent from repository -->

    19. </parent>

    20.  
    21. <properties>

    22. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    23. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    24. <java.version>1.8</java.version>

    25. </properties>

    26.  
    27. <dependencies>

    28. <dependency>

    29. <groupId>org.springframework.boot</groupId>

    30. <artifactId>spring-boot-starter-jdbc</artifactId>

    31. </dependency>

    32. <dependency>

    33. <groupId>org.mybatis.spring.boot</groupId>

    34. <artifactId>mybatis-spring-boot-starter</artifactId>

    35. <version>1.3.1</version>

    36. </dependency>

    37. <dependency>

    38. <groupId>org.springframework.boot</groupId>

    39. <artifactId>spring-boot-starter-web</artifactId>

    40. </dependency>

    41.  
    42. <dependency>

    43. <groupId>mysql</groupId>

    44. <artifactId>mysql-connector-java</artifactId>

    45. <version>5.1.6</version>

    46. </dependency>

    47. <dependency>

    48. <groupId>org.springframework.boot</groupId>

    49. <artifactId>spring-boot-starter-test</artifactId>

    50. <scope>test</scope>

    51. </dependency>

    52. </dependencies>

    53.  
    54. <build>

    55. <plugins>

    56. <plugin>

    57. <groupId>org.springframework.boot</groupId>

    58. <artifactId>spring-boot-maven-plugin</artifactId>

    59. </plugin>

    60. <!-- mybatis generator 自动生成代码插件 -->

    61. <plugin>

    62. <groupId>org.mybatis.generator</groupId>

    63. <artifactId>mybatis-generator-maven-plugin</artifactId>

    64. <version>1.3.1</version>

    65. <configuration>

    66. <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>

    67. <overwrite>true</overwrite>

    68. <verbose>true</verbose>

    69. </configuration>

    70. </plugin>

    71. </plugins>

    72. </build>

    73. </project>


    7.本案例不使用application.properties文件 而使用更加简洁的application.yml文件。将resource文件夹下原有的application.properties文件删除,创建application.yml配置文件(备注:其实SpringBoot底层会把application.yml文件解析为application.properties), 文件的内容如下(此处只配置最基本的):
  •  
    1. server:

    2. port: 8080

    3.  
    4. spring:

    5. datasource:

    6. name: test

    7. url: jdbc:mysql://127.0.0.1:3306/chenyun01

    8. username: root

    9. password: root

    10. driver-class-name: com.mysql.jdbc.Driver

    11. mybatis:

    12. mapper-locations: classpath:mapping/*Mapper.xml

    13. type-aliases-package: com.ocean.pojo

  • 8.创建数据库:
  • 在mysql(此处用SQLyog客户端)下创建数据库chenyun01,新建数据表userInfo,插入2条数据,结构如下

  •  
  • 9.配置mybatis generator 自动生成代码插件
  • 配置pom.xml中generator 插件所对应的配置文件 ${basedir}/src/main/resources/generator/generatorConfig.xml
  •  
    1. <?xml version="1.0" encoding="UTF-8"?>

    2. <!DOCTYPE generatorConfiguration

    3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

    4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

    5. <generatorConfiguration>

    6. <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->

    7. <classPathEntry location="D:\dataSourceDriver\mysql-connector-java-5.1.6-bin.jar"/>

    8. <context id="DB2Tables" targetRuntime="MyBatis3">

    9. <commentGenerator>

    10. <property name="suppressDate" value="true"/>

    11. <!-- 是否去除自动生成的注释 true:是 : false:否 -->

    12. <property name="suppressAllComments" value="false"/>

    13. </commentGenerator>

    14. <!--数据库连接驱动类,URL,用户名、密码 -->

    15. <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/chenyun01" userId="root" password="root">

    16. </jdbcConnection>

    17. <javaTypeResolver>

    18. <property name="forceBigDecimals" value="false"/>

    19. </javaTypeResolver>

    20. <!-- 生成(实体)模型的包名和位置-->

    21. <javaModelGenerator targetPackage="com.ocean.pojo" targetProject="src">

    22. <property name="enableSubPackages" value="true"/>

    23. <property name="trimStrings" value="true"/>

    24. </javaModelGenerator>

    25. <!-- 生成XML映射文件的包名和位置-->

    26. <sqlMapGenerator targetPackage="resources.mapping" targetProject="src">

    27. <property name="enableSubPackages" value="true"/>

    28. </sqlMapGenerator>

    29. <!-- 生成DAO接口的包名和位置-->

    30. <javaClientGenerator type="XMLMAPPER" targetPackage="com.ocean.dao" targetProject="src">

    31. <property name="enableSubPackages" value="true"/>

    32. </javaClientGenerator>

    33. <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->

    34. <table tableName="userInfo" domainObjectName="UserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>

    35. </context>

    36. </generatorConfiguration>

     
    • 自动生成代码:点击run----> Edit Configurations
    • 添加配置
    • 运行
    • 最后生成的项目结构:
    • 10.我们还需要修改有点东西,因为生成的类中的路径写了全路径,所以我们要把前面多余的(main.java.)删掉:
    • 生成的接口文件UserMapper.java
       
      1. package com.ocean.dao;

      2. import com.ocean.pojo.UserInfo;

      3.  
      4. import java.util.List;

      5.  
      6. public interface UserInfoMapper {

      7. /**

      8. * This method was generated by MyBatis Generator.

      9. * This method corresponds to the database table userinfo

      10. *

      11. * @mbggenerated

      12. */

      13. int insert(UserInfo record);

      14.  
      15. /**

      16. * This method was generated by MyBatis Generator.

      17. * This method corresponds to the database table userInfo

      18. *

      19. * @mbggenerated

      20. */

      21. int insertSelective(com.ocean.pojo.UserInfo record);

      22. //这个方式我自己单独加的方法

      23. List findAllUser();

      24. }

    • 模型(POJO)UserInfo.java
    •  
      1. package com.ocean.pojo;

      2.  
      3. public class UserInfo {

      4. /**

      5. * This field was generated by MyBatis Generator.

      6. * This field corresponds to the database column userinfo.userId

      7. *

      8. * @mbggenerated

      9. */

      10. private Integer userid;

      11.  
      12. /**

      13. * This field was generated by MyBatis Generator.

      14. * This field corresponds to the database column userinfo.userName

      15. *

      16. * @mbggenerated

      17. */

      18. private String username;

      19.  
      20. /**

      21. * This field was generated by MyBatis Generator.

      22. * This field corresponds to the database column userinfo.phone

      23. *

      24. * @mbggenerated

      25. */

      26. private String phone;

      27.  
      28. /**

      29. * This field was generated by MyBatis Generator.

      30. * This field corresponds to the database column userinfo.sex

      31. *

      32. * @mbggenerated

      33. */

      34. private String sex;

      35.  
      36. /**

      37. * This method was generated by MyBatis Generator.

      38. * This method returns the value of the database column userinfo.userId

      39. *

      40. * @return the value of userinfo.userId

      41. *

      42. * @mbggenerated

      43. */

      44. public Integer getUserid() {

      45. return userid;

      46. }

      47.  
      48. /**

      49. * This method was generated by MyBatis Generator.

      50. * This method sets the value of the database column userinfo.userId

      51. *

      52. * @param userid the value for userinfo.userId

      53. *

      54. * @mbggenerated

      55. */

      56. public void setUserid(Integer userid) {

      57. this.userid = userid;

      58. }

      59.  
      60. /**

      61. * This method was generated by MyBatis Generator.

      62. * This method returns the value of the database column userinfo.userName

      63. *

      64. * @return the value of userinfo.userName

      65. *

      66. * @mbggenerated

      67. */

      68. public String getUsername() {

      69. return username;

      70. }

      71.  
      72. /**

      73. * This method was generated by MyBatis Generator.

      74. * This method sets the value of the database column userinfo.userName

      75. *

      76. * @param username the value for userinfo.userName

      77. *

      78. * @mbggenerated

      79. */

      80. public void setUsername(String username) {

      81. this.username = username == null ? null : username.trim();

      82. }

      83.  
      84. /**

      85. * This method was generated by MyBatis Generator.

      86. * This method returns the value of the database column userinfo.phone

      87. *

      88. * @return the value of userinfo.phone

      89. *

      90. * @mbggenerated

      91. */

      92. public String getPhone() {

      93. return phone;

      94. }

      95.  
      96. /**

      97. * This method was generated by MyBatis Generator.

      98. * This method sets the value of the database column userinfo.phone

      99. *

      100. * @param phone the value for userinfo.phone

      101. *

      102. * @mbggenerated

      103. */

      104. public void setPhone(String phone) {

      105. this.phone = phone == null ? null : phone.trim();

      106. }

      107.  
      108. /**

      109. * This method was generated by MyBatis Generator.

      110. * This method returns the value of the database column userinfo.sex

      111. *

      112. * @return the value of userinfo.sex

      113. *

      114. * @mbggenerated

      115. */

      116. public String getSex() {

      117. return sex;

      118. }

      119.  
      120. /**

      121. * This method was generated by MyBatis Generator.

      122. * This method sets the value of the database column userinfo.sex

      123. *

      124. * @param sex the value for userinfo.sex

      125. *

      126. * @mbggenerated

      127. */

      128. public void setSex(String sex) {

      129. this.sex = sex == null ? null : sex.trim();

      130. }

      131. }

      对于映射文件UserInfoMapper.xml,删除多余的“main.java.”字符,配置xml的namespace
    • 如果有的人的xml里的sql语句有黄色的背景,真心看不下去时(解决方案按照下图):
    • UserMapper.xml
       
      1. <?xml version="1.0" encoding="UTF-8"?>

      2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

      3. <mapper namespace="com.ocean.dao.UserInfoMapper">

      4. <resultMap id="BaseResultMap" type="com.ocean.pojo.UserInfo">

      5. <!--

      6. WARNING - @mbggenerated

      7. This element is automatically generated by MyBatis Generator, do not modify.

      8. -->

      9. <result column="userId" jdbcType="INTEGER" property="userid" />

      10. <result column="userName" jdbcType="VARCHAR" property="username" />

      11. <result column="phone" jdbcType="VARCHAR" property="phone" />

      12. <result column="sex" jdbcType="VARCHAR" property="sex" />

      13. </resultMap>

      14. <insert id="insert" parameterType="com.ocean.pojo.UserInfo">

      15. <!--

      16. WARNING - @mbggenerated

      17. This element is automatically generated by MyBatis Generator, do not modify.

      18. -->

      19. insert into userinfo (userId, userName, phone,

      20. sex)

      21. values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR},

      22. #{sex,jdbcType=VARCHAR})

      23. </insert>

      24. <insert id="insertSelective" parameterType="com.ocean.pojo.UserInfo">

      25. <!--

      26. WARNING - @mbggenerated

      27. This element is automatically generated by MyBatis Generator, do not modify.

      28. -->

      29. insert into userinfo

      30. <trim prefix="(" suffix=")" suffixOverrides=",">

      31. <if test="userid != null">

      32. userId,

      33. </if>

      34. <if test="username != null">

      35. userName,

      36. </if>

      37. <if test="phone != null">

      38. phone,

      39. </if>

      40. <if test="sex != null">

      41. sex,

      42. </if>

      43. </trim>

      44. <trim prefix="values (" suffix=")" suffixOverrides=",">

      45. <if test="userid != null">

      46. #{userid,jdbcType=INTEGER},

      47. </if>

      48. <if test="username != null">

      49. #{username,jdbcType=VARCHAR},

      50. </if>

      51. <if test="phone != null">

      52. #{phone,jdbcType=VARCHAR},

      53. </if>

      54. <if test="sex != null">

      55. #{sex,jdbcType=VARCHAR},

      56. </if>

      57. </trim>

      58. </insert>

      59. <!--我自己加的方法-->

      60. <select id="findAllUser" resultType="com.ocean.pojo.UserInfo">

      61. select * from USERINFO

      62. </select>

      63. </mapper>


      11.打开类SpringbootMybatisDemoApplication.java,这个是springboot的启动类。我们需要添加点东西:
    •  
      1. package com.ocean.springbootmybatisdemo;

      2.  
      3. import org.mybatis.spring.annotation.MapperScan;

      4. import org.springframework.boot.SpringApplication;

      5. import org.springframework.boot.autoconfigure.SpringBootApplication;

      6. import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;

      7. import org.springframework.boot.web.servlet.ErrorPage;

      8. import org.springframework.context.annotation.Bean;

      9. import org.springframework.context.annotation.ComponentScan;

      10. import org.springframework.http.HttpStatus;

      11.  
      12. @SpringBootApplication

      13. @MapperScan("com.ocean.dao")

      14. @ComponentScan(basePackages = {"com.ocean.*"})

      15. public class SpringbootMybatisDemoApplication {

      16.  
      17. public static void main(String[] args) {

      18. SpringApplication.run(SpringbootMybatisDemoApplication.class, args);

      19. }

      20. }

      12.到这里本案例的搭建工作都完成了,接下来就是直接在浏览器上测试: 
      首先看一下完成之后的文件的结构:
    • 现在把controller,service层的代码都写好(因做演示,此处控制器只写了一个方法):UserController.java

    •  

       
      1. package com.ocean.controller;

      2.  
      3. import com.ocean.service.IUserService;

      4. import org.springframework.beans.factory.annotation.Autowired;

      5. import org.springframework.web.bind.annotation.RequestMapping;

      6. import org.springframework.web.bind.annotation.RequestMethod;

      7. import org.springframework.web.bind.annotation.RestController;

      8.  
      9. import java.util.List;

      10.  
      11. @RestController

      12. @RequestMapping(value = {"/user"})

      13. public class UserController {

      14.  
      15. @Autowired

      16. private IUserService userService;

      17.  
      18. @RequestMapping(value = {"/findAll"},produces = {"application/json;charset=UTF-8"},method = RequestMethod.GET)

      19. public List getAllUsers(){

      20. List list = userService.findAllUser();

      21. return list;

      22. }

      23. }


      IUserService.java
    •  

       
      1. package com.ocean.service;

      2.  
      3. import java.util.List;

      4.  
      5. public interface IUserService {

      6. List findAllUser();

      7. }

      UserServiceImpl.java
    •  

       
      1. package com.ocean.service.impl;

      2.  
      3. import com.ocean.dao.UserInfoMapper;

      4. import com.ocean.service.IUserService;

      5. import org.springframework.beans.factory.annotation.Autowired;

      6. import org.springframework.stereotype.Service;

      7.  
      8. import java.util.List;

      9.  
      10. @Service(value = "userService")

      11. public class UserServiceImpl implements IUserService {

      12.  
      13. @Autowired

      14. private UserInfoMapper userDao;//这里可能会报错,但是并不会影响

      15.  
      16. @Override

      17. public List findAllUser(){

      18. return userDao.findAllUser();

      19. }

      20. }

      如果强迫症看不下去上面那个报错:(解决方法)

    • 直接在浏览器访问,返回的数据确实是表里插入的2条数据,说明项目已经搭建成功了!!

    • 源码地址:https://github.com/guobinhui/javaWeb-project/tree/master/springboot-mybatis-demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值