开发环境
| 名称 | 版本 |
|---|---|
| 操作系统 | Windows 10 X64 |
| JDK | JDK1.8(jdk-8u151-windows-x64) |
| IntelliJ IDEA | IntelliJ IDEA 2018.3 |
| Maven | Maven 3.6.0 |
| com.baomidou | mybatis-plus-boot-starter |
官网
| 项目 | 官网 |
|---|---|
| Mybatis | https://blog.mybatis.org/ http://www.mybatis.cn/ |
| Mybatis Plus | https://mybatis.plus/ |
Lambda 表达式常用方法
eq == equal 等于ne == not equal 不等于gt == greater than 大于lt == less than 小于ge == greater than or equal 大于等于le == less than or equal 小于等于in == in 包含(数组)isNull == 等于nullisNotNull == 不等于nullorderByDesc == 倒序排序orderByAsc == 升序排序or == 或者and == 并且between == 在2个条件之间(包括边界值)like == 模糊查询clear == 清除apply == 拼接sqllambda == 使用lambda表达式exists == 临时表
添加数据
这个 insert 是根据对象赋值的属性来生成 sql 语句的。
比如 payApplyHead 对象有 20 个属性,你只赋值了 2 个,最终生成的 insert 语句,只会 insert 两个字段。
public boolean add(PayApplyHead payApplyHead){//成功 result = 1,即受影响的行数int result = baseMapper.insert(payApplyHead);;return result > 0;}
添加数据返回 Id
application.yml
#mybatismybatis-plus:typeEnumsPackage:global-config:#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";id-type: 0#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"field-strategy: 2
字段
/*** 主键ID*/@ApiModelProperty(value = "主键")@TableId(type = IdType.AUTO)private Long id;
代码
这里 insert param 之后,会自动把 ID 赋值。
/*** 添加数据* @param param 数据* @return 添加成功的数据*/@Overridepublic CostPayPlan add(CostPayPlan param){baseMapper.insert(param);return param;}
推荐的批量插入 Batch Insert Support
try(SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH)) {SimpleTableMapper mapper = session.getMapper(SimpleTableMapper.class);List<SimpleTableRecord> records = getRecordsToInsert(); // not shownBatchInsert<SimpleTableRecord> batchInsert = insert(records).into(simpleTable).map(id).toProperty("id").map(firstName).toProperty("firstName").map(lastName).toProperty("lastName").map(birthDate).toProperty("birthDate").map(employed).toProperty("employed").map(occupation).toProperty("occupation").build().render(RenderingStrategies.MYBATIS3);batchInsert.insertStatements().forEach(mapper::insert);session.commit();}
修改数据
指定条件,指定列
public boolean getTest() {LambdaUpdateWrapper<SmallflowAccountLicense> wrapper = new LambdaUpdateWrapper<>();wrapper.eq(SmallflowAccountLicense::getIsDelete, Contents.NOT_DELETE);wrapper.eq(SmallflowAccountLicense::getTenantId, Contents.TENCENT_ID);List<Long> listIds = Arrays.asList(1000000L,2000000L,4000000L);wrapper.in(SmallflowAccountLicense::getId, listIds);wrapper.set(SmallflowAccountLicense::getCreateBy,"luoma");return update(wrapper);}
- 实际效果
UPDATE smallflow_account_license SET create_by='luoma'WHERE (is_delete = 0 AND tenant_id = '1' AND id IN (1000000,2000000,4000000));
update 方法只修改赋值的列
application.yml
#mybatismybatis-plus:typeEnumsPackage:global-config:#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";id-type: 0#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"field-strategy: 2
代码
只要字段赋值为 null,就不会去修改对应字段的值
/*** 修改数据* @param param 数据* @return 修改成功返回 true*/@Overridepublic CostPayPlan update(CostPayPlan param){updateById(param);return param;}
通过 xml
FinancingBankMapper.xml
<?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.tencent.finance.mapper.FinancingBankMapper"><update id="deleteAll">update financing_bankset is_delete = 1,update_time=now(), update_by = #{userName,jdbcType=VARCHAR}where is_delete = 0</update></mapper>
FinancingBankMapper
@Repositorypublic interface FinancingBankMapper extends BaseMapper<FinancingBank> {/*** 删除所有数据* @param userName 操作用户英文名* @return 返回修改成功的数据条数*/int deleteAll(@Param("userName") String userName);}
查询数据
查询指定列-Mapper.xml
<sql id="Base_Column_List">id, operate_info_id, apply_no, pay_type, pay_id, pay_way_code, pay_way_name, apply_reason,payment_postscript, amount, currency_code, contract_no, surplus_principal_amount,our_side_ou_code, our_side_ou_name, product_name_code, financing_product_no, financing_sign_contract_bank,financing_bank_of_deposit, financing_bank_account, financing_bank_swift_code, financing_bank_code,financing_bank_branch_code, transform_bank_country, transform_bank_name, transform_bank_swift_code,transform_bank_liquidation, applicant, application_date, flow_code, flow_version,flow_instance_id, approval_status_code, approval_status_name, approval_current_node,approval_pass_date, task_owner_staff_id, task_owner_english_name, task_owner_full_name,pay_status_code, pay_status_name, pay_date, push_direct_connection, is_temp_date,tenant_id, create_by, create_time, update_by, update_time, is_delete</sql><select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">select<include refid="Base_Column_List" />from financing_pay_apply_headwhere id = #{id,jdbcType=BIGINT}</select>
查询单条数据-根据列名称
QueryWrapper<Contract> wrapper = new QueryWrapper<>();wrapper.eq("is_delete",Contents.IS_DELETE);wrapper.eq("tax_account_id",taxAccountId);//避免上面的条件能查出多条数据导致 getOne 报错wrapper.last("limit 1");Contract contract = contractService.getOne(wrapper);
查询单条数据-根据 lambda 表达式
Order order = orderService.getOne(Wrappers.<Order>lambdaQuery().eq(Order::getOrderNo,taxAccount.getOrderId()).eq(Order::getTaxAccountId,taxAccount.getTaxAccountId()).eq(Order::getIsDelete,Contents.IS_DELETE));
LambdaQueryWrapper<PayApplyApproval> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(PayApplyApproval::getApplyNo,applyNo);queryWrapper.eq(PayApplyApproval::getFlowTaskId,flowTaskId);queryWrapper.eq(PayApplyApproval::getTenantId,Contents.TENCENT_ID);queryWrapper.eq(PayApplyApproval::getIsDelete,Contents.NOT_DELETE);return baseMapper.selectOne(queryWrapper);
获取指定列-通过 select
ForeignLimit limit = baseMapper.selectOne(Wrappers.<ForeignLimit>lambdaQuery().select(ForeignLimit::getBgCode, ForeignLimit::getBgName,ForeignLimit::getOuId, ForeignLimit::getOuName,ForeignLimit::getType, ForeignLimit::getUserId,ForeignLimit::getUserName).eq(ForeignLimit::getUserId, userId));
public List<AccountBankInfo> getAccountBankList(CommonDto param){LambdaQueryWrapper<AccountBankInfo> wrapper = new LambdaQueryWrapper<>();wrapper.eq(AccountBankInfo::getIsDelete, Contents.NOT_DELETE);//wrapper.eq(AccountBankInfo::getTenantId,Contents.TENCENT_ID);//因为这个表字段老是变动,我这里只获取我需要的部分wrapper.select(AccountBankInfo::getBankAccountId,AccountBankInfo::getBankAccountName,AccountBankInfo::getBankAccountNum,AccountBankInfo::getBic,AccountBankInfo::getCurrencyCode);if(CommUtil.isNotNull(param.getNo())){wrapper.like(AccountBankInfo::getBankAccountNum,param.getNo());}if(CommUtil.isNotNull(param.getName())){wrapper.like(AccountBankInfo::getBankAccountName, param.getName());}return baseMapper.selectList(wrapper);}}
效果
SELECT bank_account_id,bank_account_name,bank_account_num,bic,currency_codeFROM account_bank_infoWHERE (is_delete = ? AND bank_account_name LIKE ?);
获取指定列-通过 map 映射并赋值
/*** 获取多条数据** @param param 查询参数* @return 数据列表*/@Overridepublic List<BaseSysOuInfo> getList(OUDTO param) {LambdaQueryWrapper<BaseSysOuInfo> wrapper = getLambdaQueryWrapper(param);return baseSysOuInfoService.getBaseMapper().selectList(wrapper);}/*** 获取公共 LambdaQuery 查询参数** @param param 查询参数* @return LambdaQueryWrapper*/public LambdaQueryWrapper<BaseSysOuInfo> getLambdaQueryWrapper(OUDTO param) {LambdaQueryWrapper<BaseSysOuInfo> wrapper = new LambdaQueryWrapper<>();//wrapper.eq(BaseSysOuInfo::getTenantId, Contents.TENCENT_ID);//这个表没有启动这个字段wrapper.eq(BaseSysOuInfo::getIsDelete, Contents.NOT_DELETE);wrapper.eq(BaseSysOuInfo::getEnabledFlag, Contents.Y);if (CommUtil.isNotNull(param.getOuId())) {wrapper.eq(BaseSysOuInfo::getOrgId, param.getOuId());}if (CommUtil.isNotNull(param.getOuCode())) {wrapper.eq(BaseSysOuInfo::getOuCode, param.getOuCode());}if (CommUtil.isNotNull(param.getOuName())) {wrapper.eq(BaseSysOuInfo::getOuShortNameZhs, param.getOuName());}return wrapper;}/*** 获取 OU 数据** @return OU 列表数据*/@Overridepublic List<OuInfoVO> getOuInfo() {OUDTO param = new OUDTO();List<OuInfoVO> listData = getList(param).stream().filter(t -> t.getIsDelete().equals(Contents.NOT_DELETE)&& Contents.Y.equals(t.getEnabledFlag())).sorted(Comparator.comparingInt(BaseSysOuInfo::getOrgId)).map(item ->new OuInfoVO(item.getOuShortNameZhs(),String.valueOf(item.getOuCode()),item.getIsDomesticInvest())).collect(Collectors.toList());listData.forEach(p -> {if (null != p.getIsDomesticInvest()) {if (p.getIsDomesticInvest().equals("Y")) {p.setIsDomesticInvest("境内");} else if (p.getIsDomesticInvest().equals("N")) {p.setIsDomesticInvest("境外");}}});return listData;}
获取指定列-distinct,selectObjs
QueryWrapper<UserRole> wrapper = new QueryWrapper<>();wrapper.select("distinct user_id,role_id,authentication");wrapper.eq("is_delete", 1);wrapper.eq("user_id", Long.parseLong(userId));wrapper.orderByAsc("role_id");List<UserRole> list = baseMapper.selectList(wrapper);
或者
/*** 获取对应用户权限的 OU Code 集合* @param userId 用户 Id* @return 对应用户权限的 OU Code 集合*/public List<String> getOUCodes(String userId){if(StringUtils.isEmpty(userId)){//获取当前登录用户UserInfoVO userInfoVO = LocalProvider.getUser();userId = userInfoVO.getCreateBy();}QueryWrapper<ForeignLimit> wrapper = new QueryWrapper<>();wrapper.select("distinct ou_code");wrapper.eq("is_delete",Contents.IS_DELETE);wrapper.eq("user_id",userId);List<String> list = (List<String>)(List)baseMapper.selectObjs(wrapper);//List<Object> listObjs = baseMapper.selectObjs(wrapper);//List<String> list = null;//if(CommonUtil.isNotNull(listObjs)) {// listResult = listObjs.stream().map(String::valueOf).collect(Collectors.toList());//}return list;}
获取数据条数
Integer count = detailService.getBaseMapper().selectCount(Wrappers.<PayDetail>lambdaQuery().eq(PayDetail::getPayOrderNo, data.getPayOrderNo()).eq(PayDetail::getIsDelete, 1));
获取 List 数据
List<TaxAccountDes> listTaxAccountDes = baseMapper.selectList(Wrappers.<TaxAccountDes>lambdaQuery().eq(TaxAccountDes::getTaxAccountId,taxAccount.getTaxAccountId()).eq(TaxAccountDes::getIsDelete,Contents.IS_DELETE));
获取分页数据-使用 sql
Impl 方法
/*** 获取实物进口供应商分页数据(根据用户对应 OU 权限)* @param param 供应商信息* @return 实物进口供应商列表*/@Overridepublic ResponseVO<Page<PhysicalImport>> getPageList(TaxExemptionData param){//分页条件Page<PhysicalImport> page = new Page<>();page.setSize(param.getSize());page.setCurrent(param.getCurrent());//当前用户存在角色“购汇业务员-子公司”-限制付款方主体为其负责的主体String userId = param.getUserId();param.setIsPaymentSub(userRoleService.userIsPaymentSub(userId));if(param.getIsPaymentSub()){List<String> ouIds = foreignLimitService.getOUCodes(userId);if(CollectionUtil.isNotEmpty(ouIds)){param.setListParamStr(ouIds);}}IPage<PhysicalImport> ipageData = baseMapper.getPageList(page,param);Page<PhysicalImport> pageData = toPage(ipageData);ResponseVO<Page<PhysicalImport>> responseVO = new ResponseVO<>(ResponseCode.OK);responseVO.setData(pageData);return responseVO;}/*** 公共类- IPage 转换为 Page** @param ipageData IPage List* @param <T> 类型* @return PageList*/public static <T> Page<T> toPage(IPage<T> ipageData) {//IPage 转换为 PagePage<T> pageData = new Page<>();pageData.setRecords(ipageData.getRecords());pageData.setCurrent(ipageData.getCurrent());pageData.setSize(ipageData.getSize());pageData.setTotal(ipageData.getTotal());return pageData;}
baseMapper
@Repositorypublic interface PhysicalImportRepository extends BaseMapper<PhysicalImport> {/*** 获取实物进口供应商分页数据(根据用户对应 OU 权限)* @param param 供应商信息* @return 实物进口供应商数据*/IPage<PhysicalImport> getPageList(Page<PhysicalImport> page, @Param("param")TaxExemptionData param);}
Mapper.xml
<select id="getPageList"resultType="com.foreign.payment.common.model.PhysicalImport"parameterType="com.foreign.payment.common.data.TaxExemptionData">select *from t_fpts_physical_import<where><if test="param.contractId != null and param.contractId.trim() != ''">AND contract_no like "%"#{param.contractId}"%"</if><if test="param.supplierName != null and param.supplierName.trim() != ''">AND supplier_name like "%"#{param.supplierName}"%"</if><if test="param.isPaymentSub">AND (ou_id IN<trim suffixOverrides=" OR ou_id IN()"><foreach collection="param.listParamStr" item="ouCode" index="index" open="(" close=")"><if test="index != 0"><choose><when test="index % 1000 == 999">) OR ou_id IN(</when><otherwise>,</otherwise></choose></if>#{ouCode}</foreach></trim>)</if>AND is_delete = 1</where>order by update_time desc</select>
获取分页数据-使用 LambdaQueryWrapper
分页插件
@Configurationpublic class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}}
BaseVO
@Getter@Setter@ToString@AllArgsConstructor@NoArgsConstructorpublic class BaseVO<T> {@ApiModelProperty("总数")private Integer total;@ApiModelProperty("当前页")private Integer current;@ApiModelProperty("分页数")private Integer pageSize;@ApiModelProperty("结果集")private List<T> dataList;}
DTO
/*** 分页基础类*/@Getter@Setter@ToStringpublic abstract class WeekdayDto {@ApiModelProperty("当前页数")private Integer current;@ApiModelProperty("每页显示条数")private Integer pageSize;@ApiModelProperty("开始时间戳,精确到毫秒")private String startTime;@ApiModelProperty("结束时间戳,精确到毫秒")private String endTime;/*** 国家*/private String country;/*** 当前日期,格式:yyyy-MM-dd*/private String day;}
分页
/*** 获取分页数据* @param param 查询参数* @return 分页数据*/@Overridepublic BaseVO<Weekday> getPage(WeekdayDto param){//必填项判断if (CommUtil.isNull(param)) {throw new InternalApiException(-1, "WeekdayDto is null!");}Integer pageSize = param.getPageSize();if (CommUtil.isNull(pageSize)) {throw new InternalApiException(-1, "pageSize is null!");}Integer current = param.getCurrent();if (CommUtil.isNull(current)) {throw new InternalApiException(-1, "current is null!");}//查询参数LambdaQueryWrapper<Weekday> wrapper = new LambdaQueryWrapper<>();wrapper.eq(Weekday::getIsDelete, Contents.NOT_DELETE);wrapper.eq(Weekday::getTenantId,Contents.TENCENT_ID);if(CommUtil.isNotNull(param.getCountry())){wrapper.eq(Weekday::getCountry, param.getCountry());}if(CommUtil.isNotNull(param.getYear())){wrapper.eq(Weekday::getYear, param.getYear());}if(CommUtil.isNotNull(param.getMonth())){wrapper.eq(Weekday::getMonth, param.getMonth());}//分页参数Page<Weekday> page = new Page<>(current,pageSize);Page<Weekday> pageList = baseMapper.selectPage(page,wrapper);//返回参数BaseVO<Weekday> baseVO = new BaseVO<>();baseVO.setPageSize(pageSize);baseVO.setCurrent(current);if(CommUtil.isNotNull(pageList)){baseVO.setDataList(pageList.getRecords());baseVO.setTotal((int)pageList.getTotal());}return baseVO;}}
获取 Map 数据
Mapper.xml
<select id="selectMap" resultType="com.test.UserInfo">select id,username,nicknamefrom t_user</select>
baseMapper
@MapKey("username")Map<String, UserInfo> selectMap();
selectMaps
- 表数据
select current_step,count(*) as count, sum(id) as id_sumfrom smallflow_account_licensegroup by current_step
| current_step | count | id_sum |
|---|---|---|
| 作废 | 1 | 53 |
| 直属Leader审批 | 5 | 308 |
| 直属上级审核 | 3 | 161 |
| 结束 | 6 | 355 |
| 草稿 | 4 | 225 |
- 代码
public List<TestVO> getTest() {QueryWrapper<SmallflowAccountLicense> wrapper = new QueryWrapper<>();wrapper.eq("is_delete", Contents.NOT_DELETE);wrapper.eq("tenant_id", Contents.TENCENT_ID);wrapper.groupBy("current_step");wrapper.select("current_step,count(*) as count, sum(id) as id_sum");List<TestVO> listResult = new ArrayList<>();List<Map<String, Object>> listMap = baseMapper.selectMaps(wrapper);for (Map<String, Object> itemMap : listMap) {TestVO item = new TestVO();for (String name : itemMap.keySet()) {String value = String.valueOf(itemMap.get(name));if("current_step".equals(name)) {item.setCurrentStep(value);}if("count".equals(name)) {item.setCount(Integer.parseInt(value));}if("id_sum".equals(name)) {item.setIdSum(new BigDecimal(value));}}listResult.add(item);}return listResult;}
- 结果
[{"currentStep": "作废","count": 1,"idSum": 53},{"currentStep": "直属Leader审批","count": 5,"idSum": 308},{"currentStep": "直属上级审核","count": 3,"idSum": 161},{"currentStep": "结束","count": 6,"idSum": 355},{"currentStep": "草稿","count": 4,"idSum": 225}]
where 条件
使用 where 标签取消 where 1=1
<select id="selectGroupByEmployeeNum" resultMap="BaseResultMap" parameterType="com.dao.impl.ZcChatGroup">select*fromzc_chat_group<where><if test="id!=null">id= #{id}</if><if test="leaderNum!=null">and leader_num = #{leaderNum}</if><if test="groupType!=null">and group_type = #{groupType}</if></where></select>
这条sql执行时,如果 id 这个参数为 null,则这条语句的执行结果为
select * from zc_chat_group where leader_num = ‘xx’ and group_type = ‘xx’
这个 where 标签会知道如果它包含的标签中有返回值的话,它就会插入一个 where。
此外,如果标签返回的内容是以 AND 或 OR 开头的,则会把它去除掉。
and (.. or ..)
//查询条件QueryWrapper<TaxExemption> wrapper = new QueryWrapper<>();wrapper.eq("is_delete", Contents.IS_DELETE);if(StringUtils.isNotEmpty(param.getSupplierName())){wrapper.and(wrapperLike->wrapperLike.like("contract_party",param.getSupplierName()).or().like("chinese_name",param.getSupplierName()));}if(StringUtils.isNotEmpty(param.getContractId())){wrapper.like("contract_no",param.getContractId());}
结果
where is_delete = 1and (contract_party like '%name%' or chinese_name like '%name%')and contract_no like '%name%'
in
//根据供应商Id获取台账明细 IdList<BigDecimal> listDesId = listReceivePaySubject.stream().filter(t->t.getVendorId().equals(itemReceivePaySubject.getVendorId())).map(DesReceivePaySubject::getTaxAccountDesId).collect(Collectors.toList());if(CollectionUtil.isEmpty(listDesId)){continue;}//根据台账明细 Id 获取明细信息List<TaxAccountDes> taxAccountDesList = taxAccountDesService.list(Wrappers.<TaxAccountDes>lambdaQuery().eq(TaxAccountDes::getIsDelete,Contents.IS_DELETE).and(wrapperIn->wrapperIn.in(TaxAccountDes::getTaxAccountDesId,listDesId)));
结果
WHERE is_delete = 1 AND ( tax_account_des_id IN (20200413163224861617922000005,20200413172202617341775000006) )
in 超过 1000 行导致报错问题解决
<select id="getTransByIds" resultType="com.tencent.oa.fm.etms.receipt.server.entity.RecepitTransBean">select t.* from CUX.CUX_CE_RECEPIT_TRANSACTION t<where><if test="condition.trxIds != null and condition.trxIds.size >0">t.trx_id IN<trim suffixOverrides=" OR t.trx_id IN()"><foreach collection="condition.trxIds" item="trxId" index="index" open="(" close=")"><if test="index != 0"><choose><when test="index % 1000 == 999">) OR t.trx_id IN(</when><otherwise>,</otherwise></choose></if>#{trxId,jdbcType=DECIMAL}</foreach></trim></if></where></select>
字符串
<select id="getSmallCategoryCodeByDemision" resultType="java.lang.String">SELECT ffv.attribute2 transaction_codeFROM apps.fnd_flex_values_vl ffv, apps.fnd_flex_value_sets ffvsWHERE ffv.enabled_flag = 'Y'AND ffv.flex_value_set_id = ffvs.flex_value_set_idAND ffvs.flex_value_set_name = 'CUX_CE_EBANK_TRANSACTION_AUTH'and (ffv.description in<trim suffixOverrides=" OR ffv.description in()"><foreach collection="demisionSmallCategorys" item="demisionSmallCategory" index="index" open="(" close=")"><if test="index != 0"><choose><when test="index % 1000 == 999">) OR ffv.description in(</when><otherwise>,</otherwise></choose></if>#{demisionSmallCategory,jdbcType=VARCHAR}</foreach></trim>)</select>
if,else
choose (when,otherwize) ,相当于 java 语言中的 switch ,与 jstl 中 的 choose 很类似。
when 元素表示当 when 中的条件满足的时候就输出其中的内容,跟 JAVA 中的 switch 效果差不多的是按照条件的顺序,当 when 中有条件满足的时候,就会跳出 choose,即所有的 when 和 otherwise 条件中,只有一个会输出
当所有的我很条件都不满足的时候就输出 otherwise 中的内容
<choose><when test="condition.trxId != null and condition.trxId != 0">and Trx_id = #{condition.trxId,jdbcType=DECIMAL}</when><otherwise><if test="condition.trxIds != null and condition.trxIds.size >0" >and Trx_id in<trim suffixOverrides=" or Trx_id in()"><foreach collection="condition.trxIds" item="id" index="index" open="(" close=")"><if test="index != 0"><choose><when test="index % 1000 == 999">) or Trx_id in(</when><otherwise>,</otherwise></choose></if>#{id,jdbcType=DECIMAL}</foreach></trim></if></otherwise></choose>
传入参数值 trxIds = 57315893,1592541
解析 sql 为
select *FROM cux.cux_ce_payment_write_offWHERE Trx_id in ( 57315893 , 1592541 )
同时传入参数值 trxId = ‘778367’, trxIds = 57315893,1592541
解析 sql 为
select *FROM cux.cux_ce_payment_write_offWHERE Trx_id = 778367;
排序
//查询条件QueryWrapper<SupplierInfo> wrapper = new QueryWrapper<>();wrapper.eq("is_delete",1);if(param.getSupplierId() != null && !StringUtil.isBlank(param.getSupplierId())) {wrapper.like("supplier_code", param.getSupplierId());}if(param.getSupplierName() != null && !StringUtil.isBlank(param.getSupplierName())){wrapper.like("supplier_name",param.getSupplierName());}wrapper.orderByDesc("update_time");
通用方法
日期字段格式化
@DateTimeFormat(pattern="yyyy-MM-dd")//页面写入数据库时格式化@JSONField(format="yyyy-MM-dd")//数据库导出页面时json格式化
xml 映射文件参数值
| 方式 | 说明 |
|---|---|
取值方式: ${} |
Statement:必须使用字符串拼接方式操作 sql,一定要注意单引号问题 |
取值方式:#{} |
PreparedStatement:可以使用通配符操作 sql,因为在使用 String 赋值时,可以自动加单引号,因此不需要注意单引号问题。 |
命名参数:@Param("param") |
当传输多个参数时,mybatis 会默认将这些参数放在 map 集合中,可以通过 @Param("param") 为 map 集合指定键的名字 |
例子:
WaitTodoHandRepository.java
public interface WaitTodoHandRepository extends BaseMapper<WaitTodoHand> {/*** 待办转交* @param page 分页信息* @param param 用户信息* @return 分页数据*/IPage<WaitTodoHandVO> waitTodoHand(Page<WaitTodoHandVO> page, @Param("param")UserData param);}
WaitTodoHandMapper.xml
<!-- 查询指定用户的待办转交--><select id="waitTodoHand"resultType="com.foreign.payment.common.vo.WaitTodoHandVO"parameterType="com.foreign.payment.common.data.UserData">select distinct handle_user_id,handle_user_name,handle_user_fullname,hand_user_id,hand_user_name,hand_user_fullname, DATE_FORMAT(begin_time,'%Y-%m-%d') as begin_time,DATE_FORMAT(end_time,'%Y-%m-%d') as end_time,create_timefrom t_fpts_wait_todo_handwhere is_delete = 1and is_valid = 1<![CDATA[ and DATE_FORMAT(NOW(),'%Y-%m-%d') <= DATE_FORMAT(end_time,'%Y-%m-%d') ]]>and (handle_user_id = #{param.staffId})</select>
xml 映射文件 if test
不等于
WHERE enable =1<if test="keyword != null and keyword != ''">AND ( mac_id = #{keyword} )OR ( user_id = #{keyword} )</if>
test="keyword != null and keyword != ''" 中 and 必须小写,否则会报错
mybatis:org.apache.ibatis.ognl.ParseException: Encountered " <IDENT> "AND "" at line 1, column 26
等于
这里要用 ==,单个 = 不行相当于赋值,这个条件会永远成立
<if test="keyword == 'DDDDD'">,AND ( mac_id = #{keyword} )</if>
另外,当 == 单个字符时,需要 .toString() 一下,否则会转换为数据判断导致报错,例如:
<if test="keyword == 'D'">,AND ( mac_id = #{keyword} )</if>
会报错
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:### Error querying database. Cause: java.lang.NumberFormatException: For input string: "D"### Cause: java.lang.NumberFormatException: For input string: "D"
需要修改为
<if test="keyword == 'D'.toString()">,AND ( mac_id = #{keyword} )</if>
xml 映射文件返回值为 List String
1.Repository
List<String> getUserRole(@Param("param") String param);
2.Maper xml
<select id="getUserRole"resultType="java.lang.String"parameterType="java.lang.String">select auth_role.codefrom auth_user_role,auth_rolewhere auth_user_role.user_id = auth_role.idand auth_user_role.user_id = #{param}</select>
insert values 字符中 () 丢失
这里我
lastUpdateLogin = 1attribute1 = 'luoma(罗马)'
<trim prefix="values(" suffix=")" suffixOverrides=","><if test="lastUpdateLogin != null">#{lastUpdateLogin,jdbcType=DECIMAL},</if><if test="attribute1 != null">#{attribute1,jdbcType=VARCHAR},</if></trim>
mybatis 解析后的 sql 为
values(10728, luoma );
把我括号弄丢了,解决办法
values(<trim suffixOverrides=","><if test="lastUpdateLogin != null">#{lastUpdateLogin,jdbcType=DECIMAL},</if></trim><if test="attribute1 != null">,'${attribute1}'</if>)
mybatis 解析后的 sql 为
values(10728, 'luoma(罗马)' );
属性不映射数据库表字段
@TableField(exist = false) //不映射数据库表private String financingCategorySubIsSofr;