mybatis plus

本文详细探讨了Mybatis Plus在Java和Spring环境中的使用,包括其核心特性、 CRUD操作、查询增强功能以及如何与Spring框架集成,帮助开发者提高开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!--连接定时器的依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
//指定扫描的包和子类
@SpringBootApplication
@EnableScheduling//开启定时注解
public class MybatiesPlusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatiesPlusApplication.class, args);
    }

}
@Component//该类交于spring容器来管理
public class QuartzTask {
    @Scheduled(cron = "0/1 * * * * ?")
    public void text(){

        System.out.println("业务代码");
    }
}
spring.datasource.druid.url=jdbc:mysql://localhost:3306/aaa?serverTimezone=GMT%2B8&&characterEncoding=utf8

spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
#??????
spring.datasource.druid.initial-size=5
#??????
spring.datasource.druid.max-active=10
#???????
spring.datasource.druid.max-wait=3000
#??????
spring.datasource.druid.min-idle=5
#?????????
mybatis.mapper-locations=classpath:/mapper/*.xml
#sql??
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
@Configuration
public class mybatisPlusInterceptor {
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
@Slf4j
@Component

public class spring implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject,"gtmCreated",()-> LocalDateTime.now(),LocalDateTime.class);//起始为3.3
        this.strictInsertFill(metaObject,"isdeleted",()-> 0,Integer.class);//起始为3.3
    }

    @Override
    public void updateFill(MetaObject metaObject) {
      this.strictUpdateFill(metaObject,"gtmUpdated",()-> LocalDateTime.now(),LocalDateTime.class);//起始为3.3
    }

}
@Mapper
public interface UserMapper extends BaseMapper<User> {

    List<User> selectUser(IPage<User> page, @Param("ew") Wrapper<User> wrapper);
}
@Data
//如果表名和实体类名不一致。@TableName(value = "tbl_user")
public class User {
    //标记该属性为主键。 value:标记列名和属性名的对应

    @TableId(value = "id")
    private Long id;
    private Integer did;
    //如果属性和列名不一样    @TableField(value = "")
    private String name;
    private Integer age;
    private String email;
    @TableLogic//逻辑列
    private Integer isdeleted;
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime gtmCreated;
    @TableField(fill = FieldFill.UPDATE)
    private LocalDateTime gtmUpdated;

    @TableField(exist = false)//该属性不存在
    private Dept dept;
}
//指定扫描的包和子类
@SpringBootApplication
@EnableScheduling//开启定时注解
public class MybatiesPlusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatiesPlusApplication.class, args);
    }

}

<?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">
<mapper namespace="com.example.mybatiesplus.dao.UserMapper">
        <resultMap id="baseMapper" type="com.example.mybatiesplus.entity.User" autoMapping="true">
                <id column="id" property="id"/>
                <association property="dept" javaType="com.example.mybatiesplus.entity.Dept" autoMapping="true">
                        <id property="did" column="did"/>
                </association>
        </resultMap>

        <select id="selectUser" resultMap="baseMapper">
                select * from user u join dept d on u.did=d.did where isdeleted =0
                <if test="ew!=null">
                    and ${ew.sqlSegment}
                </if>
        </select>
</mapper>
package com.example.mybatiesplus;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatiesplus.dao.UserMapper;
import com.example.mybatiesplus.entity.User;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.time.LocalDateTime;
import java.util.List;

@SpringBootTest
class MybatiesPlusApplicationTests {
    @Autowired//自动注入
    private UserMapper userMapper;

    @Test
    private void domeLianBiao(){
        Page<User> page = new Page<>(1,3);

        List<User> users = userMapper.selectUser(page,null);
        System.out.println("总页码:"+page.getPages());
        System.out.println("总条数:"+page.getTotal());
        System.out.println("当前记录:"+page.getRecords());
    }

    @Test
    //查询
    void contextLoads() {
        User user = userMapper.selectById(1);
        System.out.println(user);
    }
    @Test
    void isnert(){
        //添加
        User user = new User();
        user.setAge(18);
        user.setName("王文超");
        user.setEmail("6437.@qq.com");
        int insert = userMapper.insert(user);
        System.out.println(insert);
    }
    @Test
    //删除
    void delete(){
        int delete = userMapper.deleteById(1551740548321533953L);
        System.out.println(delete);
    }
    @Test
    //修改
    void update(){
        User user = new User();
        user.setId(1L);
        user.setName("xxx");
        int i = userMapper.updateById(user);
        System.out.println(i);
    }
   @Test
    //根据各种条件查询
       //Wrapper:封装了关于查询的各种条件方法。有三个子类最常用:
       // QueryWrapper查询条件  UpdateWrapper修改条件  LambdaQueryWrapper查询使用lambda表达式条件
    void selectAll(){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.between("age",15,25);//年龄15-25
        userQueryWrapper.select("name","age");//光查name  age
        userQueryWrapper.like("name","x");//查询name带有x的
        System.out.println(userMapper.selectList(userQueryWrapper));
    }
    @Test
    void selectOne(){
        //根据条件查询一条记录
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("name","xxx");
        userQueryWrapper.eq("age",18);
        System.out.println(userMapper.selectList(userQueryWrapper));
    }
    @Test
    //分页
    void textPage(){
        Page<User> page = new Page<>(1,3);
        userMapper.selectPage(page,null);
        System.out.println("总页码:"+page.getPages());
        System.out.println("总条数:"+page.getTotal());
        System.out.println("当前记录:"+page.getRecords());
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ykq</groupId>
    <artifactId>qy151-mp-generator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>qy151-mp-generator</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--mp-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
<!--        mp-->

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>
        <!--swagger依赖 要低一点的版本-->
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.7.8</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </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>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值