Spring-Data JPA: save new entity referencing existing one

前端 未结 3 1024
谎友^
谎友^ 2020-12-08 04:24

The question is basically the same as below one:

JPA cascade persist and references to detached entities throws PersistentObjectException. Why?

I\'m creating

3条回答
  •  半阙折子戏
    2020-12-08 04:56

    I had a similar issue where I was trying to save an new entity object with an already saved entity object inside.

    What I did was implemented Persistable< T > and implemented isNew() accordingly.

    public class MyEntity implements Persistable {
    
        public boolean isNew() {
            return null == getId() &&
                subEntity.getId() == null;
        }
    

    Or you could use AbstractPersistable and override the isNew there ofcourse.

    I don't know if this will be considered a good way of handling this issue but it worked out quite good for me and besides feels very natural to do.

提交回复
热议问题