Sales Order save not working for existing Customer but working for new Customer
@Entity
@Table(name = "sales_order")
@EntityListeners(AuditingEntityListener.class)
public class SalesOrder extends Auditable<String> implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@OneToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL)
@JoinColumn(name = "customer_id", nullable = false)
private Customer customer;
@Entity
@Table(name = "customer")
@EntityListeners(AuditingEntityListener.class)
public class Customer extends Auditable<String> implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@OneToOne(mappedBy="customer",cascade={CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH})
private SalesOrder salesOrder;
SalesOrder salesOrder = new SalesOrder();
Branch branch = BranchContextHolder.getCurrentBranch();
String nextSequense = null;
if(salesOrderDto.getId()==null) {
salesOrder = new SalesOrder(salesOrderDto);
salesOrder.setBranch(branch);
if(customerRepository.existsByPhone(salesOrderDto.getCustomer().getPhone())) {
Customer customer = customerRepository.findCustomerByPhone(salesOrderDto.getCustomer().getPhone());
customer.setSalesOrder(salesOrder);
salesOrder.setCustomer(customer);
}
nextSequense = sequenceService.getNextSequense(branch.getId(),module.getId());
salesOrder.setUid(nextSequense);
}
//save sales order
salesOrder = salesOrderRepository.save(salesOrder);
On save getting error:
detached entity passed to persist: com.jee.cms.app.customer.model.Customer; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.jee.cms.app.customer.model.Customer
Anything I am missing?
CodePudding user response:
Try annotating your method with @Transactional
. Then then Customer
won't get detached within the method.