Ошибка «отсоединенный объект передан в сохранение» при выборе данных через репозиторий, не понимаюJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Ошибка «отсоединенный объект передан в сохранение» при выборе данных через репозиторий, не понимаю

Сообщение Anonymous »

У меня возникли проблемы с обновлением объекта (Formation) в отношении ManyToMany с другим объектом (Intervenant).
Мой интеграционный тест завершился неудачно из-за следующей ошибки:

Код: Выделить всё

org.springframework.dao.InvalidDataAccessApiUsageException: detached
entity passed to persist: fr.foo.bar.model.Intervenant
Проблема в том, что, согласно трассировке стека, исключение перехватывается в методе, который просто извлекает данные, поэтому вызов save() не выполняется. Я не понимаю, почему появляется эта ошибка.
Вот мой тест:

Код: Выделить всё

@BeforeEach
void setUp() {
Intervenant newIntervenant = new Intervenant();
newIntervenant.setIdnum("IDNUM_NEW");
newIntervenant.setIdentite("New Intervenant");

Formation formation = new Formation();
formation.setLibelle("Sample Formation");
formation.setCodeApogee("APOGEE123");
formation.setCodeVet("VET789");
formation.setIntervenants(Set.of(newIntervenant));

formationDto = formationMapper.toDto(formation);
}

@Test
@Transactional
void whenUpdateFormation_thenIntervenantsAreUpdated() throws Exception {

FormationDto createdFormationDto = formationService.create(formationDto);

formationRepository.flush();

IntervenantDto newIntervenantDto = new IntervenantDto(null, "New IDNUM", "New Name");
createdFormationDto.intervenants().add(newIntervenantDto);

Intervenant existingIntervenant = new Intervenant();
existingIntervenant.setIdnum("IDNUM_EXISTING");
existingIntervenant.setIdentite("Existing Intervenant");
existingIntervenant = intervenantRepository.saveAndFlush(existingIntervenant);

existingIntervenant = intervenantRepository.findById(existingIntervenant.getId()).orElseThrow();
createdFormationDto.intervenants().add(intervenantMapper.toDto(existingIntervenant));

FormationDto updatedFormationDto = formationService.update(createdFormationDto.id(), createdFormationDto); // detached entity passed to persist: fr.foo.bar.model.Intervenant

[...]
}
Исключение возникает в последней строке теста, вызывающей update()
Вот update()< /code> метод:

Код: Выделить всё

@Override
@Transactional
public FormationDto update(Long id, FormationDto formationDto) throws Exception {
Formation formation = formationRepository
.findById(id)
.orElseThrow(() -> new EntityNotFoundException(String.format("La formation %d n'existe pas", id)));

Set updatedIntervenants = new HashSet();
for (IntervenantDto intervenantDto : formationDto.intervenants()) {
if (intervenantDto.id() == null) {
IntervenantDto createdDto = intervenantService.create(intervenantDto);
updatedIntervenants.add(intervenantService.toEntity(createdDto));
} else {
Intervenant existing = intervenantService.getEntity(intervenantDto.id());
updatedIntervenants.add(existing);
}
}
formation.setIntervenants(updatedIntervenants);

Collection existingEtudiants = formationEtudiantService.findAllByFormation(formation); // detached entity passed to persist: fr.foo.bar.model.Intervenant

[...]
}
Исключение возникает при вызове метода formationEtudiantService.findAllByFormation(), как показано ниже:

Код: Выделить всё

@Override
public List findAllByFormation(Formation formation) {

return formationEtudiantRepository.findAllByFormation(formation);
}
А вот репозиторий:

Код: Выделить всё

public interface FormationEtudiantRepository extends JpaRepository {

List findAllByFormation(Formation formation);
}
Вот выдержка из объекта Formation:

Код: Выделить всё

@Entity(name = "FormationEntity")
@Table(name = "formation")
public class Formation implements Identifiable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", columnDefinition = "INT UNSIGNED not null")
private Long id;

@Column(name = "libelle", length = 100)
private String libelle;

@Column(name = "code_apogee", length = 100)
private String codeApogee;

@Column(name = "code_vet", length = 100)
private String codeVet;

@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
@JoinTable(name = "formation_intervenant",
joinColumns = @JoinColumn(name = "id_formation"),
inverseJoinColumns = @JoinColumn(name = "id_intervenant"))
private Set intervenants = new LinkedHashSet();

public Set  getIntervenants() {
return intervenants;
}

public void setIntervenants(Set intervenants) {
this.intervenants = intervenants;
}
}
И, наконец, Промежуточная сущность:

Код: Выделить всё

@Entity(name = "IntervenantEntity")
@Table(name = "intervenant")
public class Intervenant implements Identifiable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", columnDefinition = "INT UNSIGNED not null")
private Long id;

@Column(name = "idnum", nullable = false, length = 50)
private String idnum;

@Column(name = "identite", length = 100)
private String identite;

@Override
public Long getId() {
return id;
}

@ManyToMany(mappedBy = "intervenants")
private Set formations = new LinkedHashSet();

public void setId(Long id) {
this.id = id;
}

public String getIdnum() {
return idnum;
}

public void setIdnum(String idnum) {
this.idnum = idnum;
}

public String getIdentite() {
return identite;
}

public void setIdentite(String identite) {
this.identite = identite;
}

public Set getFormations() {
return formations;
}

public void setFormations(Set formations) {
this.formations = formations;
}
}
Это действительно сводит меня с ума... Можете ли вы мне помочь?

Подробнее здесь: https://stackoverflow.com/questions/792 ... repository
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»