Not-null property references a transient value in SpringBoot 2.0.5.RELEASE app

I have a basic SpringBoot 2.0.5.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file

I have this object:

    public class Invoice  implements Serializable {

    @OneToMany( mappedBy = "invoice", 
                    orphanRemoval=true, 
                    cascade = CascadeType.ALL, 
                    fetch = FetchType.LAZY)
        @JsonIgnore
        private Set<Wallet> wallets = new HashSet<>();
    ...
}

and

public class Wallet implements Serializable {

    @ManyToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "invoice_id")
        @JsonIgnore
        @NotNull
        private Invoice invoice;
    ..
    }

and

public class User implements Serializable {

 @OneToMany(cascade = CascadeType.ALL,orphanRemoval = true, fetch = FetchType.EAGER,mappedBy = "user")
    @JsonIgnore
    private List<Wallet> wallets = new ArrayList<Wallet>();
..
}

and this JunitTest:

Invoice invoice = new Invoice("001");
        invoiceService.save(invoice);

        Wallet wallet = new Wallet();
        wallet.setName("myWallet");
        wallet.setInvoice(invoice);

        invoice.getWallets().add(wallet);
        invoiceService.save(invoice);

        User user = new User();
        user.setEmail("user.test@gmail.com");
        userService.save(user);

But when I save I got this error:

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : com.tdk.backend.persistence.domain.backend.Wallet.invoice -> con.tdk.backend.persistence.domain.backend.Invoice; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : com.tdk.backend.persistence.domain.backend.Wallet.invoice -> com.tdk.backend.persistence.domain.backend.Invoice
    at ....

1 answer

  • answered 2018-09-21 21:23 Yuriy Tsarkov

    Did you try change this:

    invoice.getWallets().add(wallet);
    

    with this:

    public class Invoice  implements Serializable {
        ...
      public void addWallet(Wallet wallet) {
        if (Objects.isNull(wallets)) {
          this.wallets = new HashSet<>();
        }
        wallets.add(wallet);
        wallet.setInvoice(this);
      }
        ...
    }
    

    and in the test make:

    invoice.addWallet(wallet);
    

    I've just tried this way with an identical settings on my on classes and JUnit test has been well done