MyBatisPlus详解lambdaQuery、lambdaUpdate、批量新增、代码生成、Db静态工具、逻辑删除
    		       		warning:
    		            这篇文章距离上次修改已过431天,其中的内容可能已经有所变动。
    		        
        		                
                在MyBatis-Plus中,LambdaQueryWrapper、LambdaUpdateWrapper是用于操作数据库的工具,可以避免硬编码,提高代码可读性和可维护性。
- LambdaQueryWrapper用法示例:
 
List<User> users = new LambdaQueryWrapper<User>()
    .eq(User::getName, "张三")
    .list();- LambdaUpdateWrapper用法示例:
 
int result = new LambdaUpdateWrapper<User>()
    .set(User::getName, "李四")
    .eq(User::getId, 1)
    .update();- 批量新增示例:
 
List<User> userList = new ArrayList<>();
userList.add(new User(null, "王五"));
userList.add(new User(null, "赵六"));
userMapper.insertBatchSomeColumn(userList);其中insertBatchSomeColumn是MyBatis-Plus自动生成的批量插入方法,只会插入非null的字段。
- 代码生成器示例:
 
public class MyBatisPlusGenerator {
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
 
        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
        globalConfig.setAuthor("程序员");
        globalConfig.setOpen(false); // 是否打开目标路径
        mpg.setGlobalConfig(globalConfig);
 
        // 数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("password");
        mpg.setDataSource(dataSourceConfig);
 
        // 包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setModuleName("module"); // 模块名
        packageConfig.setParent("com.example");
        packageConfig.setEntity("entity");
        packageConfig.setMapper("mapper");
        mpg.setPackageInfo(packageConfig);
 
        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setRestControllerStyle(true);
        mpg.setStrategy(strategyConfig);
 
        // 执行生成
        mpg.execute();
    }
}- Db工具类示例:
 
public class DbUtils {
    public static void main(Str           
评论已关闭