简体   繁体   English

如何根据 ID 以外的内容进行过滤

[英]How to filter based on something other than ID

I am trying to build a very small REST API with a mysql database.我正在尝试使用 mysql 数据库构建一个非常小的 REST API。 I am using Spring boot and Tomcat to deploy it locally.我正在使用 Spring boot 和 Tomcat 在本地部署它。 One of the services I am working on is to retrieve messages from the database.我正在处理的一项服务是从数据库中检索消息。 I have the ability to get ALL the messages created from the database, and I have the ability to filter based on ID but I want to be able to filter based on other parameters as well.我能够获取从数据库创建的所有消息,并且能够基于 ID 进行过滤,但我也希望能够基于其他参数进行过滤。 The other parameters are called "messageCreated" and "messageSubscribed" they're both int parameters.其他参数称为“messageCreated”和“messageSubscribed”,它们都是 int 参数。

Here is my Controller class:这是我的控制器类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.NoSuchElementException;


@RestController
@RequestMapping("/messages")
 public class MessageController {
    @Autowired
     MessageService messageService;

@GetMapping("")
public List<Message> list() {
    return messageService.listAllMessage();
}


@GetMapping(value ={"/id"})
public ResponseEntity<Message> get(@PathVariable Integer id) {
    try {
        Message message = messageService.getMessage(id);
        return new ResponseEntity<Message>(message, HttpStatus.OK);
    } catch (NoSuchElementException e) {
        return new ResponseEntity<Message>(HttpStatus.NOT_FOUND);
    }
}

@PostMapping("/")
public void add(@RequestBody Message message) {
    messageService.saveMessage(message);
}
@PutMapping("/{id}")
public ResponseEntity<?> update(@RequestBody Message message, @PathVariable Integer id) {
    try {
        Message existMessage = messageService.getMessage(id);
        message.setId(id);
        messageService.saveMessage(message);
        return new ResponseEntity<>(HttpStatus.OK);
    } catch (NoSuchElementException e) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Integer id) {

    messageService.deleteMessage(id);
   }
}

If you are using Spring data then use @Query to filter .如果您使用的是 Spring 数据,则使用 @Query 过滤。 more example find in the below url.更多示例可在以下网址中找到。 https://www.baeldung.com/spring-data-jpa-query https://www.baeldung.com/spring-data-jpa-query

  1. Use a java stream pipeline.使用 java 流管道。
    assuming that there's a method filtering the result of your listAllMessage() , we say, buildMsgsFromWanted假设有一种方法可以过滤您的listAllMessage()的结果,我们说buildMsgsFromWanted
List<Message> buildMsgsFromWanted(List<Message> allResults){
  // there should be some codes to check the validation of allResults, like ifEmpty() or something like this. then 
  List<Message> createdMsgs = allResult.stream().filter((item)->item.messageCreated()).collect(Collectors.toList());
  return createdMsgs;
}
  1. Just query the wanted items.只需查询想要的项目。
    if ur using MyBatis, in the mapper, selectAllMessages() should be like this:如果你使用 MyBatis,在映射器中, selectAllMessages()应该是这样的:
List<Message> selectAllMessages(Message filter);

and in the mapper xml file, the sql should be like:在映射器 xml 文件中,sql 应该是这样的:

<select id="selectAllMessages" parameterType="XXX.XXX.XXX.Message" resultMap="messageMap">
  select m.fieldA, m.fieldB, m.filedC, ...., m.is_created, m.is_subscribed from message m
  <where>
    <if test="messageCreated!=null"> and m.is_created=#{messageCreated}</if>
    <if test="messageSubscribed!=null"> and m.is_subscribed=#{messageSubscribed}</if>
  </where>
</select>

so whether the messageCreated and messageSubscribed are null or not in the parameter message you pass to selectAllMessage decides the result, or actually, the sql executed.因此,您传递给selectAllMessage的参数message中的messageCreatedmessageSubscribed是否为 null 决定了结果,或者实际上是执行的 sql。 just call the select method like:只需调用 select 方法,如:

Message queryObj = new Message();
queryObj.setCreated(null);
queryObj.setSubscribed(1);
mapper.selectAllMessage(queryObj);

then you'll get the subscribed messages because the argument in xml file if test="messageSubscribed!=null" is true and where m.is_subscribed=1 will be appended to the query sql.The downside is that you must maintain all the parameters as fields in class Message on which the filter may based.那么您将获得订阅的消息,因为 xml 文件中的参数if test="messageSubscribed!=null"为 true 并且where m.is_subscribed=1将附加到查询 sql 中。缺点是您必须维护所有参数作为过滤器可能基于的Message类中的字段。
It's the same in other dao frameworks, just control the 2 parameters finally passed to sql executed.在其他的dao框架中也是一样的,只是控制最后传给sql执行的2个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JPA:如何根据ID以外的字段值获取实体? - JPA: How to get entity based on field value other than ID? 如何将<junit>任务的工作目录设置为除basedir之外的其他任务? - How to set the working directory for a <junit> task to something other than the basedir? 关闭JFrame视窗时,如何使用DefaultClosingOperation以外的功能? - How to use something other than the DefaultClosingOperation when closing a JFrame window? 使用ArrayList以外的东西 - Using something other than an ArrayList 我们能否基于id以外的其他唯一字段更新Keycloak中的用户? - Can we update user in Keycloak based on any other unique fields other than id? 也许除了onClick之外还需要其他东西 - Maybe need something other than onClick 如何实现id字段以外的自增字段? - How to implement auto-increment field other than id field? 如何在SuggestBOX中保存除关键字以外的id? - How to save id's other than keyword in SuggestBOX? 如何使用iText以外的东西从模板PDF生成PDF输出? - How to generate a PDF output from a template PDF using something other than iText? Spring JavaConfig如何将dispatcher-servlet映射到root以外的其他对象 - Spring JavaConfig how to map dispatcher-servlet to something other than root
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM