mall整合SpringBoot+MyBatis搭建基本骨架

本文主要講解mall整合SpringBoot+MyBatis搭建基本骨架,以商品品牌為例實現基本的CRUD操作及通過PageHelper實現分頁查詢。

mysql數據庫環境搭建

  • 下載并安裝mysql5.7版本,下載地址:dev.mysql.com/downloads/i…
  • 設置數據庫帳號密碼:root root
  • 下載并安裝客戶端連接工具Navicat,下載地址:www.formysql.com/xiazai.html
  • 創建數據庫mall
  • 導入mall的數據庫腳本,腳本地址:github.com/macrozheng/…

項目使用框架介紹

SpringBoot

SpringBoot可以讓你快速構建基于Spring的Web應用程序,內置多種Web容器(如Tomcat),通過啟動入口程序的main函數即可運行。

PagerHelper

MyBatis分頁插件,簡單的幾行代碼就能實現分頁,在與SpringBoot整合時,只要整合了PagerHelper就自動整合了MyBatis。

PageHelper.startPage(pageNum, pageSize);
//之后進行查詢操作將自動進行分頁
List<PmsBrand> brandList = brandMapper.selectByExample(new PmsBrandExample());
//通過構造PageInfo對象獲取分頁信息,如當前頁碼,總頁數,總條數
PageInfo<PmsBrand> pageInfo = new PageInfo<PmsBrand>(list);
復制代碼

Druid

alibaba開源的數據庫連接池,號稱Java語言中最好的數據庫連接池。

Mybatis generator

MyBatis的代碼生成器,可以根據數據庫生成model、mapper.xml、mapper接口和Example,通常情況下的單表查詢不用再手寫mapper。

項目搭建

使用IDEA初始化一個SpringBoot項目

添加項目依賴

在pom.xml中添加相關依賴。

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.3.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><dependencies><!--SpringBoot通用依賴模塊--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--MyBatis分頁插件--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.2.10</version></dependency><!--集成druid連接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version></dependency><!-- MyBatis 生成器 --><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.3</version></dependency><!--Mysql數據庫驅動--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.15</version></dependency></dependencies>
復制代碼

修改SpringBoot配置文件

在application.yml中添加數據源配置和MyBatis的mapper.xml的路徑配置。

server:
  port: 8080spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: rootmybatis:
  mapper-locations:
    - classpath:mapper/*.xml
    - classpath*:com/**/mapper/*.xml
復制代碼

項目結構說明

Mybatis generator 配置文件

配置數據庫連接,Mybatis generator生成model、mapper接口及mapper.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><properties resource="generator.properties"/><context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat"><property name="beginningDelimiter" value="`"/><property name="endingDelimiter" value="`"/><property name="javaFileEncoding" value="UTF-8"/><!-- 為模型生成序列化方法--><plugin type="org.mybatis.generator.plugins.SerializablePlugin"/><!-- 為生成的Java模型創建一個toString方法 --><plugin type="org.mybatis.generator.plugins.ToStringPlugin"/><!--可以自定義生成model的代碼注釋--><commentGenerator type="com.macro.mall.tiny.mbg.CommentGenerator"><!-- 是否去除自動生成的注釋 true:是 : false:否 --><property name="suppressAllComments" value="true"/><property name="suppressDate" value="true"/><property name="addRemarkComments" value="true"/></commentGenerator><!--配置數據庫連接--><jdbcConnection driverClass="${jdbc.driverClass}"connectionURL="${jdbc.connectionURL}"userId="${jdbc.userId}"password="${jdbc.password}"><!--解決mysql驅動升級到8.0后不生成指定數據庫代碼的問題--><property name="nullCatalogMeansCurrent" value="true" /></jdbcConnection><!--指定生成model的路徑--><javaModelGenerator targetPackage="com.macro.mall.tiny.mbg.model" targetProject="mall-tiny-01\src\main\java"/><!--指定生成mapper.xml的路徑--><sqlMapGenerator targetPackage="com.macro.mall.tiny.mbg.mapper" targetProject="mall-tiny-01\src\main\resources"/><!--指定生成mapper接口的的路徑--><javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.tiny.mbg.mapper"targetProject="mall-tiny-01\src\main\java"/><!--生成全部表tableName設為%--><table tableName="pms_brand"><generatedKey column="id" sqlStatement="MySql" identity="true"/></table></context>
</generatorConfiguration>
復制代碼

運行Generator的main函數生成代碼

package com.macro.mall.tiny.mbg;import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;/*** 用于生產MBG的代碼* Created by macro on 2018/4/26.*/
public class Generator {public static void main(String[] args) throws Exception {//MBG 執行過程中的警告信息List<String> warnings = new ArrayList<String>();//當生成的代碼重復時,覆蓋原代碼boolean overwrite = true;//讀取我們的 MBG 配置文件InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = cp.parseConfiguration(is);is.close();DefaultShellCallback callback = new DefaultShellCallback(overwrite);//創建 MBGMyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);//執行生成代碼myBatisGenerator.generate(null);//輸出警告信息for (String warning : warnings) {System.out.println(warning);}}
}
復制代碼

添加MyBatis的Java配置

用于配置需要動態生成的mapper接口的路徑

package com.macro.mall.tiny.config;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;/*** MyBatis配置類* Created by macro on 2019/4/8.*/
@Configuration
@MapperScan("com.macro.mall.tiny.mbg.mapper")
public class MyBatisConfig {
}復制代碼

實現Controller中的接口

實現PmsBrand表中的添加、修改、刪除及分頁查詢接口。

package com.macro.mall.tiny.controller;import com.macro.mall.tiny.common.api.CommonPage;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.mbg.model.PmsBrand;
import com.macro.mall.tiny.service.PmsBrandService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;import java.util.List;/*** 品牌管理Controller* Created by macro on 2019/4/19.*/
@Controller
@RequestMapping("/brand")
public class PmsBrandController {@Autowiredprivate PmsBrandService demoService;private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);@RequestMapping(value = "listAll", method = RequestMethod.GET)@ResponseBodypublic CommonResult<List<PmsBrand>> getBrandList() {return CommonResult.success(demoService.listAllBrand());}@RequestMapping(value = "/create", method = RequestMethod.POST)@ResponseBodypublic CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {CommonResult commonResult;int count = demoService.createBrand(pmsBrand);if (count == 1) {commonResult = CommonResult.success(pmsBrand);LOGGER.debug("createBrand success:{}", pmsBrand);} else {commonResult = CommonResult.failed("操作失敗");LOGGER.debug("createBrand failed:{}", pmsBrand);}return commonResult;}@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)@ResponseBodypublic CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody PmsBrand pmsBrandDto, BindingResult result) {CommonResult commonResult;int count = demoService.updateBrand(id, pmsBrandDto);if (count == 1) {commonResult = CommonResult.success(pmsBrandDto);LOGGER.debug("updateBrand success:{}", pmsBrandDto);} else {commonResult = CommonResult.failed("操作失敗");LOGGER.debug("updateBrand failed:{}", pmsBrandDto);}return commonResult;}@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)@ResponseBodypublic CommonResult deleteBrand(@PathVariable("id") Long id) {int count = demoService.deleteBrand(id);if (count == 1) {LOGGER.debug("deleteBrand success :id={}", id);return CommonResult.success(null);} else {LOGGER.debug("deleteBrand failed :id={}", id);return CommonResult.failed("操作失敗");}}@RequestMapping(value = "/list", method = RequestMethod.GET)@ResponseBodypublic CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,@RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) {List<PmsBrand> brandList = demoService.listBrand(pageNum, pageSize);return CommonResult.success(CommonPage.restPage(brandList));}@RequestMapping(value = "/{id}", method = RequestMethod.GET)@ResponseBodypublic CommonResult<PmsBrand> brand(@PathVariable("id") Long id) {return CommonResult.success(demoService.getBrand(id));}
}復制代碼

添加Service接口

package com.macro.mall.tiny.service;import com.macro.mall.tiny.mbg.model.PmsBrand;import java.util.List;/*** PmsBrandService* Created by macro on 2019/4/19.*/
public interface PmsBrandService {List<PmsBrand> listAllBrand();int createBrand(PmsBrand brand);int updateBrand(Long id, PmsBrand brand);int deleteBrand(Long id);List<PmsBrand> listBrand(int pageNum, int pageSize);PmsBrand getBrand(Long id);
}復制代碼

實現Service接口

