How to save an entity with custom primary key?
For example, I have an entity like below:
@Entity
@Table(name = "customer")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Customer {
@EmbeddedId
private CustomerCompositeKey identity;
private String otherdata;
}
@Embeddable
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomerCompositeKey implements Serializable {
@Column(name = "key_one")
private String keyOne;
@Column(name = "key_two")
private String keyTwo;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CustomerCompositeKey)) {
return false;
}
CustomerCompositeKey that = (CustomerCompositeKey) o;
return Objects.equals(keyOne, that.keyOne) && Objects
.equals(keyTwo, that.keyTwo));
}
@Override
public int hashCode() {
return Objects.hash(keyOne, keyTwo);
}
}
Repository class:
@Repository
public interface CustomerRepository extends
JpaRepository<Customer, CustomerCompositeKey> {
}
Currently, if I simply save I am getting a unique constraint exception. So I modified the code with a select update like below. Save code:
@Transactional
public void saveCustomer(CustomerBO customer){
Optional<Customer> customer = customerRepository.findById(customerCompositeKey);
if(customer.isPresent()) {
}else{
}
customerRepository.save(customer);
}
This is increasing my latency while saving. Is there any other way to just save without a select query? this block will be executed concurrently.
customerRepository.save(customer) is already having select/update. But why am I getting a unique constraint error?