How to make a function that assure an update between two models classes related by @OneToMany in Quarkus?

37 Views Asked by At

I have two classes something like below :

@Entity
@Table(name = "customer ")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Customer {

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

    private String name;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "customer_invoices")
    private List<Invoices> invoicesList;
}

And

    @Entity
    @Table(name = "invoice")
    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    public class Invoice{
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;
    
        private String value;
    }

And

 @ApplicationScoped
public class CustomerServiceImpl implements CustomerService{

    @Inject
    CustomerRepository customerRepository ;

    @Override
    public Uni<List<Customer>> findAll() {
        return customerRepository.listAll().onItem().transformToMulti(Multi.createFrom()::iterable).onItem().call(customer-> Mutiny.fetch(customer.getInvoicesList())).collect().asList();
    }

    @Override
    public Uni<Customer > saveCustomer(Customer customer) {
        return customerRepository.persistAndFlush(customer);
    }

    @Override
    public Uni<Customer > updateCustomer(Customer customer) {
        /// what should I put  ???
    }

}

And

@ApplicationScoped
public class CustomerRepository implements PanacheRepositoryBase<Customer, Integer> {
}

I tried many codes to make the possibility of an update of a customer with some invoices but with no success.

Can someone guide me ?

1

There are 1 best solutions below

0
Serkan On

Firstly, you need to start a transaction and a session in which you need to retrieve your Customer entity.

After that, you can just update your entity by calling its setter methods.

Then, you need to commit the transaction.

And also enable sql logging on your console so that you can see what’s going on under the hood.

Note: there is also an update method on the entitymanager to directly update your entity without retrieving it first. But this is mostly handy if you know beforehand which properties you want to update.