I have created a maven project using Spring Boot with MySQL database.
I have two entity classes that have a primary key in one entity class and another one has a composite primary key.
Customer.java(Has a primary key)
@Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String address; private String gstin; private String phoneNumber; @CreatedDate private Date createdDate; @LastModifiedDate private Date updatedDate; //Getters and setters }
ItemId.java (Idclass for Item.java)
public class ItemId implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private Long id; private Long billNo; //Getters and Setters }
Item.java (Has a composite primary key)
@Entity @IdClass(ItemId.class) public class Item { @Id private Long id; @Id private Long billNo; private String particular; private String hsnCode; private Double quantity; private String quantityUnit; private Double rate; private String rateUnit; private Double price; @CreatedDate private Date createdDate; @LastModifiedDate private Date updatedDate; //Getters and setters }
here the problem is when an entity object is persisted through repository object with the id which is already there in the table, the Spring boot JPA is not throwing the error that primary key id already present or something like that. Instead the details of the object that is trying to persist are updated to the already available primary key data. The same is happening to the Composite primary key entity.
Is there something wrong on my side or should I do furthermore configurations?
Thanks in advance.
Advertisement
Answer
If you are using save
method from CrudRepository
then you need to understand that if the entity with id (primary-key) null is saved, then it will generate a new id (auto increment depending on the implementation) and save the record. However, if the entity with id that is already in the database is passed in save
method then it will update the entity.
I hope you got my point.
Please have a look at this article.