【问题标题】:mongodb + springboot. How to do extensive filtering?mongodb + 弹簧靴。如何进行广泛的过滤?
【发布时间】:2019-10-10 05:42:58
【问题描述】:

我的 account.java 是这个

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@Document(collection="Account")
public class Account {
    @Id
    private String id;
    private String username;
    private String password;
    private String role;
}

我的仓库是这个

import org.springframework.data.mongodb.repository.MongoRepository;
public interface AccountRepository extends MongoRepository<Account, Integer> {

}

最后。对于我的控制器(尚未完成)

@PutMapping("/createAccount")
public void createAccount(@RequestBody Account account) {

}

我想要以下,

如果我要在请求正文中发送一个 json,例如

{
    "username": "Tom",
    "password": "123456",
    "role": "Employee"
}

然后它将使用该属性在 Account 集合中创建一个对象,这可以通过 repository.insert(account) 轻松完成。但是我需要检查某些过滤器

  1. 需要设置所有 3 个对象
  2. 角色必须是“员工”、“管理员”或“客户”
  3. 最后用户不在数据库中

否则发送响应 400

如何使用 springboot 实现这一点?

【问题讨论】:

  • for 1 and 2 check this stackoverflow.com/questions/6294587/… for 3 你必须通过读入数据库来手动完成
  • > 对于 3,您必须通过读入数据库手动完成 - 如何?
  • 添加存储库方法'findByUserName'并传递用户名。只检查结果是否为空。继续保存
  • 好的,但是有这些命令的列表吗?此外,如果您知道,我将如何完成自定义查询?例如, db.getCollection("Account").find({"username":"bob123"}) (我知道这可以通过这些自定义方法轻松完成,仅以它为例)
  • @bob 用于自定义查询 baeldung.com/spring-data-jpa-query @Repository 注解也提供了默认查询。 spring bootdocs.spring.io/spring-data/jpa/docs/current/reference/html/…提供的查询示例

标签: java spring-boot


【解决方案1】:
  1. 您可以在控制器中使用@Valid Annotation,然后您可以将@NotNull 或@NotEmpty 或@NotBlank 放入您的模型类中。参考:https://www.baeldung.com/spring-boot-bean-validation

public void createAccount(@Valid @RequestBody Account account) {

}

public class Account {

    @Id
    @NotNull
    private String id;
    @NotNull
    private String username;
    @NotNull
    private String password;
    @NotNull
    private String role;
}
  1. 您可以使用 Spring 安全表达式。参考:https://www.baeldung.com/spring-security-expressions-basic

    @PreAuthorize("hasRole('ROLE_ADMIN')")

    @PutMapping("/createAccount")

    public void createAccount(@RequestBody Account account) {

    }

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 2018-02-14
    • 2017-12-22
    • 2018-09-16
    • 2019-05-03
    • 2021-04-20
    • 1970-01-01
    • 2023-01-07
    • 2018-02-16
    相关资源
    最近更新 更多