spring boot開發筆記——mybatis

概述

??mybatis框架的優點,就不用多說了,今天這邊干貨主要講mybatis的逆向工程,以及springboot的集成技巧,和分頁的使用

??因為在日常的開發中,當碰到特殊需求之類會手動寫一下sql語句,大部分的時候完全可以用mybatis的逆向工程替代。

mybatis逆向工程

相比較而言,代碼形式的逆向工程,更加靈活方便,簡單,易于管理,而且可以上傳到git中存儲。而且也只需要簡單的三步就能完成自動生成代碼。下面介紹如果搭建并生成xml和代碼
### 第一步:搭建工程
本項目使用的是maven搭建的工程,在你的pom文件中加入以下依賴:(這里以mysql數據庫為例)

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.0</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.34</version></dependency><!-- https://mvnrepository.com/artifact/log4j/log4j --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.5</version></dependency></dependencies>

第二步:配置generatorConfig.xml

該xml文件是mybatis的配置項 這里記錄了數據庫連接的配置,

<?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><context id="testTables" targetRuntime="MyBatis3"><commentGenerator><!-- 是否去除自動生成的注釋 true:是 : false:否 --><property name="suppressAllComments" value="true" /></commentGenerator><!--數據庫連接的信息:驅動類、連接地址、用戶名、密碼 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/database" userId="root"password="123456"></jdbcConnection><!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer,為 true時把JDBC DECIMAL和NUMERIC類型解析為java.math.BigDecimal --><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!-- targetProject:生成PO類的位置,重要!! --><javaModelGenerator targetPackage="springboot.modal.vo"targetProject=".\src"><!-- enableSubPackages:是否讓schema作為包的后綴 --><property name="enableSubPackages" value="false" /><!-- 從數據庫返回的值被清理前后的空格 --><property name="trimStrings" value="true" /></javaModelGenerator><!-- targetProject:mapper映射文件生成的位置,重要!! --><sqlMapGenerator targetPackage="springboot.dao"targetProject=".\src"><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- targetPackage:mapper接口生成的位置,重要!! --><javaClientGenerator type="XMLMAPPER"targetPackage="springboot.dao"targetProject=".\src"><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- 指定數據庫表,要生成哪些表,就寫哪些表,要和數據庫中對應,不能寫錯! --><table tableName="t_contents" domainObjectName="ContentVo" mapperName="ContentVoMapper" ></table></context>
</generatorConfiguration>

第三步:啟動類

啟動類主要設置main方法以及,制定配置文件generatorConfig.xml的路徑

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.File;
import java.util.ArrayList;
import java.util.List;public class Generator {public static void main(String args[]) throws  Exception{List<String> warnings = new ArrayList<String>();boolean overwrite  = true;File configFile = new File("./src/main/resources/generatorconfig.xml");System.out.println(configFile.exists());ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = cp.parseConfiguration(configFile);DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);myBatisGenerator.generate(null);}
}

當然如果有你想要設置日志輸出的話,可以加一個log4j.properties,簡單配置一下日志輸出:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

最后運行啟動類Generator,運行之前得確保,在數據庫中先創建好表

工程已經搭建好了,可以參考github上:
mybatis逆向工程GitHub

逆向工程如何使用

mapper中的方法

逆向工程生成完畢后,mybatis會在mapper中提供一些默認的接口和參數,下面就介紹一下這些方法的使用:

方法功能說明
int countByExample(UserExample example)按條件計數
int deleteByPrimaryKey(Integer id)按主鍵刪除
int deleteByExample(UserExample example)按條件刪除
String/Integer insert(User record)插入數據,返回值的ID
String/Integer insertSelective(User record)插入一條數據,只插入不為null的字段
User selectByPrimaryKey(Integer id)按主鍵查詢
List selectByExample(UserExample example)按條件查詢
List selectByExampleWithBLOGs(UserExample example)按條件查詢(包括BLOB字段)。只有當數據表中的字段類型有為二進制的才會產生。
int updateByPrimaryKey(User record)按主鍵更新
int updateByPrimaryKeySelective(User record)按主鍵更新值不為null的字段
int updateByExample(User record, UserExample example)按條件更新
int updateByExampleSelective(User record, UserExample example)按條件更新值不為null的字段

