Eugene Voevodin Eugene Voevodin - 1 year ago 89
Java Question

Getting certain value from the foreign entity using JPA

I have 2 entities User and Profile where one user has one profile.


entity mapping is pretty clear and looks like this:

public class User {

private String id;

@Column(unique = true, nullable = false)
private String email;

@Column(unique = true, nullable = false)
private String name;

So the question is about Profile entity mapping, the tricky thing
here is that Profile includes user's email(not entire user's entity), but it shouldn't be either updated or stored by Profile, so the email is readonly attribute from the foreign User entity.

I used the following Profile's entity mapping for getting User's email:

public class Profile {

private String userId;

private User user;

private String firstName;

private String lastName;

// ...

public String getEmail() {
return user.getEmail();

So i decided to join the entire entity and delegate the work to it.
As far as i understand it is impossible to use
in couple with
like this:

@JoinColumn(name = "userId", insertable = false, updatable = false)
@Column(name = "email")
private String email;

I am also not sure about using of
as it seems that it is designed for a different purpose.

Is there any better approach for getting foreign entity field using JPA mappings?

  • JPA Backend: EclipseLink 2.6.2

Answer Source

That's not really what JPA was designed to do. Getting the email by just calling user.getEmail() is the cleanest option you have.

You shouldn't be worried too much about loading the entire user; the way I see it it's a single join, and JPA should do it for you. The performance impact should be minimal. (you can simple not expose the internal user object to not impact your object design too much. When using JPA, you're always limiting your OO design options though).

If you were using hibernate, the story would be different. Then you could use the @Formula annotation. It would not be more performant though. Eclipselink has nothing like it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download