Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to initialize fields inside a JPA entity getter?

Tags:

java

jpa

In POJO Java beans such code can be beneficial, especially with collections:

class POJO {
    private Collection<X> col;

    public Collection<X> getCol() {
        if (col == null)
           col = new SomeCollection<X>();

        return col;
    }
}

It makes possible for the code using POJO to call pojo.getCol().isEmpty() without an additional null check, thus making the code clearer.

Suppose the POJO class is a JPA entity, is it still safe to do that? By initializing the collection from null to an empty one the persistent data won't be changed, but still, we are modifying the object and thus the persistence provider may run some side effects upon flushing the persistence context. What do we risk? Portability maybe?

like image 486
MaDa Avatar asked Oct 17 '11 08:10

MaDa


People also ask

Which strategy specifies that data should only be fetched when it is first accessed in JPA?

The LAZY strategy specifies that data should only be fetched when it is first accessed. According to the JPA specification, this is only a hint and a particular JPA implementation is free to eagerly fetch data for which the LAZY strategy has been specified.

Do JPA entities need setters?

JPA needs a constructor and setter for each declared field. Does it mean we have to expose the default constructor and each setter ? JPA supports private constructor and private setters. This entity is a valid JPA entity and it can't be modified after its creation.

Is it necessary to initialize local variable in Java?

Local variables must be initialized before use, as they don't have a default value and the compiler won't let us use an uninitialized value.

Do JPA entities need constructors?

Rules for JPA Entities 1. The entity class must have a no-arg constructor. The entity class may have other constructors as well. The no-arg constructor must be public or protected.


1 Answers

I do not see it as a good practice, more as some very rarely needed optimization. Maybe lazy initialization can make sense if SomeCollection is extremely heavy to create. Instead you can initialize it when declared (code is cleaner at least for my eyes):

class POJO {
    private Collection<X> col  = new SomeCollection<X>();

    public Collection<X> getCol() {
        return col;
    }
}

There is no side effects in flush or portability issues and you have one null check less.

like image 57
Mikko Maunu Avatar answered Oct 12 '22 14:10

Mikko Maunu