简体   繁体   中英

Hibernate throws NotWritablePropertyException when saving entity

This happened to me other times, but this time the reason is different.

I reduced the scenario where it can be reproduced down to two entities, Child and Parent :

Child:

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

    @Id
    @ManyToOne
    private Parent parent;

    @Id
    private int id0;

}

Parent:

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

    @Id
    private String id1;

    @Id
    private int id2;


}

The composite keys:

public class KeyChild implements Serializable {

    private KeyParent parent;
    private int id0;

}

and

public class KeyParent implements Serializable {

    private String id1;
    private int id2;

}

The problem happens when trying to save a Child (specifying the parent as you would spect).

An example controller:

@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";
    }

}

The save method of the child repository throws:

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?

I also tried without Lombok (just generating the getters and setters), but I got same result. I'm pretty sure setters are not the problem.

Update: There were, but not the entity ones... It seems that are only required in some cases.

正如错误消息中所建议的那样,您应该在KeyParent有 getter/setter,它们对应于@Id注释的Parent实体字段的适当 getter/setter。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM