Mybatis 自定义多表关联查询
由于业务场景需要实现复杂的关联查询,自定义sql实现比较方便,所以记录一下
配置文件
mybatis-plus:
mapper-locations: classpath*:/mapper/*.xml
type-aliases-package: com.xxx.entity
初始化分页插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return mybatisPlusInterceptor;
}
Mapper
//注解方式
@Select("select * from event where app_id= #{appId} and module_id = #{moduleId}")
List<EventDefineInfo> selectEventByParam(@Param("appId") Integer appId, @Param("moduleId") Integer moduleId);
//自定义SQL
Page<Event> selectByPage(Page<EventDefineInfo> page, @Param("defineInfo") Event info);
mapper.xml
<select id="selectByPage" resultType="Event">
select evt.id, evt.event_name,
evt.module_id,mdu.module_name,
evt.sub_module_id,sub.category_name,
evt.update_by,evt.update_time
from event evt
left join module mdu on evt.module_id = mdu.id
left join sub_module sub on evt.sub_module_id = sub.id
where evt.app_id = #{info.appId}
<if test="info.eventName != null and info.eventName != ''" >
AND evt.event_name like CONCAT('%',#{info.eventName},'%')
</if>
<if test="info.eventId != null and info.eventId != ''" >
AND evt.event_id = #{info.eventId}
</if>
</select>