package com.macro.mall.tiny.service.impl;import com.github.pagehelper.PageHelper;
import com.macro.mall.tiny.mbg.mapper.PmsBrandMapper;
import com.macro.mall.tiny.mbg.model.PmsBrand;
import com.macro.mall.tiny.mbg.model.PmsBrandExample;
import com.macro.mall.tiny.service.PmsBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** PmsBrandService實現類* Created by macro on 2019/4/19.*/
@Service
public class PmsBrandServiceImpl implements PmsBrandService {@Autowiredprivate PmsBrandMapper brandMapper;@Overridepublic List<PmsBrand> listAllBrand() {return brandMapper.selectByExample(new PmsBrandExample());}@Overridepublic int createBrand(PmsBrand brand) {return brandMapper.insertSelective(brand);}@Overridepublic int updateBrand(Long id, PmsBrand brand) {brand.setId(id);return brandMapper.updateByPrimaryKeySelective(brand);}@Overridepublic int deleteBrand(Long id) {return brandMapper.deleteByPrimaryKey(id);}@Overridepublic List<PmsBrand> listBrand(int pageNum, int pageSize) {PageHelper.startPage(pageNum, pageSize);brandMapper.selectByExample(new PmsBrandExample());return brandMapper.selectByExample(new PmsBrandExample());}@Overridepublic PmsBrand getBrand(Long id) {return brandMapper.selectByPrimaryKey(id);}
}復制代碼

項目源碼地址

github.com/macrozheng/…

公眾號

mall項目全套學習教程連載中,關注公眾號第一時間獲取。

轉載于:https://juejin.im/post/5cf7c4a7e51d4577790c1c50

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

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

相關文章

Web框架之Django_01初識(三大主流web框架、Django安裝、Django項目創建方式及其相關配置、Django基礎三件套:HttpResponse、render、redirect)...

摘要&#xff1a; Web框架概述 Django簡介 Django項目創建 Django基礎必備三件套(HttpResponse、render、redirect) 一、Web框架概述&#xff1a; Python三大主流Web框架&#xff1a; Django&#xff1a;大而全&#xff0c;自帶了很多功能模塊&#xff0c;類似于航空母艦&am…

Bone Collector【01背包】

F - Bone Collector HDU - 2602 Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave … The bone collector had a big bag wit…

Gamma階段第八次scrum meeting

每日任務內容 隊員昨日完成任務明日要完成的任務張圓寧#91 用戶體驗與優化https://github.com/rRetr0Git/rateMyCourse/issues/91&#xff08;持續完成&#xff09;#91 用戶體驗與優化https://github.com/rRetr0Git/rateMyCourse/issues/91牛宇航#86 重置密碼的后端邏輯https:/…

【動態規劃】多重背包

問題 Q: 【動態規劃】多重背包 時間限制: 1 Sec 內存限制: 64 MB 提交: 112 解決: 49 [提交] [狀態] [討論版] [命題人:admin] 題目描述 張琪曼&#xff1a;“魔法石礦里每種魔法石的數量看起來是足夠多&#xff0c;但其實每種魔法石的數量是有限的。” 李旭琳&#xff1a;…

【動態規劃】完全背包問題

問題 O: 【動態規劃】完全背包問題 時間限制: 1 Sec 內存限制: 64 MB 提交: 151 解決: 71 [提交] [狀態] [討論版] [命題人:admin] 題目描述 話說張琪曼和李旭琳又發現了一處魔法石礦&#xff08;運氣怎么這么好&#xff1f;各種嫉妒羨慕恨啊&#xff09;&#xff0c;她們有…

springboot超級詳細的日志配置(基于logback)

前言 java web 下有好幾種日志框架&#xff0c;比如&#xff1a;logback&#xff0c;log4j&#xff0c;log4j2&#xff08;slj4f 并不是一種日志框架&#xff0c;它相當于定義了規范&#xff0c;實現了這個規范的日志框架就能夠用 slj4f 調用&#xff09;。其中性能最高的應該使…

【動態規劃】簡單背包問題II

問題 J: 【動態規劃】簡單背包問題II 時間限制: 1 Sec 內存限制: 64 MB 提交: 127 解決: 76 [提交] [狀態] [討論版] [命題人:admin] 題目描述 張琪曼&#xff1a;“為什么背包一定要完全裝滿呢&#xff1f;盡可能多裝不就行了嗎&#xff1f;” 李旭琳&#xff1a;“你說得…

Vue組件通信

