赞
踩
目录
3.3 application.properties配置文件
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。
- DROP TABLE IF EXISTS user;
-
- CREATE TABLE user
- (
- id BIGINT(20) NOT NULL COMMENT '主键ID',
- name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
- age INT(11) NULL DEFAULT NULL COMMENT '年龄',
- email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
- PRIMARY KEY (id)
- );
- DELETE FROM user;
-
- INSERT INTO user (id, name, age, email) VALUES
- (1, 'Jone', 18, 'test1@baomidou.com'),
- (2, 'Jack', 20, 'test2@baomidou.com'),
- (3, 'Tom', 28, 'test3@baomidou.com'),
- (4, 'Sandy', 21, 'test4@baomidou.com'),
- (5, 'Billie', 24, 'test5@baomidou.com');
- <dependencies>
- <!--mp依赖-->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.3.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- #数据源信息
- spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- # characterEncoding防止您添加到数据的数据出现乱码。
- spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
- spring.datasource.username=root
- spring.datasource.password=970812
- #指定映射文件的路径--链表操作
- mybatis.mapper-locations=classpath:mapper/*.xml
- #sql日志
- mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
- @Data
- @TableName(value = "tbl_user") //如果没有添加该注解默认实体类映射对应的表名
- public class User {
- @TableId(value = "id",type = IdType.AUTO) //标记该属性为表的主键列,属性名和主键列名映射
- private long uid;
- @TableField(value = "name") //让属性名和列名映射
- private String username;
- private Integer age;
- private String email;
-
- @TableField(exist = false) //标记数据库中没有与之对应的列
- private String hobby; //属性在数据库中不存在
- }
- @Mapper
- public interface UserDao extends BaseMapper<User> {
- }
----根据id查询
- @Autowired
- private UserDao userDao;
-
- @Test
- void testById() {
- //根据id查找员工
- User user = userDao.selectById(1);
- System.out.println(user);
- }
- @Autowired
- private UserDao userDao;
- @Test
- void testSave() {
- //添加
- User user = new User();
- user.setUsername("王五");
- user.setAge(15);
- user.setEmail("123@qq.com");
- int insert = userDao.insert(user);
- System.out.println("影响行数" + insert);
- }
注意:
mp会自动为主键生成值,默认按照雪花算法【得到的值100%不会重复】。能否修改主键的生成策略.---能---如果想使用主键自增必须要求数据库中表的主键是递增模式。
- /**
- * AUTO(0),递增 按照数据库表的主键递增模式
- * NONE(1),人为输入id值
- * INPUT(2),人为输入id值
- * ASSIGN_ID(3),默认的算法。雪花算法
- * ASSIGN_UUID(4),按照UUID生成---字符串
- */
- @TableId(type = IdType.AUTO) ---实体类中写入该注解
- @Test
- void delete() {
- //根据主键删除
- // int i = userDao.deleteById(9);
- // System.out.println("影响的行数:"+i);
- //批量删除
- // List<Integer> ids = Arrays.asList(1, 2, 7, 8);
- // int i = userDao.deleteBatchIds(ids);
- // System.out.println("影响的行数:" + i);
- UpdateWrapper<User> wrapper = new UpdateWrapper<>();//修改的条件构造器
- //wrapper.eq("name","张三"); //name="张三"
- wrapper.like("name","张"); //模糊查询
- //wrapper.gt("age", 18); //大于18 ge:大于等于 lt:小于 le:小于等于 ne:不等于
- //wrapper.between("age", 12, 15); //年龄区间:11-15之间
- userDao.delete(wrapper); //Wrapper对象:它是条件构造器
- @Test
- void testUpdate(){
- //修改操作
- User user = new User();
- user.setUid(3);
- user.setUsername("辉辉");
- user.setAge(11);
- user.setEmail("123@qq.com");
-
- int i = userDao.updateById(user);
- System.out.println("受影响的行数:"+i);
- }
- @Test
- void testSelect(){
- //批量查询
- // List<Integer> ids = Arrays.asList(1,2,4);
- // List<User> users = userDao.selectBatchIds(ids);
- // System.out.println(users);
-
- //根据条件查询,如果传递的对象为null,则查询全部
- // List<User> users = userDao.selectList(null);
- // System.out.println(users);
-
- //条件查询
- QueryWrapper<User> wrapper = new QueryWrapper<>();
- wrapper.select("name","age"); //查询指定列的值
- wrapper.orderByDesc("age");//排序
- wrapper.groupBy("name");//分组 --select只能跟聚合函数以及分组的字段
- List<User> users = userDao.selectList(wrapper);
- System.out.println(users);
- @Configuration
- public class MybatisPlusConfig {
-
- /**
- * 分页插件 MP3.3.2版本
- */
- @Bean
- public PaginationInterceptor paginationInterceptor() {
- PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
- // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
- // paginationInterceptor.setOverflow(false);
- // 设置最大单页限制数量,默认 500 条,-1 不受限制
- // paginationInterceptor.setLimit(500);
- // 开启 count 的 join 优化,只针对部分 left join
- //paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
- return paginationInterceptor;
- }
- }
- @Test
- void testSelect() {
- QueryWrapper<User> wrapper = new QueryWrapper<>();
- //分页查询
- Page<User> page = new Page<>(2,2);
- Page<User> page1 = userDao.selectPage(page, null);
- System.out.println("总条数:"+page1.getTotal());
- System.out.println("总页数:"+page1.getPages());
- System.out.println("当前页的记录:"+page1.getRecords());
- }
- @Data
- @TableName(value = "tbl_user") //如果没有添加该注解默认实体类映射对应的表名
- public class User {
- @TableId(value = "id",type = IdType.AUTO) //标记该属性为表的主键列,属性名和主键列名映射
- private long uid;
- @TableField(value = "name") //让属性名和列名映射
- private String username;
- private Integer age;
- private String email;
- private Long did;
-
- @TableField(exist = false)
- private Dept dept;
- }
- @Data
- @TableName(value = "tbl_Dept")
- public class Dept {
- @TableId(type = IdType.AUTO)
- private Long did;
- private String dname;
- }
- @Configuration
- public class MybatisPlusConfig {
- /**
- * 分页插件 MP3.3.2版本
- */
- @Bean
- public PaginationInterceptor paginationInterceptor() {
- PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
- // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
- // paginationInterceptor.setOverflow(false);
- // 设置最大单页限制数量,默认 500 条,-1 不受限制
- // paginationInterceptor.setLimit(500);
- // 开启 count 的 join 优化,只针对部分 left join
- //paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
- return paginationInterceptor;
- }
- }
--------添加分页
- @Mapper
- public interface UserDao extends BaseMapper<User> {
- /*分页*/
- IPage<User> selectByCondition(IPage<User> page ,@Param("ew") Wrapper<User> queryWrapper);
- }
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <!--namesapce的内容必须和对应的接口路径映射-->
- <mapper namespace="com.aaa.dao.UserDao">
-
- <resultMap id="myMap" type="com.aaa.pojo.User" autoMapping="true">
- <id property="uid" column="id"/>
- <result property="username" column="name"/>
- <association property="dept" javaType="com.aaa.pojo.Dept">
- <id property="did" column="did"/>
- <result property="dname" column="dname"/>
- </association>
- </resultMap>
- <!--联表查询 分页功能-->
- <select id="selectByCondition" resultMap="myMap">
- select u.*,d.* from tbl_user u join tbl_dept d on u.did = d.did
- <if test="ew!=null and ew.customSqlSegment!=null">
- ${ew.customSqlSegment}
- </if>
- </select>
- </mapper>
- @Test
- void testSelect02(){
- //联表分页查询
- IPage<User> page = new Page<>(1,3);
- QueryWrapper<User> wrapper = new QueryWrapper<>();
- wrapper.between("age",18,25);
- //IPage<User> page1 = userDao.selectByCondition(page,null);
- IPage<User> page1 = userDao.selectByCondition(page,wrapper);
- System.out.println("总条数:"+page1.getTotal());
- System.out.println("总页数:"+page1.getPages());
- System.out.println("当前页的记录:"+page1.getRecords());
- }
- <!--mp代码生成器依赖-->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-generator</artifactId>
- <version>3.3.2</version>
- </dependency>
- <dependency>
- <groupId>org.freemarker</groupId>
- <artifactId>freemarker</artifactId>
- <version>2.3.29</version>
- </dependency>
- <dependency>
- <groupId>org.apache.velocity</groupId>
- <artifactId>velocity-engine-core</artifactId>
- <version>2.3</version>
- </dependency>
- package com.aaa;
-
- 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;
-
- // 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
- public class CodeGenerator {
-
- /**
- * <p>
- * 读取控制台内容
- * </p>
- */
- 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)) {
- return ipt;
- }
- }
- throw new MybatisPlusException("请输入正确的" + tip + "!");
- }
-
- public static void main(String[] args) {
- // 代码生成器
- AutoGenerator mpg = new AutoGenerator();
-
- // 全局配置
- GlobalConfig gc = new GlobalConfig();
- String projectPath = System.getProperty("user.dir");
- gc.setOutputDir( "D:\\dev\\springboot_test06/src/main/java"); //设置输出目录
- gc.setAuthor("CCH"); //作者
- gc.setOpen(false);
- gc.setSwagger2(true); //实体属性 Swagger2 注解
- mpg.setGlobalConfig(gc);
-
- // 数据源配置
- DataSourceConfig dsc = new DataSourceConfig();
- dsc.setUrl("jdbc:mysql://localhost:3306/springboot?characterEncoding=utf8&serverTimezone=Asia/Shanghai");
- // dsc.setSchemaName("public");
- dsc.setDriverName("com.mysql.cj.jdbc.Driver");
- dsc.setUsername("root");
- dsc.setPassword("970812");
- mpg.setDataSource(dsc);
-
- // 包配置
- PackageConfig pc = new PackageConfig();
- pc.setModuleName("user");
- pc.setParent("com.aaa"); //com.aaa.user 父包+模块名
- mpg.setPackageInfo(pc);
-
- // 自定义配置
- InjectionConfig cfg = new InjectionConfig() {
- @Override
- public void initMap() {
- // to do nothing
- }
- };
-
- // 如果模板引擎是 freemarker
- String templatePath = "/templates/mapper.xml.ftl";
- // 如果模板引擎是 velocity
- // String templatePath = "/templates/mapper.xml.vm";
-
- // 自定义输出配置
- List<FileOutConfig> focList = new ArrayList<>();
- // 自定义配置会被优先输出
- focList.add(new FileOutConfig(templatePath) {
- @Override
- public String outputFile(TableInfo tableInfo) {
- // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
- return "D:\\dev\\springboot_test06" + "/src/main/resources/mapper/" + pc.getModuleName()
- + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
- }
- });
- /*
- cfg.setFileCreate(new IFileCreate() {
- @Override
- public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
- // 判断自定义文件夹是否需要创建
- checkDir("调用默认方法创建的目录,自定义目录用");
- if (fileType == FileType.MAPPER) {
- // 已经生成 mapper 文件判断存在,不想重新生成返回 false
- return !new File(filePath).exists();
- }
- // 允许生成模板文件
- return true;
- }
- });
- */
- cfg.setFileOutConfigList(focList);
- mpg.setCfg(cfg);
-
- // 配置模板
- TemplateConfig templateConfig = new TemplateConfig();
-
- // 配置自定义输出模板
- //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
- // templateConfig.setEntity("templates/entity2.java");
- // templateConfig.setService();
- // templateConfig.setController();
-
- templateConfig.setXml(null);
- mpg.setTemplate(templateConfig);
-
- // 策略配置
- StrategyConfig strategy = new StrategyConfig();
- strategy.setNaming(NamingStrategy.underline_to_camel);
- strategy.setColumnNaming(NamingStrategy.underline_to_camel);
- strategy.setEntityLombokModel(true);
- strategy.setRestControllerStyle(true);
- // 公共父类
- // 写于父类中的公共字段
- strategy.setSuperEntityColumns("id");
- strategy.setControllerMappingHyphenStyle(true);
- strategy.setTablePrefix("tbl_");
- mpg.setStrategy(strategy);
- mpg.setTemplateEngine(new FreemarkerTemplateEngine());
- mpg.execute();
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。