1.确保项目启动成功
pom依赖
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.44version>
dependency>
添加依赖时可能遇到的问题:
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-surefire-pluginartifactId>
<configuration>
<skipTests>trueskipTests>
configuration>
plugin>
若遇到其他情况也有可能会是版本问题可以尝试降低springboot版本到3.0以下
application.yml
mybatis:
mapper-locations: classpath:mappers/**/*.xml
type-aliases-package: com.zking.testspringboot03.mybatis.entity
server:
port: 8082
spring:
application:
name: testspringboot03
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
password: 123456
username: root
logging:
level:
com.zking.testspringboot03: debug
2.代码生成
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
generatorConfig.xml
DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<properties resource="jdbc.properties"/>
<classPathEntry location="D:\\SoftwareInstallPath\\repository\\mvn_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
<context id="infoGuardian">
<commentGenerator>
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
commentGenerator>
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
javaTypeResolver>
<javaModelGenerator targetPackage="com.zking.testspringboot03.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="false"/>
<property name="constructorBased" value="true"/>
<property name="trimStrings" value="false"/>
<property name="immutable" value="false"/>
javaModelGenerator>
<sqlMapGenerator targetPackage="/mappers"
targetProject="src/main/resources">
<property name="enableSubPackages" value="false"/>
sqlMapGenerator>
<javaClientGenerator targetPackage="com.zking.testspringboot03.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
javaClientGenerator>
<table schema="" tableName="t_mvc_book" domainObjectName="Book"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
table>
context>
generatorConfiguration>
pom.xml
<plugin>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.2version>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.44version>
dependency>
dependencies>
<configuration>
<overwrite>trueoverwrite>
configuration>
plugin>
3.测试
利用Eolink进行测试
package com.zking.testspringboot03.web;
import com.zking.testspringboot03.mapper.BookMapper;
import com.zking.testspringboot03.model.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author小李飞刀
* @site www.javaxl.com
*/
@RestController
@RequestMapping("/jdbc")
public class JdbcController {
@Autowired
public BookMapper bookMapper;
@GetMapping("/get")
public Book list(Integer bid){
return bookMapper.selectByPrimaryKey(bid);
}
@DeleteMapping("/delete")
public int delete(Integer bid){
return bookMapper.deleteByPrimaryKey(bid);
}
@PutMapping("/add")
public int add(Book book){
return bookMapper.insertSelective(book);
}
}
启动类
@MapperScan("com.zking.testspringboot03.mapper")
@EnableTransactionManagement
@SpringBootApplication
public class Testspringboot03Application {
public static void main(String[] args) {
SpringApplication.run(Testspringboot03Application.class, args);
}
}
官网
https://baomidou.com/
pom.xml
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.4.2version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.4.1version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.31version>
dependency>
application.yml
server:
port: 8082
spring:
application:
name: testspringboot03
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
password: 123456
username: root
logging:
level:
com.zking.demo: debug
mybatis-plus:
mapper-locations: classpath:mappers/**/*.xml
type-aliases-package: com.zking.demo.book.model
package com.zking.demo.mp;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* mybatis-plus代码生成
*/
public class MPGenerator {
/**
*
* 读取控制台内容
*
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip);
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
if ("quit".equals(ipt)) return "";
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 1.全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir") + "/testspboot03";
System.out.println(projectPath);
gc.setOutputDir(projectPath + "/src/main/java");
gc.setOpen(false);
gc.setBaseResultMap(true);//生成BaseResultMap
gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
//gc.setSwagger2(true); //实体属性 Swagger2 注解
gc.setAuthor("lky");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
gc.setIdType(IdType.AUTO);
mpg.setGlobalConfig(gc);
// 2.数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 3.包配置
PackageConfig pc = new PackageConfig();
String moduleName = scanner("模块名(quit退出,表示没有模块名)");
if (StringUtils.isNotBlank(moduleName)) {
pc.setModuleName(moduleName);
}
pc.setParent("com.zking.demo")
.setMapper("mapper")
.setService("service")
.setController("controller")
.setEntity("model");
mpg.setPackageInfo(pc);
// 4.自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
if (StringUtils.isNotBlank(pc.getModuleName())) {
return projectPath + "/src/main/resources/mappers/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
} else {
return projectPath + "/src/main/resources/mappers/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 5.策略配置
StrategyConfig strategy = new StrategyConfig();
// 表名生成策略(下划线转驼峰命名)
strategy.setNaming(NamingStrategy.underline_to_camel);
// 列名生成策略(下划线转驼峰命名)
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 是否启动Lombok配置
strategy.setEntityLombokModel(true);
// 是否启动REST风格配置
strategy.setRestControllerStyle(true);
// 自定义实体父类strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
// 自定义service父接口strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
// 自定义service实现类strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
// 自定义mapper接口strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
strategy.setSuperEntityColumns("id");
// 写于父类中的公共字段plus
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
//表名前缀(可变参数):“t_”或”“t_模块名”,例如:t_user或t_sys_user
strategy.setTablePrefix("t_", "t_sys_");
//strategy.setTablePrefix(scanner("请输入表前缀"));
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 执行
mpg.execute();
}
}
生成出来的代码如下
MvcBookMapper.xml
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zking.demo.book.mapper.MvcBookMapper">
<resultMap id="BaseResultMap" type="com.zking.demo.book.model.MvcBook">
<id column="bid" property="bid" />
<result column="bname" property="bname" />
<result column="price" property="price" />
resultMap>
<sql id="Base_Column_List">
bid, bname, price
sql>
mapper>
MvcBookMapper.java
package com.zking.demo.book.mapper;
import com.zking.demo.book.model.MvcBook;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface MvcBookMapper extends BaseMapper<MvcBook> {
}
MvcBookService.java
package com.zking.demo.book.service;
import com.zking.demo.book.model.MvcBook;
import com.baomidou.mybatisplus.extension.service.IService;
public interface MvcBookService extends IService<MvcBook> {
}
MvcBookServiceImpl.java
package com.zking.demo.book.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zking.demo.book.mapper.MvcBookMapper;
import com.zking.demo.book.model.MvcBook;
import com.zking.demo.book.service.MvcBookService;
import org.springframework.stereotype.Service;
@Service
public class MvcBookServiceImpl extends ServiceImpl<MvcBookMapper, MvcBook> implements MvcBookService {
}
MvcBookController.java
package com.zking.demo.book.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/book/mvc-book")
public class MvcBookController {
}
完成基本增删改查方法开发
MvcBookController.java开发
package com.zking.demo.book.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zking.demo.book.model.MvcBook;
import com.zking.demo.book.service.MvcBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* 前端控制器
*
*
* @author lky
* @since 2022-10-30
*/
@RestController
@RequestMapping("/book")
public class MvcBookController {
@Autowired
private MvcBookService bookService;
// 查询所有
@GetMapping("/list")
public List<MvcBook> list(){
return bookService.list();
}
// 按条件查询
@GetMapping("/ListByCondition")
public List<MvcBook> ListByCondition(MvcBook book){
QueryWrapper w = new QueryWrapper();
w.like("bname",book.getBname());
return bookService.list(w);
}
// 查询单个
@GetMapping("/load")
public MvcBook load(MvcBook book){
QueryWrapper w = new QueryWrapper();
w.like("bid",book.getBid());
return bookService.getOne(w);
}
// 增加
@PutMapping("/add")
public boolean add(MvcBook book){
boolean save = bookService.save(book);
return save;
}
// 修改
@PostMapping("/update")
public boolean update(MvcBook book){
boolean save = bookService.saveOrUpdate(book);
return save;
}
// 删除
@DeleteMapping("/delete")
public boolean delete(MvcBook book){
boolean save = bookService.removeById(book.getBid());
return save;
}
// 连表查询
@GetMapping("/userRole")
public List<Map> userRole(String uname){
Map map = new HashMap();
map.put("username",uname);
List<Map> maps = bookService.queryUserRole(map);
return maps;
}
}
完成之后用Eolink进行测试
Mybatis-plus中依然可以兼容使用Mybatis的相关功能,测试代码如下
public interface MvcBookService extends IService<MvcBook> {
List<Map> queryUserRole(Map map);
}
@Service
public class MvcBookServiceImpl extends ServiceImpl<MvcBookMapper, MvcBook> implements MvcBookService {
@Autowired
private MvcBookMapper bookMapper;
public List<Map> queryUserRole(Map map){
return bookMapper.queryUserRole(map);
}
}
@Repository
public interface MvcBookMapper extends BaseMapper<MvcBook> {
List<Map> queryUserRole(Map map);
}
<select id="queryUserRole" parameterType="java.util.Map" resultType="java.util.Map">
SELECT u.username,r.rolename FROM t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
where u.userid = ur.userid and ur.roleid = r.roleid
<if test="username != null and username != ''">
and u.username = #{username}
if>
select>