In short, my question is how to save an entity with preset primary key(instead of null) using Spring data JPA.
To explain, consider a simple entity class named Customer. Remember, id is not set to auto increment, and it must be a custom unique value. This is a small example only. I need the id in my actual table to be a custom unique one, something like username.
@Entity
@Table(name = "customer")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "cust_id", nullable = false)
private Integer custId;
@Column(name = "first_name", length = 30)
private String firstName;
@Column(name = "last_name", length = 30)
private String lastName;
//getter, setters
}
And, I have a CustomerRepository as
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
}
Now, I suppose I have to insert a new customer record with id 101. The expected way is:
Customer customer = new Customer();
customer.setCustId(101);
customer.setFirstName("Some");
customer.setLastName("Name");
repository.save(customer);
But, it happens that repository.save() doesn’t insert the new customer with id 101. So, how should I do this?
If you are in an active transaction always remember to call flush explicitly or to ensure the transaction has committed before independently checking the database to ensure changes have been made.