I am building a RESTful API in Spring boot. My architecture is the three-tier achitecture; Controller -> Service -> Repository.
I have 2 entities, Transaction and Invoice. This is a OneToOne relationship. A Transaction may or may not have an Invoice, but an Invoice must have a Transaction.
I am also using the DTO pattern which has the services return DTO objects of the Entity back to the calling Controller which then gets returned back to my frontend.
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "invoice")
public class Invoice {
/**
Omitted fields
**/
@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JsonManagedReference(value = "transaction-invoice")
private Transaction transaction;
}
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "transaction")
public class Transaction {
/**
Omitted fields
**/
@OneToOne
@JsonBackReference(value = "transaction-invoice")
private Invoice invoice;
}
I have a POST endpoint in my InvoiceController which calls an InvoiceService. The InvoiceService builds and saves the created Invoice Entity, using an InvoiceRepository (JpaRepository).
However, when this is being created I also need to save the link to an existing Transaction entity. I am using JpaRepositories and not entitymanager.
Options:
- Should I have TransactionRepository in my InvoiceService directly and get a proxy entity for Transaction and save the link, which then uses cascading to to update the Transaction table?
- Should I have TransactionService in my InvoiceService, which calls the getTransaction method – which in turn calls the TransactionRepository to get a proxy entity. Problem here, is since I am using the DTO pattern, my services return DTO objects of the Entity, which I would need to map into the Entity before using in my InvoiceService, creating a lot of overhead.
Are there any other options to do this?
I feel like both of these options infringe the Separation of Concerns.
This is not the only time this scenario comes up, so I am wondering the best way to deal with this.
TLDR;
The issue I’m facing though is whether the correct way to lay the code out to still adhere to separation of concerns, in my three-tier architecture, when creating an Invoice Entity but also saving the link to an existing Transaction Entity.
12