草庐IT

java - spring-data-mongodb 不会在列表中保留多个对象

coder 2023-11-03 原文

我正在使用 Spring-data-mongodb,我可以将一个对象保存在列表中,但是当我尝试添加另一个对象时,它不起作用,应用程序不会抛出异常。

这是我的 Json:

[
  {
    idUser: "4a9f10d9-e19f-42af-ba00-891a567cc41f",
    login: "peter",
    password: "mypassword",
    email: "peter@eeee.com",
    patients: 
      [
        {
          idPatient: "d31e8052-36d3-4285-9f97-454f3437812d",
          name: "ada",
          birthday: 1363474800000,
          idUser: "4a9f10d9-e19f-42af-ba00-891a567cc41f",
          region: 
          {
            idRegion: "d8acfa45-486e-49e0-b4e6-edde6743cf30",
            name: "Madrid"
          },
          personalCalendars: null
        },
        null
      ]
   }
]

如您所见,我的第一个 Patient 元素是正确的,第二个元素插入为 null。

我留下我的代码:

用户.java

@Document(collection = "users")
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id
private String id;

@Indexed
private UUID idUser;

@Indexed(unique = true)
private String login;

private String password;

@Indexed(unique = true)
private String email;

@DBRef
private List<Patient> patients;

@PersistenceConstructor
public User(UUID idUser, String login, String password, String email, List<Patient> patients){
    this.idUser = idUser;
    this.login = login;
    this.password = password;
    this.email = email;
this.patients = patients;
}

患者.java

@Document(collection = "patients")
public class Patient implements Serializable {

private static final long serialVersionUID = 1L;

@Id
private String id;

@Indexed
private UUID idPatient;

private String name;

private Date birthday;

private UUID idUser;

private Region region;

@Transient
private List<PersonalCalendar> personalCalendars;

@PersistenceConstructor
public Patient(UUID idPatient, String name, Date birthday,UUID idUser, Region region){
    this.idPatient = idPatient;
    this.name = name;
    this.birthday = birthday;
    this.idUser = idUser;
    this.region = region;
}

以及我执行插入操作的 DAO。

@Override
public Patient createPatient(User user, Patient patient) {
    this.mongoOps.save(patient , "patients");
    this.mongoOps.save(user , "users");
    return this.getPatientById(patient.getIdPatient());
}

控制台返回这个,但没有坚持病人:

15:16:16.718 [tomcat-http--6] DEBUG o.s.data.mongodb.core.MongoTemplate - Saving DBObject containing fields: [_class, _id, idPatient, name, birthday, idUser, region]
15:16:16.723 [tomcat-http--6] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[application]
15:16:16.747 [tomcat-http--6] DEBUG org.mongodb.driver.protocol.insert - Inserting 1 documents into namespace application.patients on connection [connectionId{localValue:2, serverValue:119}] to server 127.0.0.1:27017
15:16:16.761 [tomcat-http--6] DEBUG org.mongodb.driver.protocol.insert - Insert completed

我需要帮助。 非常感谢

最佳答案

首先,如果您将 Spring Data 与 MongoDB 一起使用,请正确使用它:

@Repository
public interface UserRepository extends MongoRepository<User, String> {

}

现在只需通过 @Autowired 注入(inject) UserRepository注释:

@Autowired
private UserRepository userRepository;

User user = new User();
Patient patient = new Patient();
user.addPatient(patient);

// Just call save from userRepository to save your User with Patient.
// save method will return instance of saved user (together with instance of
// patient)
User user = userRepository.save(user);

请注意 save方法也可用于更新现有的 User .如果User是新的(没有生成 id)它将被插入。如果用户存在(已生成 ID),它将被更新。

假设User类有一个 addPatient看起来像这样的方法:

public void addPatient(Patient patient) {
    this.patients.add(patient);
}

此外,请确保您的列表已初始化:List<Patient> patients = new ArrayList<>();

关于java - spring-data-mongodb 不会在列表中保留多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31942621/

有关java - spring-data-mongodb 不会在列表中保留多个对象的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  3. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  4. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  5. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  6. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  7. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  8. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  9. ruby - RVM 使用列表[0] - 2

    是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论

  10. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

随机推荐