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?
Every JPA entity must have a primary key. You can specify a primary key as a single primitive, or JDK object type entity field (see "Configuring a JPA Entity Simple Primary Key Field").
With an entity, make sure that you specify the primary key in the class hierarchy. When you specify the primary key, follow the below rules: For a simple (not complex type) primary key, specify @Id in the persistence field or persistence property or specify the key in the O/R mapping file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With