Springboot Mybatis 整合(完整版)

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。

正題
本項目使用的環境:

開發工具:Intellij IDEA 2017.1.3
springboot: 1.5.6
jdk:1.8.0_161
maven:3.3.9
額外功能

PageHelper 分頁插件
mybatis generator 自動生成代碼插件
步驟:
1.創建一個springboot項目:

2.創建項目的文件結構以及jdk的版本

3.選擇項目所需要的依賴


然后點擊finish

5.看一下文件的結構:


6.查看一下pom.xml:

<?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>

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


server:port: 8080spring:datasource:name: testurl: jdbc:mysql://127.0.0.1:3306/depotusername: rootpassword: root# 使用druid數據源type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.jdbc.Driverfilters: statmaxActive: 20initialSize: 1maxWait: 60000minIdle: 1timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: select 'x'testWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: truemaxOpenPreparedStatements: 20## 該配置節點為獨立的節點,有很多同學容易將這個配置放在spring 的節點下,導致配置無法被識別
mybatis:mapper-locations: classpath:mapping/*.xml ?#注意:一定要對應mapper映射xml文件的所在路徑type-aliases-package: com.winter.model ?# 注意:對應實體類的路徑#pagehelper分頁插件
pagehelper:helperDialect: mysqlreasonable: truesupportMethodsArguments: trueparams: count=countSql

8.創建數據庫:

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;

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

配置pom.xml中generator 插件所對應的配置文件 ${basedir}/src/main/resources/generator/generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfigurationPUBLIC "-//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>

點擊run-Edit Configurations


添加配置


運行
注意!!!同一張表一定不要運行多次,因為 mapper 的映射文件中會生成多次的代碼,導致報錯,切記


最后生成的文件以及結構:

10. 生成的文件

UserMapper.javapackage 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();
}

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();}
}

對于 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_userwhere 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_userwhere 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_userset user_name = #{userName,jdbcType=VARCHAR},password = #{password,jdbcType=VARCHAR},phone = #{phone,jdbcType=VARCHAR}where user_id = #{userId,jdbcType=INTEGER}</update>
</mapper>

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);}
}

注意:@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 {@Autowiredprivate 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);}
}

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);
}

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 {@Autowiredprivate UserMapper userMapper;//這里會報錯,但是并不會影響@Overridepublic int addUser(User user) {return userMapper.insertSelective(user);}/** 這個方法中用到了我們開頭配置依賴的分頁插件pagehelper* 很簡單,只需要在service層傳入參數,然后將參數傳遞給一個插件的一個靜態方法即可;* pageNum 開始頁數* pageSize 每頁顯示的數據條數* */@Overridepublic List<User> findAllUser(int pageNum, int pageSize) {//將參數傳給這個方法就可以實現物理分頁了,非常簡單。PageHelper.startPage(pageNum, pageSize);return userMapper.selectAllUser();}
}

如果強迫癥看不下去那個報錯:(解決方法)

測試我使用了 idea 一個很用心的功能。
可以發 http 請求的插件:

點擊左側的運行按鈕就可以發送請求了;
如果返回值正確 說明你已經搭建成功了!

如果出現mapper注入不了的情況,請檢查版本.


轉自:https://blog.csdn.net/winter_chen001/article/details/77249029?
?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/447950.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/447950.shtml
英文地址,請注明出處:http://en.pswp.cn/news/447950.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

OpenCL 第5課:向量相加

OpenCL程序分為兩個部份&#xff0c;一部份是內核代碼&#xff0c;負責具體算法。另一部份是主程序負責初始化OpenCL和準備數據。主程序加載內核代碼&#xff0c;并按照即定方法進行運算。 內核代碼可以寫在主程序里面&#xff0c;也可以寫在另一個文本文件里&#xff0c;有點…

同名的const 成員函數

如下代碼&#xff1a;struct Derived{ void foo(string) { cout<<"ddd foo"<<endl; }; void foo(string) const { cout<<"ddd foo const"<<endl; };}; int _tmain(int argc, TCH…

springboot 中使用 Mybatis 注解 配置 詳解

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 傳參方式 使用不同的傳參方式&#xff1a; 使用Param 之前博文中的項目使用了這種簡單的傳參方式&#xff1a; Insert("INSERT IN…

mongodb數據庫的備份與恢復

先介紹下命令語法&#xff1a; ./mongodump -h 127.0.0.1:10001 -d lietou -o /usr/local/data -h&#xff1a;MongDB所在服務器地址&#xff0c;例如&#xff1a;127.0.0.1&#xff0c;當然也可以指定端口號&#xff1a;127.0.0.1:10001 -d&#xff1a;需要備份的數據庫實例…

OpenCL 第6課:矩陣轉置

上一節我們寫了個一維向量相加的程序。這節我們來看一個44矩陣轉置程序。 4X4矩陣我們采用二維數組進行存儲&#xff0c;在程序設計上&#xff0c;我們讓轉置過程分4次轉置完成&#xff0c;就是一次轉一行。注意這里的OpenCL的工作維數是二維。&#xff08;當然用一維的方式也…

