Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA - saving a new entity with custom id / primary key

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?

like image 655
Jomoos Avatar asked Feb 03 '13 22:02

Jomoos


People also ask

Does JPA require primary key?

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").

How do I set primary key in entity class?

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.


1 Answers

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.

like image 162
robert_difalco Avatar answered Sep 22 '22 08:09

robert_difalco