example類中的方法

mybatis的逆向工程中會生成實例及實例對應的example,example用于添加條件,相當where后面的部分

xxxExample example = new xxxExample();
Criteria criteria = new Example().createCriteria();

下表是常用方法

方法說明
example.setOrderByClause(“字段名 ASC”);添加升序排列條件,DESC為降序
example.setDistinct(false)去除重復,boolean型,true為選擇不重復的記錄。
criteria.andXxxIsNull添加字段xxx為null的條件
criteria.andXxxIsNotNull添加字段xxx不為null的條件
criteria.andXxxNotEqualTo(value)添加xxx字段不等于value條件
criteria.andXxxGreaterThan(value)添加xxx字段大于value條件
criteria.andXxxGreaterThanOrEqualTo(value)添加xxx字段大于等于value條件
criteria.andXxxLessThan(value)添加xxx字段小于value條件
criteria.andXxxLessThanOrEqualTo(value)添加xxx字段小于等于value條件
criteria.andXxxIn(List<?>)添加xxx字段值在List<?>條件
criteria.andXxxNotIn(List<?>)添加xxx字段值不在List<?>條件
criteria.andXxxLike(“%”+value+”%”)添加xxx字段值為value的模糊查詢條件
criteria.andXxxNotLike(“%”+value+”%”)添加xxx字段值不為value的模糊查詢條件
criteria.andXxxBetween(value1,value2)添加xxx字段值在value1和value2之間條件
criteria.andXxxNotBetween(value1,value2)添加xxx字段值不在value1和value2之間條件

sringboot整合mybatis

springboot整合mybatis很簡單 只需要簡單的配置即可以。
這里使用時xml方式,注解方式相對而言是清爽一些,但是sql全都堆砌在java文件中,并不利于閱讀,而且也沒有xml方式靈活。

項目構建

這里使用的是maven來構建項目,下面是pom文件:

  <properties><java.version>1.8</java.version></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.1.RELEASE</version><relativePath/></parent><dependencies><!-- 數據庫連接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.18</version></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.35</version><scope>runtime</scope></dependency><!-- spring boot 配置 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.2.0</version></dependency></dependencies>

工程搭建

搭建springboot第一件事就是使用配置application.properties。整合mybatis的時候需要配置jdbc的信息,這里還用了阿里的連接池Druid.下面是詳細的配置信息:

server.port=80
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bootmybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&autoReconnect=true
#用戶名
spring.datasource.username=root
#密碼
spring.datasource.password=123456
spring.datasource.initialSize=20
spring.datasource.minIdle=10
spring.datasource.maxActive=100
# 輸出mybatis日志 sql語句方便調試
logging.level.com.dao=DEBUG

下圖是工程結構圖:
1167080-20180426232032113-739579606.jpg

這里的UserVoMapper,UserVo,UserVoExample,都是使用的逆向工程生成的
啟動類代碼:

package com;import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import javax.sql.DataSource;@SpringBootApplication
@ComponentScan
@EnableAutoConfiguration
@MapperScan("com.dao")
public class StartApplication {public static void main(String[] args) throws Exception {SpringApplication app = new SpringApplication(StartApplication.class);app.setBannerMode(Banner.Mode.OFF);app.run(args);}// datasource注入@Bean@ConfigurationProperties(prefix = "spring.datasource")public DataSource dataSource() {return new DruidDataSource();}//mybatis SQLSession注入@Beanpublic SqlSessionFactory sqlSessionFactoryBean() throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource());PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();// 這里設置mybatis xml文件的地址sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));return sqlSessionFactoryBean.getObject();}
}

測試

在IndexController代碼如下:

package com.controller;import com.dao.UserVoMapper;
import com.domain.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class IndexController {@AutowiredUserVoMapper userDao;@GetMapping(value = "")@ResponseBodypublic UserVo index(){UserVo userVo = new UserVo();userVo.setUsername("SELECTIVE");userVo.setPassword("123456");userVo.setAddress("北京");userDao.insertSelective(userVo);userVo = userDao.selectByPrimaryKey(1);return userVo;}
}

