场景描述
在实际业务场景中,存在复杂SQL的情况,具体表现为:
- 单表单SQL满足不了的情况下
- 有复杂的Join关系或者子查询
- 复杂SQL的逻辑通过程序逻辑难以实现或实现代价较大
在此情况下,通过原生的mybatis/mybatis-plus, 自定义Mapper的方式实现业务功能
1、编写所需的Mapper
SQL Mapper写法无限制,与使用原生的mybaits/mybaits-plus用法一样; Mapper(DAO)和SQL可以写在一个文件中,也分开写在两个文件中。
package pro.shushi.pamirs.demo.core.map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
@Mapper
public interface DemoItemMapper {
@Select("<script>select sum(item_price) as itemPrice,sum(inventory_quantity) as inventoryQuantity,categoryId from ${demoItemTable} as core_demo_item ${where} group by category_id</script>")
List<Map<String, Object>> groupByCategoryId(@Param("demoItemTable") String pamirsUserTable, @Param("where") String where);
}
2.调用mapper
调用Mapper代码示例
package pro.shushi.pamirs.demo.core.map;
import com.google.api.client.util.Lists;
import org.springframework.stereotype.Component;
import pro.shushi.pamirs.demo.api.model.DemoItem;
import pro.shushi.pamirs.framework.connectors.data.api.datasource.DsHintApi;
import pro.shushi.pamirs.meta.api.core.orm.convert.DataConverter;
import pro.shushi.pamirs.meta.api.session.PamirsSession;
import pro.shushi.pamirs.meta.common.spring.BeanDefinitionUtils;
import java.util.List;
import java.util.Map;
@Component
public class DemoItemDAO {
public List<DemoItem> customSqlDemoItem(){
try (DsHintApi dsHint = DsHintApi.model(DemoItem.MODEL_MODEL)) {
String demoItemTable = PamirsSession.getContext().getModelCache().get(DemoItem.MODEL_MODEL).getTable();
DemoItemMapper demoItemMapper = BeanDefinitionUtils.getBean(DemoItemMapper.class);
String where = " where status = 'ACTIVE'";
List<Map<String, Object>> dataList = demoItemMapper.groupByCategoryId(demoItemTable,where);
DataConverter persistenceDataConverter = BeanDefinitionUtils.getBean(DataConverter.class);
return persistenceDataConverter.out(DemoItem.MODEL_MODEL, dataList);
}
return Lists.newArrayList();
}
}
调用Mapper一些说明
- 启动类需要配置扫描包MapperScan
@MapperScan(value = "pro.shushi", annotationClass = Mapper.class) @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, FreeMarkerAutoConfiguration.class}) public class DemoApplication {
- 调用Mapper接口的时候,需要指定数据源;即上述示例代码中的
DsHintApi dsHint = DsHintApi.model(DemoItem.MODEL_MODEL)
, 实际代码中使用 try-with-resources语法。 - 从Mapper返回的结果中获取数据
- 如果SQL Mapper中已定义了
resultMap
,调用Mapper(DAO)返回的就是Java对象 - 如果Mapper返回的是Map<String, Object>,则通过 DataConverter.out进行转化,参考上面的示例
- 如果SQL Mapper中已定义了
其他参考:Oinone连接外部数据源方案:https://doc.oinone.top/backend/4562.html
Oinone社区 作者:数式-海波原创文章,如若转载,请注明出处:https://doc.oinone.top/backend/4759.html
访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验