In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail how Springboot can access the database through Mybatis and Mybatis-plus. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
1. Create SpringBoot Project 1.1 to introduce dependencies
Pom.xml
4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.3.RELEASE com.gcl vue_day03_admin 1.0-SNAPSHOT UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-web Com.baomidou mybatis-plus-boot-starter 3.2.0 com.baomidou mybatis-plus-generator 3.2.0 org.freemarker freemarker mysql mysql-connector-java 5.1.46 com.alibaba druid-spring-boot-starter 1.1.21 org.projectlombok lombok true org.springframework.boot spring-boot-starter-test Test org.apache.commons commons-lang3 3.10 org.springframework.boot spring-boot-maven-plugin 1.2 write configuration files
Application.yml
Server: port: 8088spring: datasource: driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://192.168.0.131:3306/vue_day03?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC username: root password: Root@123456mybatis-plus: type-aliases-package: com.gcl.entity configuration: map-underscore-to-camel-case: true use-generated-keys: true log-impl: Org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath:com/gcl/mapper/*Mapper.xmllogging: level: com.demo.mapper: debug2. Write MybatisPlus code generation tool classes
2.1 write code to generate tool classes
CodeGenerator.java
Package com.gcl.utils;import com.baomidou.mybatisplus.annotation.DbType;import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;import com.baomidou.mybatisplus.core.toolkit.StringPool;import com.baomidou.mybatisplus.generator.AutoGenerator;import com.baomidou.mybatisplus.generator.InjectionConfig;import com.baomidou.mybatisplus.generator.config.*;import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;import com.baomidou.mybatisplus.generator.config.po.TableInfo;import com.baomidou.mybatisplus.generator.config.rules.IColumnType Import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;import org.apache.commons.lang3.StringUtils;import java.util.ArrayList;import java.util.List;import java.util.Scanner;// executes main method console input module table name enter to automatically generate public class CodeGenerator {/ * in the corresponding project directory
* read console contents *
* / public static String scanner (String tip) {Scanner scanner = new Scanner (System.in); StringBuilder help = new StringBuilder (); help.append ("Please enter" + tip + ":"); System.out.println (help.toString ()); if (scanner.hasNext ()) {String ipt = scanner.next () If (StringUtils.isNotEmpty (ipt)) {return ipt;}} throw new MybatisPlusException ("Please enter correct" + tip + "!") ;} public static void main (String [] args) {/ / Code Generator AutoGenerator mpg = new AutoGenerator (); / / Global configuration GlobalConfig gc = new GlobalConfig (); String projectPath = System.getProperty ("user.dir"); gc.setOutputDir (projectPath + "/ vue_day03_admin/src/main/java"); gc.setAuthor ("gcl") / / whether to open the output directory, default true gc.setOpen (false); / / enable ActiveRecord mode, default false gc.setActiveRecord (true); / / whether to overwrite the existing file gc.setFileOverride (true); / / XML enable BaseResultMap gc.setBaseResultMap (true); / / XML enable baseColumnList gc.setBaseColumnList (true) / / Custom file naming, note that% s will automatically populate the table entity attributes! / / gc.setMapperName ("% sDao"); / / gc.setXmlName ("% sMapper"); gc.setServiceName ("% sService"); / / gc.setServiceImplName ("% sServiceDiy"); / / gc.setControllerName ("% sAction"); mpg.setGlobalConfig (gc); / / data source configuration DataSourceConfig dsc = new DataSourceConfig (); dsc.setDbType (DbType.MYSQL) Dsc.setUrl ("jdbc:mysql://192.168.0.131:3306/vue_day03?useUnicode=true&useSSL=false&characterEncoding=utf8"); dsc.setDriverName ("com.mysql.jdbc.Driver"); dsc.setUsername ("root"); dsc.setPassword ("Root@123456") Dsc.setTypeConvert (new MySqlTypeConvert () {/ / Custom database table field type conversion [optional] @ Override public IColumnType processTypeConvert (GlobalConfig globalConfig, String fieldType) {System.out.println ("conversion type:" + fieldType); / / Note! There is a default type conversion in processTypeConvert. If it is not the effect you want, please customize the return, otherwise return directly as follows. Return super.processTypeConvert (globalConfig, fieldType);}}); mpg.setDataSource (dsc); / / package configuration PackageConfig pc = new PackageConfig (); / / com.demo.user pc.setParent ("com"); / / pc.setModuleName ("user"); pc.setModuleName (scanner ("module name")); mpg.setPackageInfo (pc) / / Custom configuration InjectionConfig cfg = new InjectionConfig () {@ Override public void initMap () {/ / TODO}}; mpg.setCfg (cfg); / / if the template engine is freemarker String templatePath = "/ templates/mapper.xml.ftl" / / Custom output configuration List focList = new ArrayList (); / / Custom configuration will be given priority to output focList.add (new FileOutConfig (templatePath) {@ Override public String outputFile (TableInfo tableInfo) {/ / Custom output filename). If you set the suffix for Entity, notice here that the name of xml will change accordingly! Return projectPath + "/ vue_day03_admin/src/main/resources/com/gcl/mapper" + "/" + tableInfo.getEntityName () + "Mapper" + StringPool.DOT_XML;}}); cfg.setFileOutConfigList (focList); mpg.setCfg (cfg); / / configuration template TemplateConfig templateConfig = new TemplateConfig (); templateConfig.setXml (null) Mpg.setTemplate (templateConfig); / / Policy configuration StrategyConfig strategy = new StrategyConfig (); strategy.setEntityLombokModel (true); strategy.setRestControllerStyle (true); / / you can modify it here to your table prefix strategy.setTablePrefix (new String [] {"tb_", "tsys_", "t _"}) / / Table name generation strategy strategy.setNaming (NamingStrategy.underline_to_camel); / / tables to be generated strategy.setInclude (scanner ("Table name, multiple English comma division") .split (","); / / strategy.setInclude (new String [] {"tb_user"}); strategy.setEntityBuilderModel (true); mpg.setStrategy (strategy) Mpg.setTemplateEngine (new FreemarkerTemplateEngine ()); mpg.execute ();}} 2.2 create databases and tables
Create table statement
CREATE TABLE `t _ user` (`id` int (60) NOT NULL AUTO_INCREMENT COMMENT 'key', `username` varchar (255) DEFAULT NULL COMMENT 'name', `salary` double (7recover2) DEFAULT NULL COMMENT 'salary', `age`int (11) DEFAULT NULL, `y`varchar (255) DEFAULT NULL COMMENT 'description', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;2.3 test code generator
Execute the main method in the CodeGenerator class
Results after the execution of the code generator
3. Add paging configuration
MyBatisPlusConfig.java
Package com.gcl.config;import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @ ClassName MyBatisPlusConfig * @ Description TODO * @ Author gcl * @ Date 2021-03-18 8:36 * * / @ Configurationpublic class MyBatisPlusConfig {/ * mybatis-plus paging plug-in * / @ Bean public PaginationInterceptor paginationInterceptor () {PaginationInterceptor paginationInterceptor = new PaginationInterceptor () Return paginationInterceptor;}}
4. The test provider fetches data from the database (with paging)
4.1 add 5 pieces of data to the database
INSERT INTO `vue_ day03`.`t _ user` (`id`, `username`, `salary`, `age`, `room`) VALUES ('1Qing,' Zhang San', '2000.00,' 23', 'born in May 1995'); INSERT INTO `vue_ day03`.`t _ user` (`id`, `username`, `salary`, `age`, `room`) VALUES ('2Qin,' Li Si', '3000.005', '24Qing,' born in 1996') INSERT INTO `vue_ day03`.`t _ user` (`id`, `username`, `salary`, `age`, `room`) VALUES ('3Qing,' Wangwu', '4000.00515,' 2503, '007'); INSERT INTO `vue_ day03`.`t _ user` (`id`, `username`, `salary`, `age`, `room`) VALUES ('4Li,' Zhao Liu', '5000.005,' 26Qing, born in August 2008') INSERT INTO `vue_ day03`.`t _ user` (`id`, `username`, `salary`, `age`, `room`) VALUES ('515,' Tian Qi', '6000.005,' 279, born in September 2009')
4.2 write query methods
Package com.gcl.controller;import com.baomidou.mybatisplus.core.conditions.query.Query;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.gcl.entity.User;import com.gcl.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping Import org.springframework.web.bind.annotation.RestController;import java.util.List;/** *
* Front-end controller *
* * @ author gcl * @ since 2021-04-10 * / @ RestController@RequestMapping ("/ user") public class UserController {@ Autowired private UserService userService; / * * @ param pageNo current page * @ param pageSize number of records displayed per page * @ return * / @ GetMapping public List findList (int pageNo,int pageSize) {/ / create query condition wrapper QueryWrapper wrapper = new QueryWrapper () Page page = new Page (pageNo, pageSize); IPage iPage = userService.page (page, wrapper); List records = iPage.getRecords (); return records }} this is the end of the article on "how Springboot implements database access through Mybatis and Mybatis-plus". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.