啟動startApplication,在瀏覽器中輸入http://127.0.0.1,即可查看到結果。

如果有不明白的可以去git上查看源碼,傳送門
喜歡的話,給個star

轉載于:https://www.cnblogs.com/superfj/p/8955646.html

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

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

相關文章

Angular項目目錄介紹

通過 ng new 項目名生成的項目 一級目錄 Angular cli 工具生成的目錄文件名不要隨意修改&#xff0c;要不然會影響工具的使用。e2e&#xff1a;端到端的測試目錄&#xff0c;用來做自動測試的。node_modules&#xff1a;Angular第三方包。src&#xff1a;應用源代碼目錄&#…

jvm內存模型_四種視角看JVM內存模型

1.JVM運行視角程序計數器Java虛擬機棧本地方法棧Java堆方法區1 .程序計數器程序計數器是一塊較小的內存空間&#xff0c;它可以看作是當前線程所執行的行號指示器。這個計數器記錄的是正在執行的虛擬機字節碼指令的地址。此內存區域是唯一一個在JAVA虛擬機規范中沒有規定任何Ou…

linux mysql失敗_linux下登陸mysql失敗

標簽&#xff1a;一.提示由于沒有密碼&#xff0c;拒絕登陸ERROR 1045 (28000): Access denied for user ‘root‘‘localhost‘ (using password: NO)1.關閉mysql# service mysqld stop2.屏蔽權限# mysqld_safe --skip-grant-table屏幕出現&#xff1a; Starting demo from ..…

Tomcat服務腳本

為什么80%的碼農都做不了架構師&#xff1f;>>> #!/bin/bash ### BEGIN INIT INFO # Provides: tomcat # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # S…

Angular開發準備

cmd&#xff0c;進入項目文件下1、安裝jquerynpm install jquery --save。--save 安裝的同時&#xff0c;將信息寫入package.json中2、安裝bootstrapnpm installbootstrap--save。3、在.angular-cli.json中添加 jquery和bootstrap的引用在styles節點和scripts節點下加入。&quo…

python桌面開發吐血_想用java寫個桌面小demo,就布局都差點寫吐血了,學藝不精...

demo簡略需求項目背景很多文件重復存放&#xff0c;除了管理混亂&#xff0c;還會對患有強迫癥用戶的身心造成10000點的傷害...其實就是360云盤當時上傳了有上傳&#xff0c;造成很多重復的圖片視頻&#xff0c;前陣子360個人云盤“倒閉”&#xff0c;電腦日夜兼程&#xff0c;…

oracle 取當前日期時間的前一天前一小時前一分鐘前一秒

原文鏈接&#xff1a;http://wentao365.iteye.com/blog/779492 點擊閱讀原文 --------------------------------------------------------------------------- SELECT 當前時間 TITLE, TO_CHAR(SYSDATE, yyyy-mm-dd hh24:mi:ss) TIME FROM DUAL --當前時間 UNION ALL S…

mysql8事務級別_Mysql幾種事務隔離級別

前言&#xff1a;之前對mysql的基礎知識通過了幾篇博客進行了一個詳解&#xff0c;包括從數據庫系統的原理以及最基本的操作使用&#xff0c;此篇博客將主要對mysql的事務級別進行實戰分析1.什么是事務&#xff1f;事務是應用程序中一系列嚴密的操作&#xff0c;所有操作必須成…

控制臺應用和空項目有什么區別_互聯網小程序的應用以及APP的應用有什么區別及發展...

隨時移動互聯網進入的千家萬戶&#xff0c;互聯網的手機應用程序也漸漸的在市場上流行起來了。今天主要跟大家談一下互聯網小程序的應用以及APP的應用有什么區別以及未來的發展趨。未來會流行什么手機應用或者APP應用&#xff0c;我帶大家都為了解一下。下邊先來了解一下小程序…

day19_java基礎加強_動態代理+注解+類加載器

