hhh3112
hhh3112

Reputation: 2187

question about hibernate annotations

i have 2 entities: User and Role i have one class Userrole that will contain a composite key between user and role.

now Userrole will not contain userId and roleId.. but the object User and Role and it looks like this:

public class UserRole implements Serializable{
    User user;
    Role role;

can i put @Id on the User? like:

    @Id
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

?

Upvotes: 1

Views: 227

Answers (3)

Bence Olah
Bence Olah

Reputation: 684

The way I would do:

    @Entity
    public class User {
    ...
    @OneToMany
    public Set<UserRoles> getUserRoles() {
            return this.userRoles;
        }
    }

    @Entity
    public class UserRole {
    ...

    @Id 
    @GeneratedValue
    public long getId() {
                   return this.id;
   }

    @ManyToOne
    public Role getRole() {
            return this.role;
        }


    @ManyToOne
    public Role getCategory() {
            return this.category;
        }

    }

Upvotes: 0

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116266

Using annotations, you need to define a proper class for your composite id, and annotate it as @Embeddable. (With XML, one can map the composite id without an explicit id class too.) Here is an example using an inner class as composite id, and another one, with a top-level id class.

Upvotes: 2

no. You can only use @Id in primitives. But you can use a @ComposeId or @IdClass (something like that, cant access hibernate doc now...) and map user as your composed id

Upvotes: 0

Related Questions