带有自定义Getter的org.springframework.http.converter.HttpMessageNotWritableException

p5cysglq  于 2022-10-23  发布在  Spring
关注(0)|答案(1)|浏览(182)

当我启用定制获取程序时,我得到了这个异常。当我评论它时,我没有得到例外。
我需要这个getter来生成从另一个持久化值计算出的传递值'state',它是对另一个持久化版本'stateId'的完整描述

.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: 1; nested exception is com.fasterxml.jackson.databind.JsonMappingException: 1 (through reference chain: com.example.model.Employee["state"])]

这是我的实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
public class Employee implements Serializable {
    @Id
    @GeneratedValue(generator = UUIDGenerator.UUID_GEN_STRATEGY ) //strategy = GenerationType.IDENTITY
    UUID id ;
    @Column
    String name;
    @Column
    String telephone;
    @Column
    String address;

    @Enumerated
    @JsonIgnore
    @Column(name="state", nullable = false)
    State stateId;

    @Transient
    List<String> state;

    public Employee(BaseEmployeeRequest employee) {
        stateId = State.ADDED;
        this.name = employee.getName();
        this.address = employee.getAddress();
        this.telephone = employee.getTelephone();
    }

    public void setState(List<String> state) {
        this.state = state;
    }

    public List<String> getState(){
        List<String> state = new ArrayList<String>();
        if(stateId !=null) {
            String[] states = stateId.getId().split("_");
            if(states[1] ==null || states[1].length()==0){
                state.add(states[0]);
                state.add(EventFullName.SECURITY.get(states[1]));
                state.add(EventFullName.SECURITY.get(states[2]));
            }
            return state;
        }
        return Collections.EMPTY_LIST;
    }
}
1l5u6lss

1l5u6lss1#

您已经从Lombok声明了@data,它内部有一个getter和setter,所以当您手动编写它们时,它会变成一个副本。
您可以从here中读取:@Data注解等同于以下注解的组合:

@Getter
@Setter
@RequiredArgsConstructor
@ToString
@EqualsAndHashCode

如果您想从不同位置使用setter或getter,只需使用与手动创建时将使用的相同,它将显示出来
例如:

public class Work{
public static void main(String[] args){
   Employee emp = new Employee();
    emp.setName("John");
    String name = emp.getName(); // => John

  }
}

正如您从示例中看到的,您不需要手动设置它们,Lombok @Data就可以了

相关问题