MybatisPlus的简单应用

1.  引入相关依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.20</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatisplus-spring-boot-starter</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-core</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.2.0</version>
        </dependency>
    </dependencies>

2. dao数据

@TableName("work_order")
@Data
@Accessors(chain = true)
@ValidateBean
public class WorkOrder {
    /**
     * 主键.
     */
    @NotNull(message = ErrorMessage.ID_IS_NULL, groups = Update.class)
    private Long id;

    /**
     * 创建时间.
     */
    private Date gmtCreate;
}

3. service层

@Component
@Slf4j
public class WorkOrderManager extends ServiceImpl<WorkOrderMapper, WorkOrder> {

}

4. map包下

public interface WorkOrderMapper extends BaseMapper<WorkOrder> {

    WorkOrder selectByPrimaryKey(Long id);

    Integer countByQuery(@Param("workOrderQuery") WorkOrderQuery workOrderQuery);
}

5、MybatisPlus的QueryWrapper和UpdateWrapper应用

QWrapper<WorkOrder> wrapper = new QWrapper<>();
        wrapper.lambda().eq(WorkOrder::getId, workOrderQuery.getId()).in(WorkOrder::getId, workOrderQuery.getIds())
            .like(WorkOrder::getAssessProjectName, workOrderQuery.getAssessProjectName())
            .eq(WorkOrder::getFillFormWorkNo, workOrderQuery.getFillFormWorkNo())
            .eq(WorkOrder::getBusinessLine, workOrderQuery.getBusinessLine())
            .eq(WorkOrder::getStatus, workOrderQuery.getStatus()).in(WorkOrder::getStatus, workOrderQuery.getStatuses())
            .in(WorkOrder::getBusinessLine, workOrderQuery.getBusinessLines())
            .eq(WorkOrder::getAssessProcessId, workOrderQuery.getAssessProcessId())
            .eq(WorkOrder::getIsDeleted, workOrderQuery.getIsDeleted());

 

6. config类

@Configuration
@MapperScan(basePackages = {"com.tiantian.datasecurity.tddl.dal.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory",
    sqlSessionTemplateRef = "sqlSessionTemplate")
@Slf4j
public class MybatisPlusConfig {

    @Primary
    @Bean(name = "sqlSessionFactory")
    public MybatisSqlSessionFactoryBean osSqlSessionFactory(@Qualifier("dataOkDataSource") DataSource dataSource,
        @Qualifier("globalConfig") GlobalConfig globalConfig,
        @Value("classpath*:/mybatis-plus/mapper/*.xml") Resource[] mapperLocations) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(mapperLocations);
        sqlSessionFactoryBean.setGlobalConfig(globalConfig);

        String sysProp = System.getProperty("spring.profiles.active", "testing");

        if (!StringUtils.containsAny(sysProp, "production", "staging")) {
            MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
            mybatisConfiguration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
            sqlSessionFactoryBean.setConfiguration(mybatisConfiguration);
        }

        sqlSessionFactoryBean.setTypeHandlers(new JSONArrayHandler(), new JSONObjectHandler());

        MybatisPlusInterceptor pageInterceptor = new MybatisPlusInterceptor();
        pageInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        Interceptor[] plugins = {new SqlRecordInterceptor(), pageInterceptor};
        sqlSessionFactoryBean.setPlugins(plugins);

        return sqlSessionFactoryBean;
    }

    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate
        osSqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "globalConfig")
    public GlobalConfig initGlobalConfig(@Qualifier("dbConfig") GlobalConfig.DbConfig dbConfig) {
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setDbConfig(dbConfig);
        return globalConfig;
    }

    @Bean(name = "dbConfig")
    public GlobalConfig.DbConfig initDbConfig() {
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setSelectStrategy(FieldStrategy.NOT_EMPTY);
        dbConfig.setIdType(IdType.AUTO);
        return dbConfig;
    }

}

