Search code examples
jpapersistencejpqlopenjpa

Hide password field in User in JPQL queries (or with FetchType)


I have an Entity like this:

public class User {
    @Column(name = "password")
    @Element(name = "pass", data = true)
    private String password;
}

What I would like is that the field password is not read/populated in Queries by default. But in some cases I of course want to check the PWD and in this special case the PWD should be read and filled by openJPA in the User object.

What kind of Fetch strategy or JPQL queries might I use to implement this? I think FetchType.Lazy only applies to join'ed tables not single fields. Also I can't imagine a JPQL query where I can tell openJPA to overwrite this FetchType and to load this field in case I do really need it for a PWD check.

Many Thanks! Sebastian


Solution

  • Actually, it is possible to set a single field to be lazy loaded. Simply add a @Basic annotation with the lazy fetch strategy as follows:

    public class User {
        @Basic(fetch = FetchType.LAZY)
        @Column(name = "password")
        @Element(name = "pass", data = true)
        private String password;
    }
    

    More details are available here: http://openjpa.apache.org/builds/1.1.0/docs/jpa_overview_meta_field.html#jpa_overview_meta_fetch