Dmitry Korchemkin
Dmitry Korchemkin

Reputation: 298

Mapping to entity id with Hibernate

Is there a way to map entities by their ID?

Currently i have a code that works liek this:

User object has some roles assigned to it:

@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE})
@JoinTable(name = "USER_ROLES", joinColumns = {
        @JoinColumn(name = "USER_ID", nullable = false, updatable = false) },
        inverseJoinColumns = { @JoinColumn(name = "ROLE_ID", nullable = false, updatable = false) })
protected List<Role> assignedRoles = new ArrayList<>();

Role is mapped to users:

@ManyToMany(fetch = FetchType.LAZY, mappedBy = "assignedRoles")
protected Collection<? extends User> users;

The thing is, what i want is something like:

@ManyToMany(fetch = FetchType.LAZY, mappedBy = "assignedRoles")
protected Collection<Integer> users;

To operate userIds instead of User objects.

Is it possible to somehow configure Mapping to work this way? I failed to find anything on this in available Hibernate documentation.

Upvotes: 1

Views: 1943

Answers (2)

isnot2bad
isnot2bad

Reputation: 24444

In addition to the solution provided by tringel, you could also try to use hibernate's basic collection mapping feature:

@ElementCollection
@CollectionTable(name="USER_ROLES", joinColumns=@JoinColumn(name="ROLE_ID"))
@Column(name="USER_ID")
protected Set<Integer> users;

With this strategy you could also map more complex value types like some sort of UserRef object that contains the user id and some other useful properties:

@ElementCollection
@CollectionTable(name="USER_ROLES", joinColumns=@JoinColumn(name="ROLE_ID"))
@Column(name="USER_ID")
protected Set<UserRef> users;

...
@Embeddable
public class UserRef {
    public Integer id;
    public String name;
}

Upvotes: 4

tringel
tringel

Reputation: 405

This is possible using Hibernates @Formula instead of a mapping. So for your user_roles table with columns user_id and role_id, this should work:

@Formula("(SELECT USER_ID " +
        "FROM USER_ROLES " +
        "WHERE ROLE_ID = id")
protected Collection<Integer> users;

In this example the parameter id is the id field from the entity using this formula, so probably the role entity. If your user entity is a fairly basic entity this would probably not improve performance (as isnot2bad already mentioned). We used it instead of fetching a very complex entity with several relationships, where it can improve performance considerably.

Upvotes: 2

Related Questions