MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window) 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

mybatis parallestream 禁用 mybatis plus not in_java

首先我们需要又java的开发环境,熟悉springboot框架及maven。

然后正式开始,先建立数据库,这里在后期运行的时候会有一个坑,后来再说。

建立数据库语句,我个人用的是可视化的navicat,点击查询然后新建查询

mybatis parallestream 禁用 mybatis plus not in_spring boot_02

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');

 数据库的操作完成,然后建立一个springboot项目,然后导入依赖

<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>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

 然后编写配置文件

spring.profiles.active=dev
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&severTimezone=GMT%2B8&allowPublicKeyRetrieval=true

然后在启动类扫描包

@SpringBootApplication
@MapperScan("(包名)例如(com.baomidou.mybatisplus.samples.quickstart.mapper)")
public class Application {

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

}

编写实体类,使用的lombok,lombok的依赖已经在前面导入,也可以加上@AllArgsConstructor @NoArgsConstructor,这两个注解为无参构造和有参构造

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

然后编写Mapper,为UserMapper,如果运行出现问题加上@Repository 注解 或者@Mapper 注解,表明这是一个持久层,这里的话可以点进去BaseMapper查看源码可以发现里面已经封装好了大量的sql语句,基本的CRUD操作已经不需要我们做了,到这里mybatis——plus的快速开始已经结束,开始测试

public interface UserMapper extends BaseMapper<User> {

}

 编写测试类

mybatis parallestream 禁用 mybatis plus not in_java_03

@SpringBootTest
public class SampleTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<User> userList = userMapper.selectList(null);
        Assert.assertEquals(5, userList.size());
        userList.forEach(System.out::println);
    }

}

测试输出结果:

User(id=1, name=Jone, age=18, email=test1@baomidou.com)
User(id=2, name=Jack, age=20, email=test2@baomidou.com)
User(id=3, name=Tom, age=28, email=test3@baomidou.com)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
User(id=5, name=Billie, age=24, email=test5@baomidou.com)

前面提到的一个坑就是mysql的版本问题,我最开始使用的是5.0版本,发现运行总是报错,控制台输出

Error creating bean with name 'sqlSessionFactory' defined in class path 后边还有一堆,但是我的问题解决之后才想到写个博客记录一下,所以完整的找不到了。

然后更换了mysql的最新版本后发现问题解决了,但是报了另外一个错误就是CLIENT_PLUGIN_AUTH is required  这个问题需要在url后边加上&allowPublicKeyRetrieval=true以及最新版本必须配置时区&severTimezone=GMT%2B8

mybatis-plus暂时关闭分页查全部:

将传入的page参数的pageSize设为 -1 即可  就是查全部

mybatis-plus的@TableLogic注解:

加上这个注解之后

1、在实体类中属性加上@TableLogic注解,表示该字段是逻辑删除字段。
2、增加注解后调用BaseMapper的deleteById(id)或者IService的removeById(id),是逻辑删除。如果没有增加该注解,是真删除。
3、@TableLogic注解参数
 value = “未删除的值,默认值为0”
 delval = “删除后的值,默认值为1”
 如果不设置,就使用默认值
4、 当使用了@TableLogic注解,调用update方法修改该字段的值是不会将该字段放入修改字段中,而是在条件字段中where条件后。

 使用jdbc查询

try (Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)) {
    try (Statement stmt = conn.createStatement()) {
        try (ResultSet rs = stmt.executeQuery("SELECT id, grade, name, gender FROM students WHERE gender=1")) {
            while (rs.next()) {
                long id = rs.getLong(1); // 注意:索引从1开始
                long grade = rs.getLong(2);
                String name = rs.getString(3);
                int gender = rs.getInt(4);
            }
        }
    }
}

使用sqlSession

@Component
 public class SqlSessionService {    private final SqlSessionFactory sqlSessionFactory;
    @Autowired
     public SqlSessionService(SqlSessionFactory sqlSessionFactory) {
         this.sqlSessionFactory = sqlSessionFactory;
     }    /**
      * 使用sqlSession查询控制表数据
      * @param paramMap 查询条件
      */
     public List<ControlTableCell> executeSql(Map<String, Object> paramMap) throws SQLException {
         List<ControlTableCell> objectList = new ArrayList<>();
         try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
             MappedStatement mappedStatement = sqlSession.getConfiguration().getMappedStatement("com.rongda.process.dal.mapper.controlTable.RpaControlTableCellMapper.controlTableSearch");
            //获取未拼接参数的sql
             BoundSql boundSql = mappedStatement.getBoundSql(paramMap);
             PreparedStatement preparedStatement = sqlSession.getConnection().prepareStatement(boundSql.getSql());
             //为sql拼接参数
             ParameterHandler parameterHandler = sqlSession.getConfiguration().newParameterHandler(mappedStatement, paramMap, boundSql);
             parameterHandler.setParameters(preparedStatement);
             //执行查询获取结果
             ResultSet resultSet = preparedStatement.executeQuery();
             while (resultSet.next()) {
                 ControlTableCell controlTableCell = new ControlTableCell();
                 controlTableCell.setId(resultSet.getLong("id"));
                 controlTableCell.setRelevanceStatus(resultSet.getInt("relevance_status"));
                 controlTableCell.setControlTableId(resultSet.getLong("control_table_id"));
                 controlTableCell.setControlTableCellMergeId(resultSet.getLong("control_table_cell_merge_id"));
                 controlTableCell.setChainOfEvidenceTypeId(resultSet.getLong("chain_of_evidence_type_id"));
                 controlTableCell.setChainOfEvidenceFieldId(resultSet.getLong("chain_of_evidence_field_id"));
                 controlTableCell.setRowIndex(resultSet.getInt("row_index"));
                 controlTab

使用 下列写法的时候,要注意select,只能写一条,如果写多条的话,后边的会将上一个覆盖

LambdaQueryWrapper<FileSortHitConfigPo> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.select(FileSortHitConfigPo::getName,FileSortHitConfigPo::getHitConfig);
queryWrapper.eq(FileSortHitConfigPo::getFileSortTaskId, fileSortTaskId);
自动填充注解@TableField(fill = FieldFill.INSERT)

自定义填充策略

@Component
public class MybatisColumnHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName("createTime", metaObject);
        if (createTime != null) {
            this.setFieldValByName("createTime", createTime, metaObject);
        } else {
            this.setFieldValByName("createTime", new Date(), metaObject);
        }
        this.setFieldValByName("modifyTime", new Date(), metaObject);
        this.setFieldValByName("deleted", DeleteEnum.DEFAULT.getStatus(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("modifyTime", new Date(), metaObject);
    }
}

以上就是常见错误及mybatis-plus的快速入门