一、動態代理 1.1、代理模式 什么是代理模式及其作用&#xff1f; Proxy Pattern&#xff08;即&#xff1a;代理模式&#xff09;&#xff0c;23種常用的面向對象軟件的設計模式之一。? ? ? ? 代理模式的定義&#xff1a;為其他對象提供一種代理以控制對這個對象的訪問。?…

mysql壓力寫入測試_mysql壓力測試工具

相關推薦&#xff1a;測試工具測試工具 測試管理工具 Quality Center 基于WEB的測試管理工具 Test Director 功能測試工具 QuickTest Professional 性能測試工具 LoadRunner 哪位仁兄有相關…

python中隊列的應用用場景_消息隊列應用場景

原文http://blog.csdn.net/konglongaa/article/details/52208273一、消息隊列概述消息隊列中間件是分布式系統中重要的組件&#xff0c;主要解決應用解耦&#xff0c;異步消息&#xff0c;流量削鋒等問題&#xff0c;實現高性能&#xff0c;高可用&#xff0c;可伸縮和最終一致…

oracle獲取一段時間內所有的小時、天、月

原文鏈接&#xff1a;http://blog.csdn.net/ld422586546/article/details/9626921/ 點擊閱讀原文 ---------------------------------------------------------------------- 獲取一段時間內所有的小時 SELECT to_date(2013-07-01 12, yyyy-mm-dd hh24) (ROWNUM - 1) / 24 s…

eclipse快捷鍵、智能提示

1、Alt / 調出智能提示功能&#xff0c;即使在XML文件中&#xff1b; 2、 轉載于:https://www.cnblogs.com/JAVA-STUDYER/p/9143862.html

python下載網頁歌詞_python3個人學習筆記-批量下載分析歌詞2

我發現之前自己真是太愚蠢了沒有搞清楚正則表達的各種用法。不同詞語的篩選根本不用像re.sub(另一個想替換的內容,另一個替換后的內容,re.sub(想要替換的內容,替換后的內容,x))這樣傻了吧唧地篩一層又一層……(受linux的pipe荼毒太深)正則表達中不同字符的or其實大家都知道是[a…

使用循環鏈表實現一個通訊錄的管理程序_【LeetCode鏈表題型總結】

點擊上方藍字&#xff0c;關注公眾號鏈表概念的講解鏈表是什么鏈表是一種線性數據結構&#xff0c;每個節點都存有數據&#xff0c;通過指針將各個節點鏈接在一起。鏈表的性質一致性: 每個節點有相同的數據結構&#xff0c;相同的數據大小&#xff0c;內存中占據相同的大小&…

win10 C盤超過50G?教你如何對C盤瘦身!

原文鏈接&#xff1a;http://blog.csdn.net/u012762305/article/details/53469446 點擊閱讀原文 ------------------------------------------- 本人C盤是128G SSD硬盤&#xff0c;Win10系統盤和一些常用的程序都裝在這個盤&#xff08;特大程序除外&#xff09;&#xff0c;…

python的kite下載安裝及使用_Kite下載|Kite Python編程工具 V1.2020.1203.0 最新版下載 - 下載銀行...

Kite是一款專為Python打造的一款代碼補全軟件&#xff0c;如果你正在學習Python或是從事與Python相關的編程工作&#xff0c;那么這款軟件絕對是你的好幫手&#xff01;其會智能判斷用戶想要輸入的每個代碼字段&#xff0c;并在所有庫中進行匹配相應的內容&#xff0c;如果看到…

layui前端時間戳轉化

https://blog.csdn.net/rightbeforethesix/article/details/80358890轉載于:https://www.cnblogs.com/newlangwen/p/9144204.html

單頁web應用是什么?它又會給傳統網站帶來哪些好處?

原文鏈接&#xff1a;http://blog.csdn.net/zuoninger/article/details/38842823 點擊閱讀原文 ---------------------------------------------------- 什么是單頁應用&#xff1f; 單頁應用是指在瀏覽器中運行的應用&#xff0c;它們在使用期間不會重新加載頁面。像所有的…