简体   繁体   English

如何只修改spring数据jpa中的实体的一部分?

[英]How do I modify only part of an entity in spring data jpa?

How do I modify only part of an entity in Spring Data JPA?如何只修改Spring数据JPA中的实体的一部分?

Here is my code.这是我的代码。

public void modifyDrawing(Long no, String name, Double lat, Double lon, String physicalName, String desc) {
   Drawing drawing = drawingRepository.findById(no)
       .orElseThrow(NoSuchElementException::new);

   drawing.setName(name);
   drawing.setLat(lat);
   drawing.setLon(lon);
   drawing.setPhysicalName(physicalName);
   drawing.setDesc(desc);
   drawingRepository.save(drawing);
}

At this time, if lat and lon are null, I want to keep the values without changing them.此时,如果latlon是null,我想保持数值不变。 I am wondering how to update the entity value using only non-null parameter values.我想知道如何仅使用非空参数值更新实体值。

You should add an if check to make sure the latitude/longitude are not null before calling their setters.在调用他们的设置器之前,您应该添加一个if检查以确保纬度/经度不是null

public void modifyDrawing(Long no, String name, Double lat, Double lon, String physicalName, String desc) {
    Drawing drawing = drawingRepository.findById(no)
        .orElseThrow(NoSuchElementException::new);

    drawing.setName(name);
    if (lat != null) {
        drawing.setLat(lat);
    }
    if (lon != null) {
        drawing.setLon(lon);
    }
    drawing.setPhysicalName(physicalName);
    drawing.setDesc(desc);
    drawingRepository.save(drawing);
}

暂无
暂无

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

相关问题 Spring Data JPA(Hibernate):如何仅使用抽象超类中的字段来检索具体实体? - Spring Data JPA(Hibernate): How do I retrieve a concrete entity using only a field in its abstract superclass? 如何使用 spring-data-jpa 更新实体? - How do I update an entity using spring-data-jpa? 如何使用 spring 数据 jpa 更新实体 - how to update an entity with spring data jpa 如何在 Spring Data 中漂亮地更新 JPA 实体? - How to beautifully update a JPA entity in Spring Data? 如何使用 Spring JPA DATA 仅获取特定的子实体及其具有特定值的父实体 - How to fetch only the specific child entity along with its Parent entities with specific value using Spring JPA DATA 使用spring数据jpa的spring boot。 如何从请求主体执行实体的部分更新? - Spring boot with spring data jpa. How can i perform partial update of entity from request body? 当要获取的字段作为请求的一部分出现在spring数据jpa中时,我们如何以所需的格式获取ResultSet? - How do we fetch the ResultSet in the desired format when the fields to be fetched are coming as part of the request in spring data jpa? Spring boot/Spring data jpa - 如何更新相关实体? - Spring boot/Spring data jpa - how to update related entity? 如何级联删除属于 JPA 实体的集合? - How can I cascade delete a collection which is part of a JPA entity? 使用Spring Data JPA缓存实体 - Caching an entity with spring data jpa
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM