fred madison
fred madison

Reputation: 85

JPA: How to exclude certain fields from loading from database table

i have a class User which holds an email address and password for authentication users in my web application. This user is mapped to the database via JPA / Eclipselink.

My question is, how can i prevent JPA from loading the password field back from the database? Since i will access the user object in my web app, i'm uncomfortable regarding security with sending the password to the browser.

Is there any way i can prevent loading the field in JPA / EclipseLink? Declaring the field transient is not an option, since i want to store it on the database when i call persist() on the user object.

Thanks, fredddmadison

Upvotes: 3

Views: 2418

Answers (2)

Jeff_Alieffson
Jeff_Alieffson

Reputation: 2882

I have the similar problem. But in my case I have many @OneToMany relationships inside of Entity class and some of them are EAGER. When I query against this Entity it loads all of them, although for web service I need only some of them. I tried TupleQuery. But it's not the solution because to get needed OneToMany relationships I have to join and get many duplicate rows of the main query. It makes the result more heawy, than economic.

Upvotes: 0

Shaun
Shaun

Reputation: 2530

JB Nizet has a valid point. Retrieving it and serializing it in the Http response are two separate concerns.

I'm not sure what you're using to serialize your data. If it this is a REST API, consider Jackson's @JsonIgnore annotation or Eclipselink MOXy's @XmlTransient equivalent. If this uses Java EL (facelets, jsps), you should be able to select only the bean properties of interest.

If you really must do this during retrieval, consider JPQL's/Criteria API's constructor functionality. Ensure that the object has a constructor that accepts the specified parameters, and keep in mind that it won't be managed in the persistence context if it's retrieved in this manner.

SELECT NEW my.package.User(u.id, u.name, u.etc) FROM User u

Alternatively, consider the @PostLoad lifecycle callback.

@PostLoad
private void postLoad() {
    this.password = null;
}

Finally, this might not be the case, but I would like to reinforce the notion that passwords shouldn't be stored in plaintext. I mention this because returning a hashed salted password that used a secure algorithm (bCrypt, multiple iteration SHA-512, etc) wouldn't be that big a deal (but still isn't ideal).

Upvotes: 2

Related Questions