Jpa Repository save() doesn't update existing data

后端 未结 3 1139
挽巷
挽巷 2021-01-21 11:48

I am trying to update data and as I know save() method saves entity if the id is null or update an existing entity in the database if the given id is found in DB.

Howeve

相关标签:
3条回答
  • 2021-01-21 12:31

    To update an existing entity object through JPA it should be made available to the entity manager first.

    Read through the article

    https://www.objectdb.com/java/jpa/query/jpql/update

    excerpt from the same

    1.Retrieving the entity objects into an EntityManager.
    2.Updating the relevant entity object fields within an active transaction.
    3.Applying changes to the database by calling the commit method.
    

    I assume for the case where update does not happen , the entity is not a managed entity yet.

    More on managed entity : https://www.baeldung.com/hibernate-entity-lifecycle#managed-entity

    0 讨论(0)
  • 2021-01-21 12:38

    Your Entity Employer looks to be in detached/Transient state and you are passing id value manually which is not permitted, as it is marked as @GeneratedValue(strategy = GenerationType.IDENTITY).

    What you need to do is when you know the primary key value i.e id value, first you fetch the Entity from the database using findById() method, by which Entity comes into Managed state and then try to update the Entity by calling save() method. This will update your Entity.

    For more info on Entity state you can refer this: https://vladmihalcea.com/a-beginners-guide-to-jpa-hibernate-entity-state-transitions/

    0 讨论(0)
  • 2021-01-21 12:53

    This question is already been answered but this is my understanding of topic, as I recently started working on it.

    This can be answered on basis of Transient and Persistent/managed entities.

    Transient entity : A new entity object created which is not associated with any session till now. This object is not related to any stored data in database since it is freshly created.

    When you fetch a record from db it is fetched in managed or persistent state and any changes made to it will be reflected back to the record that it is mapped to.

    Suggestion 1 : You should not be manually adding primary key values since it is already AutoIncremented.

    Suggestion 2 : If you already have recirds id, fetch it from db first and then update it.

    Here is a Stackoverflow discussion on the topic to get you some more insight : What are detached, persistent and transient objects in hibernate?

    0 讨论(0)
提交回复
热议问题