Eugene Voevodin Eugene Voevodin - 5 months ago 26
Java Question

Getting certain value from the foreign entity using JPA

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

The

User
entity mapping is pretty clear and looks like this:

@Entity
public class User {

@Id
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:

@Entity
public class Profile {

@Id
private String userId;

@PrimaryKeyJoinColumn
private User user;

@Basic
private String firstName;

@Basic
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
@JoinColumn
in couple with
@Column
like this:

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


I am also not sure about using of
@SecondaryTable
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

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.