Java Spring JPA存储库合并而不是保存

Java Spring JPA存储库合并而不是保存,java,spring,spring-boot,spring-data-jpa,Java,Spring,Spring Boot,Spring Data Jpa,你能帮我处理JPA存储库吗?在更新请求和使用POST方法期间-我只需要保存发送到我的帖子正文中的字段。但若我并没有将其写入body,那个么JPA存储库设置为null(DBMySQL,默认为null)。请看这幅画。 如果我不发送博德机场代码,更新后将变为空。但它是“UAAA”。我如何管理它?谢谢你的建议 模型等级切割: @Entity @SelectBeforeUpdate @DynamicUpdate @Table(name = "airports") @JsonIgnorePrope

你能帮我处理JPA存储库吗?在更新请求和使用POST方法期间-我只需要保存发送到我的帖子正文中的字段。但若我并没有将其写入body,那个么JPA存储库设置为null(DBMySQL,默认为null)。请看这幅画。

如果我不发送博德机场代码,更新后将变为空。但它是“UAAA”。我如何管理它?谢谢你的建议

模型等级切割:

@Entity 
@SelectBeforeUpdate 
@DynamicUpdate 
@Table(name = "airports") 
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) 
public class Airports {

     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private long id;
     private String airport; 
     private String code;
@RestController
public class AirportsController {
    private AirportsRepository repository;


    public AirportsController(AirportsRepository repository) {
        this.repository = repository;
    }

    @PostMapping(value = "airports/update")
    public ResponseEntity updateAirportById(@RequestBody Airports airports) {
        Airports foundedById = repository.findOne(airports.getId());
        foundedById.setAirport(airports.getAirport());
        foundedById.setCode(airports.getCode());
        repository.save(foundedById);

        return new ResponseEntity(foundedById, HttpStatus.OK);
    }
控制器类剪切:

@Entity 
@SelectBeforeUpdate 
@DynamicUpdate 
@Table(name = "airports") 
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) 
public class Airports {

     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private long id;
     private String airport; 
     private String code;
@RestController
public class AirportsController {
    private AirportsRepository repository;


    public AirportsController(AirportsRepository repository) {
        this.repository = repository;
    }

    @PostMapping(value = "airports/update")
    public ResponseEntity updateAirportById(@RequestBody Airports airports) {
        Airports foundedById = repository.findOne(airports.getId());
        foundedById.setAirport(airports.getAirport());
        foundedById.setCode(airports.getCode());
        repository.save(foundedById);

        return new ResponseEntity(foundedById, HttpStatus.OK);
    }

这是因为您在控制器updateAirportById方法中设置了值,即使它们为null。 如果未在正文中传递“code”和“airport”的值,则getAirports方法将返回null并将其设置为foundedById,然后进行更新。简单的if条件可以解决这个问题

if(airports.getAirport() != null) 
  foundedById.setAirport(airports.getAirport());

对于“code”

调用
save()
也会将null作为列
code
上的默认值保留。仅更新给定字段需要预加载或其他查询。这就是问题所在。不会的,因为他在第一行从数据库中获取记录。所以,如果他没有用null更新值,它将有自己的值,它真的在工作!谢谢拉法索卡尔斯基!祝你今天愉快,兄弟!!