Kevin Meredith
Kevin Meredith

Reputation: 41939

Necessary to call persist()?

removeGroupCoordinator() takes 2 arguments: name of user & name of group. The method removes the input user from the input group.

There's an overloaded removeGroupCoordinator(coordinators: Set<Long>, coordinatorIdToRemove: Long, groupId: Long) that removes a coordinator from a group via an eventual call to coordinators.remove(coordinatorIdToRemove).

Is it necessary to call persist() before calling flush? I believe that it's not since flush() will sync up the database to cache, which I will have just modified with my coordinators.removeCoordinator(...).

public void removeGroupCoordinator(final long followerId, final long followingId)
{
    DomainGroup groupEntity = getDomainGroup();

    Set<Person> groupCoordinators = groupEntity.getCoordinators();

    removeGroupCoordinator(groupCoordinators, followerId, followingId);

    groupEntity.setCoordinators(groupCoordinators);

    // getEntityManager().persist(groupEntity); needed? 

    getEntityManager().flush();
}

Upvotes: 1

Views: 225

Answers (2)

Ken Chan
Ken Chan

Reputation: 90517

It depends on the state of groupEntity instance passed into persist() . According to the JPA specification , the semantics of the persist(X) is:

  • If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.

  • If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element value or specified with the equivalent XML descriptor element.

  • If X is a removed entity, it becomes managed.

  • If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.

  • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.

So , I would say persist() is only required in your code in the following situations:

  1. groupEntity is the new instance that is just instantiated by the new()
  2. groupEntity has some "persist" cascade relationships and these relationships reference to some instances that are just instantiated by the new()

Upvotes: 2

Atropo
Atropo

Reputation: 12561

It's not mandatory to call persist(). If the object is already associated with an Hibernate session every modification to that object to it will be saved. From the manual Modifying persistent objects.

Upvotes: 1

Related Questions