springboot 系列技術教程目錄

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 一、教程目錄地址&#xff1a; springboot系列技術教程目錄 二、教程內容&#xff1a; springboot2.X系列&#xff1a; springboot整…

OpenCL 第7課:旋轉變換(1)

旋轉是一個常用的處理功能。圖片中所有的點以某一個點為軸&#xff0c;順時或逆時方向旋轉N個角度。我們利用OpenCL就可以對圖片中所有的點進行并行轉換&#xff0c;大大提高效率。 上兩節中&#xff0c;我們編寫了CL文件來傳遞數組的地址&#xff0c;這一節中我們會多加入幾個…

WinForms多線程編程之搖獎程序

利用多線程模擬一個電腦搖獎程序&#xff0c;如圖所示。在點擊【滾動號碼】&#xff0c;啟動線程&#xff0c;對后臺的電話號碼進行循環顯示&#xff1b;點擊【開獎】按鈕&#xff0c;關閉線程&#xff0c;此時顯示在文本框中的電話號碼即為中獎號碼 using System;using System…

idea 版本控制忽略文件、文件夾設置

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 setting 中&#xff1a; 或者底部的 設置 忽略某個文件 后面選擇框可以去選擇 忽略某個文件夾 后面選擇框可以去選擇 忽略某種文件 后面…

Windows Azure HandBook (1) IaaS相關技術

《Windows Azure Platform 系列文章目錄》 1.Microsoft Azure底層是否由System Center和Hyper-V構成? Microsoft Azure雖然支持Hyper-V的VHD直接上傳至Azure云端進行管理&#xff0c;但是Azure底層技術是微軟自己研發的、獨有的技術&#xff0c;且不對外提供。如果客戶想構建屬…

OpenCL 第8課:旋轉變換(2)

上兩節課都是對一個數組進行處理。這節我們來個有意思的。同樣是旋轉。但我們旋轉的對象是張&#xff08;&#xff12;&#xff15;&#xff16;*&#xff12;&#xff15;&#xff16;&#xff09;的圖片。圖片旋轉&#xff14;&#xff15;度&#xff0c;旋轉后大小還是&…

VUE: 當前頁面 引用自定義公用樣式 (:style=“樣式名“)

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 1. 在當前頁面&#xff0c;自行定義了幾個樣式&#xff0c;在不同地方引用。 2. 實現代碼。 樣式定義&#xff1a; data() {return {i…

免費的api接口

歡迎大家加群討論&#xff1a;地址&#xff1a;https://www.apiopen.top 為了方便各類開發者&#xff0c;現提供免費開放Api接口&#xff0c;所有接口均無使用限制&#xff0c;返回格式全是JSON&#xff0c;所以基本能滿足大家的開發需求&#xff0c;但請各位不要將這些Api接入…

養成這8個好習慣 開車會很安全的

第一&#xff0c;過路口時減速左右看——要養成過口子時&#xff0c;不管有沒有紅綠燈&#xff0c;也不管自己的行道是綠燈&#xff0c;都要左顧右盼&#xff08;同時要減速&#xff09;的習慣&#xff0c;觀察在橫道上的車輛情況&#xff0c;確認沒有車橫沖&#xff0c;才加速…

css background-attachment:fixed 固定背景、不隨內容一起滾動

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 兼容性&#xff1a;全兼容&#xff0c;只不過IE滾動時會有一點不流暢。 background-attachment 有 3 個選項&#xff1a;scroll / fix…

Javacript和AngularJS中的Promises

promise是Javascript異步編程很好的解決方案。對于一個異步方法&#xff0c;執行一個回調函數。比如頁面調用google地圖的api時就使用到了promise。 function success(position){var cords position.coords;console.log(coords.latitude coords.longitude); }function error(…

男人沉默的真實原因

英國社會學家馬克經過調查發現&#xff1a;男人每天的說話量&#xff0c;是女人的一半。但男人們也大多用于朋友圈中、工作中&#xff0c;而與愛人的聊天交流&#xff0c;每天可能不足15分鐘&#xff0c;用詞量不超過10%。 其實&#xff0c;男人有很多緘默的方法&#xff0c;每…

Visual Studio 使用說明文檔、VScode 使用手冊

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 我只是記錄下地址&#xff0c;方便自已以后查看&#xff1a; Visual Studio 使用文檔 內容如&#xff1a;

JAVA File的創建及相對路徑絕對路徑

JAVA File的創建及相對路徑絕對路徑 轉載自 http://blog.sina.com.cn/s/blog_9386f17b0100w2vv.htmlFile f new File("D:/test/mytest.txt");//當執行這句話后在內存的棧空間存在一個f的應用&#xff0c;在堆空間里存在一個mytest.txt對象。注意 這個對象只含有文件…

腎有多好人就有多年輕 男女通用的補腎秘方

每天都堅持喝一碗&#xff0c;現在已經連續喝了三個多星期了&#xff0c;以前有好些白發的地方居然沒有復發&#xff0c;而且現在一根也沒有啊&#xff0c;我真的很開心。不僅白頭發不見了&#xff0c;而且皮膚變白皙和光滑了好多&#xff0c;氣色也比原來好了!好東西要大家分享…