Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EclipseLink/JPA @OneToMany Backpointer Cardinality Error

I am trying to generate a unidirectional one-to-many mapping between two JPA entities. In my ChatRoom class, I have a Vector<User> type object that represents Users in a ChatRoom. I am trying to create a one-to-many mapping, based on userId (in the User class). Here is my sample code:

@Entity
public class ChatRoom {
    @Id
    @GeneratedValue
    private int chatRoomID;

    @OneToMany(mappedBy="userID")
    private Vector<User> users;

    // A no-argument constructor is required for EclipseLink to instantiate the persistence object properly.
    public ChatRoom() {}

    // Getter/Setter section
}

Here is the User class:

@Entity
public class User {
    @Id
    @GeneratedValue
    private int userID;

    private String username;

    // Getter/Setter section
}

When I try to generate the tables from these entities in Eclipse, I get the following error:

Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ChatJPA] failed.
Internal Exception: Exception [EclipseLink-7244] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.ValidationException
Exception Description: An incompatible mapping has been encountered between [class iosoa.entity.ChatRoom] and [class iosoa.entity.User]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
    at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:126)

Do you have any ideas on how to resolve this problem? Thanks for your help.

like image 957
Nick Ruiz Avatar asked Feb 06 '11 11:02

Nick Ruiz


2 Answers

A few things,

Your mappedBy is wrong, a mappedBy for a OneToMany must be a ManyToOne. I would recommend you add the ManyToOne back, or use a @JoinTable, if you do not wish to, then you could use an @JoinColumn and no mappedBy.

Vector is not valid in JPA, you must use List, Set or Map. You can still use a Vector as your implementation class. If you really want to use Vector, then EclipseLink will support this, but you must make your mapping EAGER.

like image 113
James Avatar answered Sep 28 '22 06:09

James


I guess It's problem of mappedBy annotation. It should be: "private ChatRoom chatRoom;" in your user class. And in mappedBy try to write this variable. P.S. If you don't have link to CharRoom in your relation, than you for sure have join table. Then you should use @JoinTable annotation and @OneToMany without mappedBy.

like image 36
Konstantin Milyutin Avatar answered Sep 28 '22 04:09

Konstantin Milyutin