springboot/Mybatis整合

正題

本項目使用的環境:java

  • 開發工具:Intellij IDEA 2017.1.3
  • springboot: 1.5.6
  • jdk:1.8.0_161
  • maven:3.3.9

額外功能mysql

  • PageHelper 分頁插件
  • mybatis generator 自動生成代碼插件

步驟:
1.建立一個springboot項目:
這裏寫圖片描述
2.建立項目的文件結構以及jdk的版本
這裏寫圖片描述
3.選擇項目所須要的依賴
這裏寫圖片描述
這裏寫圖片描述
而後點擊finishgit

5.看一下文件的結構:
這裏寫圖片描述github

6.查看一下pom.xml:web

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.winter</groupId> <artifactId>springboot-mybatis-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-mybatis-demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.7</java.version> </properties> <dependencies> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-joda</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-parameter-names</artifactId> </dependency> <!-- 分頁插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.1.2</version> </dependency> <!-- alibaba的druid數據庫鏈接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- mybatis generator 自動生成代碼插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build> </project> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106

7.項目不使用application.properties文件 而使用更加簡潔的application.yml文件:
將原有的resource文件夾下的application.properties文件刪除,建立一個新的application.yml配置文件,
文件的內容以下:spring

server: port: 8080 spring: datasource: name: test url: jdbc:mysql://127.0.0.1:3306/depot username: root password: root # 使用druid數據源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 ## 該配置節點爲獨立的節點,有不少同窗容易將這個配置放在spring的節點下,致使配置沒法被識別 mybatis: mapper-locations: classpath:mapping/*.xml #注意:必定要對應mapper映射xml文件的所在路徑 type-aliases-package: com.winter.model # 注意:對應實體類的路徑 #pagehelper分頁插件 pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

8.建立數據庫:sql

CREATE DATABASE mytest; CREATE TABLE t_user( user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, user_name VARCHAR(255) NOT NULL , password VARCHAR(255) NOT NULL , phone VARCHAR(255) NOT NULL ) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

9.使用mybatis generator 自動生成代碼:數據庫

  • 配置pom.xml中generator 插件所對應的配置文件 ${basedir}/src/main/resources/generator/generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 數據庫驅動:選擇你的本地硬盤上面的數據庫驅動包--> <classPathEntry location="E:\developer\mybatis-generator-core-1.3.2\lib\mysql-connector-java-5.1.25-bin.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自動生成的註釋 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--數據庫連接URL,用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/mytest" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置--> <javaModelGenerator targetPackage="com.winter.model" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.winter.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名--> <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 點擊run-Edit Configurations

這裏寫圖片描述

  • 添加配置

這裏寫圖片描述

  • 運行
    注意!!!同一張表必定不要運行屢次,由於mapper的映射文件中會生成屢次的代碼,致使報錯,切記
    這裏寫圖片描述apache

    最後生成的文件以及結構:json

這裏寫圖片描述

10. 生成的文件

UserMapper.java

package com.winter.mapper; import com.winter.model.User; public interface UserMapper { int deleteByPrimaryKey(Integer userId); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer userId); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); //這個方式我本身加的 List<User> selectAllUser(); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

User.java

package com.winter.model; public class User { private Integer userId; private String userName; private String password; private String phone; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

對於sql語句這種黃色的背景,真心是看不下去了(解決方案):
這裏寫圖片描述

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="com.winter.mapper.UserMapper" > <resultMap id="BaseResultMap" type="com.winter.model.User" > <id column="user_id" property="userId" jdbcType="INTEGER" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="phone" property="phone" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > user_id, user_name, password, phone </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from t_user where user_id = #{userId,jdbcType=INTEGER} </select> <!-- 這個方法是我本身加的 --> <select id="selectAllUser" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from t_user </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from t_user where user_id = #{userId,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.winter.model.User" > insert into t_user (user_id, user_name, password, phone) values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.winter.model.User" > insert into t_user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="userId != null" > user_id, </if> <if test="userName != null" > user_name, </if> <if test="password != null" > password, </if> <if test="phone != null" > phone, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="userId != null" > #{userId,jdbcType=INTEGER}, </if> <if test="userName != null" > #{userName,jdbcType=VARCHAR}, </if> <if test="password != null" > #{password,jdbcType=VARCHAR}, </if> <if test="phone != null" > #{phone,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.winter.model.User" > update t_user <set > <if test="userName != null" > user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="password != null" > password = #{password,jdbcType=VARCHAR}, </if> <if test="phone != null" > phone = #{phone,jdbcType=VARCHAR}, </if> </set> where user_id = #{userId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.winter.model.User" > update t_user set user_name = #{userName,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, phone = #{phone,jdbcType=VARCHAR} where user_id = #{userId,jdbcType=INTEGER} </update> </mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89

11.打開類SpringbootMybatisDemoApplication.java,這個是springboot的啓動類。咱們須要添加點東西:

package com.winter; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.winter.mapper")//將項目中對應的mapper類的路徑加進來就能夠了 public class SpringbootMybatisDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMybatisDemoApplication.class, args); } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

注意:@MapperScan("com.winter.mapper")這個註解很是的關鍵,這個對應了項目中mapper(dao)所對應的包路徑,不少同窗就是這裏忘了加致使異常的

12.到這裏全部的搭建工做都完成了,接下來就是測試的工做,沒使用junit4進行測試:
首先看一下完成以後的文件的結構:
這裏寫圖片描述

如今controller,service層的代碼都寫好:

UserController.java

package com.winter.Controller; import com.winter.model.User; import com.winter.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by Administrator on 2017/8/16. */ @Controller @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @ResponseBody @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"}) public int addUser(User user){ return userService.addUser(user); } @ResponseBody @RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"}) public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){ return userService.findAllUser(pageNum,pageSize); } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

UserService.java

package com.winter.service; import com.winter.model.User; import java.util.List; /** * Created by Administrator on 2017/8/16. */ public interface UserService { int addUser(User user); List<User> findAllUser(int pageNum, int pageSize); } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

UserServiceImpl.java

package com.winter.service.impl; import com.github.pagehelper.PageHelper; import com.winter.mapper.UserMapper; import com.winter.model.User; import com.winter.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by Administrator on 2017/8/16. */ @Service(value = "userService") public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper;//這裏會報錯,可是並不會影響 @Override public int addUser(User user) { return userMapper.insertSelective(user); } /* * 這個方法中用到了咱們開頭配置依賴的分頁插件pagehelper * 很簡單,只須要在service層傳入參數,而後將參數傳遞給一個插件的一個靜態方法便可; * pageNum 開始頁數 * pageSize 每頁顯示的數據條數 * */ @Override public List<User> findAllUser(int pageNum, int pageSize) { //將參數傳給這個方法就能夠實現物理分頁了,很是簡單。 PageHelper.startPage(pageNum, pageSize); return userMapper.selectAllUser(); } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

若是強迫症看不下去那個報錯:(解決方法)
這裏寫圖片描述

測試我使用了idea一個很用心的功能。
能夠發http請求的插件
這裏寫圖片描述

這裏寫圖片描述

點擊左側的運行按鈕就能夠發送請求了;
若是返回值正確 說明你已經搭建成功了!!

https://blog.csdn.net/winter_chen001/article/details/77249029

相關文章
相關標籤/搜索