7.多字段排序

  • qwrapper
    private QWrapper getQWrapper(PrivacyPolicyInterpretQO privacyPolicyInterpretQO) {
            List<SortField> sortFields = Optional.ofNullable(privacyPolicyInterpretQO.getSort()).map(Sort::getSortFields).orElse(null);
            QWrapper<PrivacyPolicyInterpretPO> wrapper = new QWrapper<>();
            LambdaQWrapper<PrivacyPolicyInterpretPO> lambdaQWrapper = wrapper.lambda().eq(PrivacyPolicyInterpretPO::getDeleteFlag, StatusEnum.ENABLE.getValue())
                    .eq(PrivacyPolicyInterpretPO::getAppId, privacyPolicyInterpretQO.getAppId())
                    .eq(PrivacyPolicyInterpretPO::getPlatform, privacyPolicyInterpretQO.getPlatform())
                    .eq(PrivacyPolicyInterpretPO::getCountry, privacyPolicyInterpretQO.getCountry())
                    .eq(PrivacyPolicyInterpretPO::getInterpreted, privacyPolicyInterpretQO.getInterpreted())
                    .lt(PrivacyPolicyInterpretPO::getVersion, privacyPolicyInterpretQO.getVersionLt())
                    .like(PrivacyPolicyInterpretPO::getVersion, privacyPolicyInterpretQO.getVersion())
                    .between(PrivacyPolicyInterpretPO::getCreateTime, privacyPolicyInterpretQO.getCreateTimeStart(), privacyPolicyInterpretQO.getCreateTimeEnd())
                    .between(PrivacyPolicyInterpretPO::getPublishDate, privacyPolicyInterpretQO.getPublishDateStart(), privacyPolicyInterpretQO.getPublishDateEnd());
            CollectionUtils.emptyIfNull(sortFields).forEach(field -> {
                ISqlSegment[] sqlSegments = {ORDER_BY, () -> field.getField(),
                        SqlKeyword.valueOf(Order.findByValue(field.getOrder().getValue()).name())};
                lambdaQWrapper.getExpression().add(sqlSegments);
            });
            return wrapper;
        }
  • xml
    <if test="query.sort != null">
                    order by
                    <trim prefixOverrides=",">
                        <foreach collection="query.sort.sortFields" item="sortField">
                            ,a.${sortField.field}
                            <choose>
                                <when test="sortField.order == @com.aliyun.opensearch.sdk.generated.search.Order@DECREASE">
                                    desc
                                </when>
                                <otherwise>
                                    asc
                                </otherwise>
                            </choose>
                        </foreach>
                    </trim>
                </if>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus是MyBatis的增强工具,在MyBatis的基础上添加了许多实用的功能,其中包括快速简单的登录功能。下面是一个简单MyBatis-Plus登录示例: 1. 创建数据库表 在数据库中创建用户表,包含用户id、用户名和密码等字段。 2. 创建实体类 创建一个User实体类,包含与数据库表对应的字段。 ```java public class User { private Integer id; private String username; private String password; // 省略getter和setter方法 } ``` 3. 创建Mapper接口 创建一个UserMapper接口,继承BaseMapper接口,该接口提供了常见的CRUD操作。 ```java public interface UserMapper extends BaseMapper<User> { User selectByUsernameAndPassword(@Param("username") String username, @Param("password") String password); } ``` 4. 创建Service层 创建一个UserService接口和实现类,实现登录功能。 ```java public interface UserService { User login(String username, String password); } @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User login(String username, String password) { User user = userMapper.selectByUsernameAndPassword(username, password); return user; } } ``` 5. 创建Controller层 创建一个LoginController,处理登录请求。 ```java @RestController public class LoginController { @Autowired private UserService userService; @PostMapping("/login") public String login(@RequestParam("username") String username, @RequestParam("password") String password) { User user = userService.login(username, password); if (user != null) { return "登录成功"; } else { return "登录失败"; } } } ``` 以上就是一个简单MyBatis-Plus登录示例。在实际应用中,还需要加入数据校验、密码加密、异常处理等功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值