在CrudRepository

时间:2017-09-11 15:29:50

标签: java hibernate spring-boot

有2个实体 亲本

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private String name;
    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Phone> phones = new ArrayList<>();

    public Person(String name) {
        this.name = name;
    }

    public void addPhone(Phone phone) {
        phones.add( phone );
        phone.setPerson( this );
    }

    public void removePhone(Phone phone) {
        phones.remove( phone );
        phone.setPerson( null );
    }
}

和孩子

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Phone {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private String number;
    @ManyToOne
    private Person person;
...

直接级联添加记录不起作用

Person person = new Person("Rodber Smit");
for (int i = 0; i < 3 ; i++) {
  person.addPhone(new Phone(0l,"xxx" + i,person));
}

person = personRepository.save(person);

例外

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: io.khasang.moikaplus.entity.Phone;

被抛出。 必须再次写入和阅读父记录。

person = personRepository.save(person);
person = personRepository.findOne(person.getId());

是否可以避免两次额外的读写操作?

1 个答案:

答案 0 :(得分:1)

是的预期,当你尝试级联具有id的对象时,hibernate会认为该对象是持久化的,但由于它不是托管的,它将作为分离对象处理,你需要做的就是不设置Id和级联应该运行良好。