hibernate在保存实体时抛出notwritablepropertyexception

qvtsj1bj  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(324)

我以前也遇到过这种情况,但这次的原因不同。
我把它可以复制的场景简化为两个实体, Child 以及 Parent :
孩子:

@Table(name = "Childs")
@Entity
@IdClass(KeyChild.class)
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Child {

    @Id
    @ManyToOne
    private Parent parent;

    @Id
    private int id0;

}

起源:

@Table(name = "Parents")
@IdClass(KeyParent.class)
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Getter
@Setter
public class Parent {

    @Id
    private String id1;

    @Id
    private int id2;

}

组合键:

public class KeyChild implements Serializable {

    private KeyParent parent;
    private int id0;

}

public class KeyParent implements Serializable {

    private String id1;
    private int id2;

}

在尝试保存子级时(按照您希望的方式指定父级),会出现此问题。
控制器示例:

@Controller
public class ParticiparController {

    @Autowired
    ParentRepository parentRepository;

    @Autowired
    ChildRepository childRepository;

    @GetMapping("/test/")
    public String evento() {

       Parent p = Parent.builder().id("test").id2(1).build();

       parentRepository.save(p);

       childRepository.save(Child.builder()
                .parent(p)
                .id(0)
                .build());

        return "test";
    }

}

子存储库的save方法引发:

org.springframework.beans.NotWritablePropertyException: Invalid property 'id1' of bean class [com.example.myProject.Entities.Keys.KeyParent]: Bean property 'id1' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

我也尝试过不使用lombok(只生成getter和setter),但得到了相同的结果。我很确定二传手不是问题。
更新:有,但不是实体的。。。似乎只有在某些情况下才需要。

u91tlkcl

u91tlkcl1#

正如错误消息中所建议的,在 KeyParent 对应于 Parent 由注解的实体字段 @Id .

相关问题