봄 부팅 JPA 업데이트를 업데이트만의 특정 필드

0

질문

그래서 저는 이 문제가 발생한 업데이트와는 엔티티에서 DB. 을 통과하면서 전체 엔터티 및 업데이트만의 특정 필드를 처리 손길이 닿지 않은 분야로 null,결과적으로 나는 예외가 이런 분야 @Not-Null,

가 찾는 유사한 문제가지 문제 해결 문제입니다.

회사 개체:

@Entity
@Table (name = "companies")
@Data
@ToString(exclude = "perfumes")
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @NotNull
    private String name;

    @NotNull
    @Email(message = "Wrong input. please enter a VALID email address")
    private String email;

    @NotNull
    @Size(min = 4, max = 14, message = "Password range must be between 4 - 14 digits")
    private String password;

    @NotNull
    @Enumerated(EnumType.STRING)
    private Country country;

    @Singular
    @OneToMany(mappedBy = "company", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<Perfume> perfumes = new ArrayList<>();
}

대부분의 필드는 @NotNull 생성,그러나,를 업데이트해야 합 entity,때로는 특정한 필드가 있습니다.

서비스:

@Override
public String updateCompany(int id, Company company) throws DoesNotExistException {
    if(!companyRepository.existsById(id))
    {
        throw new DoesNotExistException(id);
    }

    companyRepository.saveAndFlush(company);
    return company.getName() + " has been UPDATED";
}

당신이 볼 수 있습니다 ENTITY 전달되었는 원인은 나머지 부분의 속성을 자동으로 null 인 경우 수정되지 않습니다.

컨트롤러:

  @PutMapping("/updateCompany/{id}")
    @ResponseStatus(HttpStatus.ACCEPTED)
    public String updateCompany(@PathVariable int id, @RequestBody Company company) throws DoesNotExistException {
        return admin.updateCompany(id,company);
    }

예외:

Validation failed for classes [com.golden.scent.beans.Company] during update time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=password, rootBeanClass=class com.golden.scent.beans.Company, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]

감사합니다.

hibernate java jpa
2021-11-21 18:38:43
1

최고의 응답

0

컨트롤러는 바인딩 값을 전달하는 새로운 회사 entity. 새로운 기업에 부착되지 않고 지속성 컨텍스트,그것은 있지 않은 상태의 기존 entity. 저장할 때 그것은 JPA 하고 싶은 생각하 null 모두 필드 해당 값이 없습니다.

대신,당신이 할 수 있 컨트롤러는 바인딩에 대한 인수를 DTO. 그런 다음 서비스에서 당신은 기존 사용하여 고객 findById,복사할 필드에서 업데이트 DTO 을 entity. 그런 다음 전화 saveAndFlush 전달에서 업데이트 entity.

그것은 다음과 같이 개선 DTO 사용할 수 있습니다 aJsonPatch 을 보유 업데이트를 통과한 참조하십시오 https://www.baeldung.com/spring-rest-json-patch. 패치 방법은 다음과 같이 더 나은 일을 위해 당신이 무슨 일을 어쨌든.

서버에서 중요한 일은 기존의 엔티티는 당신이 있는 엔티티에 연결된 지속성 컨텍스트의 모든 분야 현재 있습니다.

2021-11-21 20:00:13

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................