【问题标题】:Getting a list object in a object with Spring and MongoTemplate使用 Spring 和 MongoTemplate 在对象中获取列表对象
【发布时间】:2021-06-25 09:14:16
【问题描述】:

这是我的 Employee 类

public class Employee {

    @Id
    private String id;
    private String firstName;
    private String lastName;
    private float salary;
    private List<Address> addresses;
    private Date joiningDate;

我想从我的 mongoDB 中获取特定员工的地址列表。 而且我知道要返回一个特定的字段

query.fields().include(addresses);

但这对我不起作用。我收到 500 内部服务器错误。

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.mapping.model.MappingInstantiationException: Failed to instantiate com.example.demo.model.Employee using constructor public com.example.demo.model.Employee(java.lang.String,java.lang.String,java.lang.String,float,java.util.List,java.util.Date) with arguments 60d5798c319336085ac8130a,hello,null,null,null,null] with root cause

这是我的代码

员工资料库

@Repository
public class EmployeeRepository {

    @Autowired
    MongoTemplate mongoTemplate;

    public List<Employee> findAddressesByFirstName(String firstName) {
        Query query = new Query(Criteria.where("firstName").is(firstName));
        query.fields().include("addresses");
        return mongoTemplate.find(query, Employee.class);
    }
}

员工服务

    public List<Employee> findAddressesByFirstName(String firstName) {
        return employeeRepository.findAddressesByFirstName(firstName);
    }

员工控制器

    @GetMapping("/firstName/{firstName}")
    public List<Employee> getAddressesByFirstName(@PathVariable("firstName") String firstName){
        return employeeService.findAddressesByFirstName(firstName);
    }

【问题讨论】:

  • 你有来自日志的堆栈跟踪吗?

标签: java spring mongodb


【解决方案1】:

mongo 中的薪水是否为空?

float 类型的工资不能为 null,它是基本类型

你可以将其修改为 Float 或给它一个值;

【讨论】:

    【解决方案2】:

    您的模型上是否有 @Document 注释和带有所有参数的 @PersistenceConstrunctor?

    就像这个例子:https://github.com/eugenp/tutorials/blob/master/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/model/User.java

    【讨论】:

    • 是的,我愿意。实际上,如果我删除行 query.fields().include(addresses);我可以得到一份员工名单。但我不确定如何访问对象中的字段
    • 地址是不同的文件吗?
    • 没有。它只是作用域中定义的另一个类
    猜你喜欢
    • 2021-08-31
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 2015-09-25
    • 2021-09-24
    • 2021-11-06
    • 2017-05-13
    相关资源
    最近更新 更多