Как сохранить отношения (отсоединенных) объектов в весенней загрузке Java (jpa-hibernate)

Я хочу сохранить отношения двух или более человек друг к другу с определенными элементами. Человек со своим умением и по определенному адресу должен быть связан друг с другом. Обычно я создаю таблицу для сохранения идентификаторов каждого элемента и создания строки в таблице (в обычном MySQL с PHP). Как решить эту проблему в Java Spring Boot (JPA-Hibernate-MySQL)?

Когда я создаю (или лучше прошу) «объект» (отдельно) из репозитория каждого элемента и хочу сохранить его в новом «репозитории» (базе данных), я получаю сообщение об ошибке.

Реализация PartnerConnectionServiceImplementation (.java)

@Service
public class PartnerConnectionServiceImpl implements PartnerConnectionService {

    @Autowired
    private PartnerConnectionRepository partnerConnectionRepository;

    @Autowired
    private DanceSkillServiceImpl danceSkillDatabaseService;

    @Autowired
    private AddressLocationServiceImpl addressLocationDatabaseService;

    @Autowired
    private UserProfileServiceImpl userProfileDatabaseService;

@Override
    public Optional<PartnerConnection> connectPartnersWithDanceSkillAndAddressLocation(long userIdPartner1, long danceSkillIdPartner1, long addressLocationIdPartner1, long userIdPartner2, long danceSkillIdPartner2, long addressLocationIdPartner2) {

        Optional<UserProfile> userProfile1 = this.userProfileDatabaseService.getUserById(userIdPartner1);
        Optional<UserProfile> userProfile2 = this.userProfileDatabaseService.getUserById(userIdPartner2);

        Optional<DanceSkill> danceSkill1 = this.danceSkillDatabaseService.getDanceSkillById(danceSkillIdPartner1);
        Optional<DanceSkill> danceSkill2 = this.danceSkillDatabaseService.getDanceSkillById(danceSkillIdPartner2);

        Optional<AddressLocation> addressLocation1 = this.addressLocationDatabaseService.getAddressLocationById(addressLocationIdPartner1);
        Optional<AddressLocation> addressLocation2 = this.addressLocationDatabaseService.getAddressLocationById(addressLocationIdPartner2);

        if (
        (userProfile1.isPresent()) && (userProfile2.isPresent())
        ){
            Optional<PartnerConnection> theConnection = getPartnerConnectionOfPartners(
                    userProfile1.get(),
                    userProfile2.get());

            if (theConnection.isPresent()) {
                return theConnection;
            }
        }


        if (
                (userProfile1.isPresent()) && (userProfile2.isPresent()) &&
                (danceSkill1.isPresent()) && (danceSkill2.isPresent()) &&
                (addressLocation1.isPresent()) && (addressLocation2.isPresent())
        ) {
            PartnerConnection newPartnerConnection = new PartnerConnection(
                null,
                userProfile1.get(),
                danceSkill1.get(),
                addressLocation1.get(),
                userProfile2.get(),
                danceSkill2.get(),
                addressLocation2.get()
        );

        this.partnerConnectionRepository.save(newPartnerConnection);


        return Optional.of(newPartnerConnection);
        }

        return Optional.empty();
    }
...

Партнерское соединение (.java)


// indicates the connecitons between partners/ users
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = "partner_connection")
public class PartnerConnection {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;


    @OneToOne(
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL
    )
    @JoinColumn(
            name = "firstmessage_fk",    // foreign key
            nullable = true
    )
    private UserMessage firstMessage;

    @ManyToOne(
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL
    )
    @JoinColumn(name = "onepartner_fk",     // foreign key
            nullable = false)
    private UserProfile firstPartner;

    @OneToOne(
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL
    )
    @JoinColumn(
            name = "firstpartnerdanceskill_fk",    // foreign key
            nullable = false
    )
    private DanceSkill firstPartnerDanceSkill;

    @OneToOne(fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JoinColumn(name = "firstpartneraddresslocation_fk",    // foreign key
            nullable = false)
    private AddressLocation firstPartnerAddressLocation;

    @ManyToOne(fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JoinColumn(name = "secondpartner_fk",   // foreign key
            nullable = false)
    private UserProfile secondPartner;

    @OneToOne(fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JoinColumn(name = "secondpartnerdanceskill_fk",    // foreign key
            nullable = false)
    private DanceSkill secondPartnerDanceSkill;

    @OneToOne(fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JoinColumn(name = "secondpartneraddresslocation_fk",    // foreign key
            nullable = false)
    private AddressLocation secondPartnerAddressLocation;


    public PartnerConnection(UserMessage firstMessage, UserProfile firstPartner, DanceSkill firstPartnerDanceSkill, AddressLocation firstPartnerAddressLocation, UserProfile secondPartner, DanceSkill secondPartnerDanceSkill, AddressLocation secondPartnerAddressLocation) {
        this.firstMessage = firstMessage;
        this.firstPartner = firstPartner;
        this.firstPartnerDanceSkill = firstPartnerDanceSkill;
        this.firstPartnerAddressLocation = firstPartnerAddressLocation;
        this.secondPartner = secondPartner;
        this.secondPartnerDanceSkill = secondPartnerDanceSkill;
        this.secondPartnerAddressLocation = secondPartnerAddressLocation;
    }
}

Ошибка org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: ... nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: ... появляется на this.partnerConnectionRepository.save(newPartnerConnection);

Есть ли у вас простые для понимания предложения?

Я думаю, что этот вопрос может вам помочь: Spring data jpa detached entity

Zinc 13.12.2020 09:04
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
0
1
509
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Я думаю, что ваш метод должен содержать аннотацию @Transactional. Вы пометили все отношения как LAZY, поэтому, если вы хотите их получить, вам нужна транзакция, чтобы загрузить их в управляемое состояние из отсоединенного, а затем иметь возможность прикрепить его к объекту, который вы хотите сохранить.

Другие вопросы по теме