1、配置application.properties
server.servlet.context-path=/hysightdashboard
server.port=4003
#mysql数据库连接信息
spring.datasource.url=jdbc:mysql://ip:port/database?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.type-aliases-package=com.entity
mybatis.mapper-locations=classpath*:mappers/*.xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mapper.xml
<!--动态查询的语句 -->
<select id="getAllDashboards" parameterType="com.hiynn.hysight.dashboard.entity.Dashboard" resultMap="dashboard">
SELECT
<include refid="baseColumns"/>
FROM t_dashboard
WHERE delete_flag='0'
<if test="userId!= null">
AND user_id=#{userId}
</if>
<if test="_parameter !=null">
AND is_shared=#{isShared}
</if>
<if test="dashboardName!= null">
AND dashboard_name LIKE CONCAT(CONCAT('%', #{dashboardName}), '%')
</if>
ORDER BY update_time DESC , create_time DESC
</select>
mapper.java
Dashboard getDashboardById(String dashboardId);
service.java
public List<Dashboard> getAllDashboards(Dashboard dashboard) {
// String userid=HysightThreadContext.getUser().getUserId();
dashboard.setUserId("123");
dashboard.setShared(false);
return dashboardMapper.getAllDashboards(dashboard);
}
controller
@PostMapping("/getAll")
public Result getAllDashboards(@RequestParam(value="page",defaultValue="1") int currentPage,
@RequestParam(value="pagesize",defaultValue="10") int pageSize,
@RequestBody Dashboard dashboard){
PageHelper.startPage(currentPage, pageSize);
PageInfo<Dashboard> pageInfo=new PageInfo<>(dashboardService.getAllDashboards(dashboard));
return Result.build().success("获取Dashboards成功",pageInfo);
}
测试结果如图:
需要注意几个小问题
- 传入参数是对象时,需要使用@ResquestBody注解,可以将对象转化为json字符串,不然谁知道你传进来的啥,怎么解析
- mybatis中的映射<resultType>只能在返回结果中使用如:reultType="dashboard"
- 有个参数的问题一直报错,报错原因是找不到该参数的get方法,将该参数的非空判断改为_parameter !=null就好了,具体原因未知
- 动态查询有一个很别扭的问题就是我要查询的是Dashboard的集合,然而却让我使用dashboard作为参数,刚开始还在想是不是有问题,但是再写一个包装类挺麻烦,后来发现其实没什么问题,输入的条件只是属于dashboard而已,当然可能封装起来更好,便于扩展。