Cookies help us deliver our services.

By using our services, you agree to our use of cookies. Learn more

I understand

Working with Service Builder, you'll certainly notice a lot of useful methods exposed by the persistence class EntityLocalServiceUtil; among the various generated methods, there are two of them used to retrieve an instance of a single entity starting from the primary key: getEntity and fetchEntity.

But what's the difference between these two methods?

Both methods have the same behavior, namely they retrieve the instance of the entity corresponding to the primary key provided; and both of them, in case of a system failure, throw a SystemException exception.

Methods' signatures are also similar:

Entity getEntity(long primaryKey) throws PortalException, SystemException;
Entity fetchEntity(long primaryKey) throws SystemException;

Ciò che li differenzia è il loro comportamento nel caso in cui l'entità corrispondente alla chiave primaria non esista; infatti mentre il metodo fetchEntity restituisce semplicemente null, il metodo getEntity lancia un'eccezione di tipo NoSuchEntityException (sottoclasse di PortalException).

The difference between them is the behavior in case the entity corresponding to the primary key does not exist; while fetchEntity method simply returns null, the getEntity method throws a NoSuchEntityException exception (a subclass of PortalException).

Which method to use? It depends on how you prefer to handle the errors.

Finally you must know that getEntity method invoke internally the fetchEntity method.

Remember that the Entity term must be replaced with the specific entity name.