Wednesday, April 11, 2012

Hibernate : Repeated column in mapping for entity error

Well I guess I need to explain this error so when I’ll get it one more time I’ll at least have a place to see where the problem was.

So I was having this problem because I’ve got an entity and also I’ve got a composed primary key entity that was embedded in the first one.

So let’s imagine I’ve had some GridPreferences entity, that had the GridPreferencesPK composed entity as a primary key which contained userId, and gridId.

GridPreferences.java

@Entity
@Table(name = "GRID_PREFERENCES")
public class GridPreferences extends BaseEntity{
    
    private static final long serialVersionUID = 6521799809955099787L;

    @EmbeddedId
    private GridPreferencesPK id;
    
    @Column(name = "GRPR_GRID_ROWS_PER_PAGE", nullable = false)
    private int rowsPerPage;

}

GridPreferencesPK.java

@Embeddable
public class GridPreferencesPK extends BaseEntity {
    
    private static final long serialVersionUID = 2499336910059865064L;

    @Column(name = "GRPR_USER_ID", nullable = false, precision = 8)
    private String userId;
    
    @Column(name = "GRPR_GRID_ID", nullable = false, precision = 250)
    private String gridId;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "GRPR_USER_ID", insertable = false, updatable = false)
    private User user;
}

Now I got this error  org.hibernate.MappingException: Repeated column in mapping for entity. Which isn’t exactly self-explanatory. But this time Hibernate got it right.

Basically it is an embedded primary key, so it would be logical that all the fields that are in the PK are the fields of the table itself, not the relation tables.

And the solution is to move the connections to other entities into base entity, in our example GridPreference. Doing that will solve the problem.

Hope this will help someone else too.