mamoon
mamoon

Reputation: 47

how to resolve , Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements

i am trying to map the below UserRolesActivity model to Activity model which has OneToMany relationship to it. I don't know where i am doing it wrong even when the annotations i have used are correct. Can someone please help ?

@Entity
@Table(name = "user_roles_activity")
public class UserRolesActivity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "user_id")
    private Long userId;

    @Column(name = "role_id")
    private Long roleId;

    @OneToMany
    @JoinTable(name = "user_role_activities_mapping", joinColumns = @JoinColumn(name = "user_roles_id"), inverseJoinColumns = @JoinColumn(name = "activity_id"))
    private Activity activity;

}
@Entity
@Table(name = "activities")
public class Activity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

}

Upvotes: 1

Views: 2518

Answers (1)

Henrique Forlani
Henrique Forlani

Reputation: 1353

From the error:

Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements

You are trying to have a OneToMany relationship on something that is not collection. So if it makes sense according to your requirements that each UserRolesActivity is mapped to many Activities, so you you could have something like for example:

@Entity
@Table(name = "user_roles_activity")
public class UserRolesActivity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "user_id")
private Long userId;

@Column(name = "role_id")
private Long roleId;

@OneToMany
@JoinTable(name = "user_role_activities_mapping", joinColumns = @JoinColumn(name = "user_roles_id"), inverseJoinColumns = @JoinColumn(name = "activity_id"))
private List<Activity> activities;

}

Here I'm using a List, but it could be a Set, Map, Collection, etc.

Ref. https://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html#example.collection.mapping.annotations

Upvotes: 2

Related Questions