请求地址:localhost:8989/SmartPush/Users
请求参数:{“department_id”:[41,42]}
1.先定义实体类
@Data
public class PushUser {
private Integer id;
private String name;
private Integer department_id;
private String phone;
private Integer height;
private Integer weight;
@JsonIgnore //此注解用于隐藏该字段,不向前端返回
private Date birthday;
private Integer age;
private Integer sex;
}
2.再定义一个实体类,用于存放传入的数组型的id
@Data
public class RequestDepartmentID {
private ArrayList<Integer> department_id;
}
3.Controller
@Slf4j
@RestController
@RequestMapping("/SmartPush")
public class SmartPushController {
@Autowired
private SmartPushService smartPushService;
@PostMapping("/Users")
public ResponseData SmartPushUsers(@RequestBody RequestDepartmentID ReqID) {
ResponseData responseData = new ResponseData();
ArrayList<Integer> deptid = ReqID.getDepartment_id();
Collections.sort(deptid);
if (deptid.size()<=0) {
responseData.setCode(-1);
responseData.setMessage("该部门信息有误");
responseData.setData(null);
return responseData;
} else {
responseData.setData(smartPushService.getUsersByDepartmentid(deptid));
responseData.setCode(200);
return responseData;
}
}
}
4.Service
@Service
public class SmartPushService {
@Autowired
private TaUserDao taUserDao;
public List<PushUser> getUsersByDepartmentid(ArrayList<Integer> department_id){
List<PushUser> list = new ArrayList<>();
if (department_id != null) {
List<PushUser> users = taUserDao.getUsersByDepartment_id(department_id);
//lamda表达式,将users集合按人员身高从高到低排序,关键方法:.reversed
list = users.stream()
.sorted(Comparator.comparing(PushUser::getHeight)
.reversed()).collect(Collectors.toList());
}
return list;
}
}
5.Dao
@Mapper
public interface TaUserDao {
List<PushUser> getUsersByDepartment_id(ArrayList<Integer> department_id);
}
6.XML
<!--关键方法:<foreach> 里面的东西不用改,直接复用-->
<select id="getUsersByDepartment_id" resultType="com.jfsystem.manage.dwpc.model.PushUser">
select id,name,height,department_id,weight,TIMESTAMPDIFF(YEAR, birthday, CURDATE()) as age,phone,sex FROM ta_user where department_id in
<foreach collection="list" open="(" close=")" separator="," item="item">
#{item}
</foreach>
ORDER BY RAND() LIMIT 6;
</select>
7.返回的数据
{
"code": 0,
"message": null,
"data": [
{
"id": 48,
"name": "李伟",
"department_id": 42,
"phone": "18747205204",
"height": 175,
"weight": 80,
"age": 30,
"sex": 1
},
{
"id": 99,
"name": "常威",
"department_id": 41,
"phone": "13039586119",
"height": 173,
"weight": 146,
"age": 25,
"sex": 1
},
{
"id": 87,
"name": "曹操",
"department_id": 42,
"phone": "18648467050",
"height": 171,
"weight": 74,
"age": 23,
"sex": 1
},
{
"id": 69,
"name": "王凯",
"department_id": 42,
"phone": "17604875674",
"height": 169,
"weight": 140,
"age": 24,
"sex": 1
},
{
"id": 133,
"name": "刘磊",
"department_id": 41,
"phone": "17604854980",
"height": 166,
"weight": 72,
"age": 20,
"sex": 1
},
{
"id": 123,
"name": "张讯",
"department_id": 42,
"phone": "18586185119",
"height": 165,
"weight": 66,
"age": 24,
"sex": 1
}
]
}