简体   繁体   中英

Spring data mongoDb controller how can I update document as a field in side document

I have document as a field in side another document how can I update in it

Models:


@Document(collection = "maladies")
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Malady {
    @Id
    private String id;
    private String nom;
    @DBRef
    private Organ organ;
}


@Document(collection = "organs")
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Organ {//organe Document
    @Id
    private String id;
    private String nom;
}

Repositorys



public interface MaladyRepository extends MongoRepository<Malady, String> {
}


public interface OrganRepository extends MongoRepository<Organ, String> {
}



Controller I use this method to update all field but doesn't work with the organ document field My question is how can I update organ document as a field?


 @RequestMapping(method=RequestMethod.PUT, value="/maladies/{id}")
    public Malady update(@PathVariable String id, @RequestBody Malady malady) {
        Optional<Malady> optionalMalady = maladyRepository.findById(id);
        Malady m = optionalMalady.get();
        if(malady.getNom() != null)
            m.setNom(malady.getNom());
        if(malady.getOrgan() != null)
            m.setOrgan(malady.getOrgan());
        maladyRepository.save(m);
        return m;
    }

You need to update the document in the organs collection. Because you reference it.

Annotation @DbRef only resolves the dependency document during reading.

Mapping framework doesn't handle cascading operations. So – for instance – if we trigger a save on a parent, the child won't be saved automatically – we'll need to explicitly trigger the save on the child if we want to save it as well.

In order to solve your problem, you can consider using the lifecycle events listeners. It is quite common to use them in combination with @DbRef

public class OrganCascadeSaveMongoEventListener extends AbstractMongoEventListener<Object> {
    @Autowired
    private MongoOperations mongoOperations;

    @Override
    public void onBeforeConvert(BeforeConvertEvent<Object> event) { 
        Object source = event.getSource(); 
        if ((source instanceof Malady) && (((Malady) source).getOrgan() != null)) { 
            mongoOperations.save(((Malady) source).getOrgan());
        }
    }
}

You also need to add this listener to your configuration:

@Configuration
public class Config {

    @Bean
    public OrganCascadeSaveMongoEventListener  organCascadeSaveMongoEventListener() {
        return new OrganCascadeSaveMongoEventListener();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM