0

I'm getting this error when I'm trying to run simply test:

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.Company; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.Company

I'm using H2 and Postgre database with SpringData and Hibernate.

Here are my entities:

@Entity
@Proxy(lazy = false)
public class Invoice {

  @ElementCollection(fetch = FetchType.EAGER)
  private List<InvoiceEntry> products = new ArrayList<>();

  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  @Column(name = "ID", unique = true, nullable = false)
  private Long id;

  private String name;

  @JoinColumn
  @ManyToOne(cascade = CascadeType.ALL)
  private Company buyer;

  @JoinColumn
  @ManyToOne(cascade = CascadeType.ALL)
  private Company seller;

And Company class:

@Entity
@Proxy(lazy = false)
public class Company{

  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  private Long id;
  private String name;
  private LocalDate issueDate;
  private String address;
  private String city;
  private String zipCode;
  private String nip;
  private String bankAccoutNumber;

Simple test looks like this:

@Test
  public void shouldAddAndGetSingleInvoice() {
    //given
    long invoiceId = database.addEntry(testInvoice);

    //when
    String output = mapper.toJson(database.getEntryById(invoiceId));
    String expected = mapper.toJson(testInvoice);

    //then
    assertThat(output, is(equalTo(expected)));
  }

Was trying to change cascade type to Merge but it doesn't work. I would be grateful for any suggestions.

Sebas
  • 1
  • 1
  • I think this answer might help you as it describe in details why this exception happens and what changes need to be made: https://stackoverflow.com/questions/27672337/detached-entity-passed-to-persist-error/27672764#27672764 – Ilya Ovesnov May 01 '18 at 16:20
  • Refer https://stackoverflow.com/questions/49592081/jpa-detached-entity-passed-to-persist-nested-exception-is-org-hibernate-persis – puneet goyal Jun 24 '18 at 18:15

0 Answers0