前言 Vue組件之間的通信 其實是一種非常常見的場景 不管是業務邏輯還是前段面試中都是非常頻繁出現的 這篇文章將會逐一講解各個傳值的方式 不過在此之前 先來總結一下各個傳值方式吧 1.父組件向子組件傳值 > props2.子組件向父組件傳值 > $emit3.平級組件傳值 > 總線…

【動態規劃】0/1背包問題

問題 H: 【動態規劃】0/1背包問題 時間限制: 1 Sec 內存限制: 64 MB 提交: 152 解決: 95 [提交] [狀態] [討論版] [命題人:admin] 題目描述 張琪曼和李旭琳有一個最多能用m公斤的背包&#xff0c;有n塊魔法石&#xff0c;它們的重量分別是W1&#xff0c;W2&#xff0c;…&a…

貓哥教你寫爬蟲 005--數據類型轉換-小作業

小作業 程序員的一人飲酒醉 請運用所給變量&#xff0c;使用**str()**函數打印兩句話。 第一句話&#xff1a;1人我編程累, 碎掉的節操滿地堆 第二句話&#xff1a;2眼是bug相隨, 我只求今日能早歸 number1 1 number2 2 unit1 人 unit2 眼 line1 我編程累 line2 是bug相…

索引失效

轉載于:https://blog.51cto.com/11009785/2406488

棋盤問題【深搜】

棋盤問題 POJ - 1321 在一個給定形狀的棋盤&#xff08;形狀可能是不規則的&#xff09;上面擺放棋子&#xff0c;棋子沒有區別。要求擺放時任意的兩個棋子不能放在棋盤中的同一行或者同一列&#xff0c;請編程求解對于給定形狀和大小的棋盤&#xff0c;擺放k個棋子的所有可行…

python isinstance()

isinstanceisinstance(object, classinfo) 判斷實例是否是這個類或者object是變量 classinfo 是類型(tuple,dict,int,float) 判斷變量是否是這個類型 舉例&#xff1a; class objA: pass A objA() B a,v C a string print isinstance(A, objA) #注意該用法 print isinst…

P1303 A*B Problem 高精度乘法

復習了一下高精乘 #include<bits/stdc.h> using namespace std; const int maxn1e67; char a1[maxn],b1[maxn]; int a[maxn],b[maxn],c[maxn*10],lena,lenb,lenc,x; int main() {scanf("%s",a1);scanf("%s",b1);lenastrlen(a1);lenbstrlen(b1);for(i…

Catch That Cow【廣搜】

Catch That Cow POJ - 3278 Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number l…

Go2Shell 已無法使用

在更新 Mac 系統時提醒了這個, 像我一樣對 Go2Shell 中毒的人來說, 這是無法忍受的。貌似 Go2Shell 沒有升級&#xff0c;沒有辦法&#xff0c;就直接找來了一個替代品。cd to, 下載入口如下&#xff1a;目前感覺良好。 轉載于:https://juejin.im/post/5cfe82e15188252b1b0366e…

Fliptile【搜索】

Fliptile POJ - 3279 Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He has arranged a brainy activity for cows in which they manipulate an M N grid (1 ≤ M ≤ 15; 1 ≤ N ≤ 15) of square tiles, each of which…

JS異步開發總結

1 前言 眾所周知&#xff0c;JS語言是單線程的。在實際開發過程中都會面臨一個問題&#xff0c;就是同步操作會阻塞整個頁面乃至整個瀏覽器的運行&#xff0c;只有在同步操作完成之后才能繼續進行其他處理&#xff0c;這種同步等待的用戶體驗極差。所以JS中引入了異步編程&…

迷宮問題【廣搜】

迷宮問題 POJ - 3984 定義一個二維數組&#xff1a; int maze[5][5] {0, 1, 0, 0, 0,0, 1, 0, 1, 0,0, 0, 0, 0, 0,0, 1, 1, 1, 0,0, 0, 0, 1, 0,}; 它表示一個迷宮&#xff0c;其中的1表示墻壁&#xff0c;0表示可以走的路&#xff0c;只能橫著走或豎著走&#xff0c;不能…

大蝦對51單片機入門的經驗總結

回想起當初學習AT89S52的日子還近在眼前:畢業后的第一年呆在親戚公司做了10個月設備管理.乏味的工作和繁雜的瑣事讓我郁悶不已.思考很久后終于辭職.投奔我的同學去了,開始并不曾想到要進入工控行業,知識想找一份電子類技術職業,至于什么職業我根本沒有目標可言.經過兩個多月的挫…