日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

spring boot开发笔记——mybatis

發(fā)布時(shí)間:2025/3/8 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring boot开发笔记——mybatis 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

概述

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

??因?yàn)樵谌粘5拈_發(fā)中,當(dāng)碰到特殊需求之類會(huì)手動(dòng)寫一下sql語(yǔ)句,大部分的時(shí)候完全可以用mybatis的逆向工程替代。

mybatis逆向工程

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

<!-- 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的配置項(xiàng) 這里記錄了數(shù)據(jù)庫(kù)連接的配置,

<?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><!-- 是否去除自動(dòng)生成的注釋 true:是 : false:否 --><property name="suppressAllComments" value="true" /></commentGenerator><!--數(shù)據(jù)庫(kù)連接的信息:驅(qū)動(dòng)類、連接地址、用戶名、密碼 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/database" userId="root"password="123456"></jdbcConnection><!-- 默認(rèn)false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer,為 true時(shí)把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" /><!-- 從數(shù)據(jù)庫(kù)返回的值被清理前后的空格 --><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><!-- 指定數(shù)據(jù)庫(kù)表,要生成哪些表,就寫哪些表,要和數(shù)據(jù)庫(kù)中對(duì)應(yīng),不能寫錯(cuò)! --><table tableName="t_contents" domainObjectName="ContentVo" mapperName="ContentVoMapper" ></table></context> </generatorConfiguration>

第三步:啟動(dòng)類

啟動(dòng)類主要設(shè)置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);} }

當(dāng)然如果有你想要設(shè)置日志輸出的話,可以加一個(gè)log4j.properties,簡(jiǎn)單配置一下日志輸出:

# 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

最后運(yùn)行啟動(dòng)類Generator,運(yùn)行之前得確保,在數(shù)據(jù)庫(kù)中先創(chuàng)建好表

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

逆向工程如何使用

mapper中的方法

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

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

example類中的方法

mybatis的逆向工程中會(huì)生成實(shí)例及實(shí)例對(duì)應(yīng)的example,example用于添加條件,相當(dāng)where后面的部分

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

下表是常用方法

方法說明
example.setOrderByClause(“字段名 ASC”);添加升序排列條件,DESC為降序
example.setDistinct(false)去除重復(fù),boolean型,true為選擇不重復(fù)的記錄。
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很簡(jiǎn)單 只需要簡(jiǎn)單的配置即可以。
這里使用時(shí)xml方式,注解方式相對(duì)而言是清爽一些,但是sql全都堆砌在java文件中,并不利于閱讀,而且也沒有xml方式靈活。

項(xiàng)目構(gòu)建

這里使用的是maven來(lái)構(gòu)建項(xiàng)目,下面是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><!-- 數(shù)據(jù)庫(kù)連接池--><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的時(shí)候需要配置jdbc的信息,這里還用了阿里的連接池Druid.下面是詳細(xì)的配置信息:

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語(yǔ)句方便調(diào)試 logging.level.com.dao=DEBUG

下圖是工程結(jié)構(gòu)圖:

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

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();// 這里設(shè)置mybatis xml文件的地址sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));return sqlSessionFactoryBean.getObject();} }

測(cè)試

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

啟動(dòng)startApplication,在瀏覽器中輸入http://127.0.0.1,即可查看到結(jié)果。

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

轉(zhuǎn)載于:https://www.cnblogs.com/superfj/p/8955646.html

總結(jié)

以上是生活随笔為你收集整理的spring boot开发笔记——mybatis的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。