0

I'm trying to implement to following : Many to Many Hibernate Mapping for additional property in the join table

for creating many to many connection with extra fields. I keep getting this exception:

org.hibernate.MappingException: Repeated column in mapping for entity:
UserRole column: id (should be mapped with insert="false" update="false")

Why?

I'm using spring 4 and MySQL My code:

@Entity
@AssociationOverrides({ @AssociationOverride(name = "pk.user", joinColumns = @JoinColumn(name = "id")),
@AssociationOverride(name = "pk.role", joinColumns = @JoinColumn(name = "id")) })
public class UserRole extends AbstractEntity {
    private UserRoleId pk;

    public UserRole(User user, Role role) {
        super();
        this.pk = new UserRoleId(user, role);
    }

    @EmbeddedId
    public UserRoleId getPk() {
        return pk;
    }

    public Long getUserId() {
        return pk.getUser().getId();
    }

    public Long getRoleId() {
        return pk.getRole().getId();
    }
}

@Embeddable
public class UserRoleId implements Serializable {
    private User user;
    private Role role;

    public UserRoleId(User user, Role role) {
        super();
        this.user = user;
        this.role = role;
    }

    @ManyToOne
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

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

    public void setRole(Role role) {
        this.role = role;
    }

}

@MappedSuperclass
public abstract class AbstractEntity {
    @Column(nullable = false)
    protected Date timeCreated;

    @Column
    private Long modifiedBy;

    public AbstractEntity() {
        super();
        this.timeCreated = DateUtil.now();
        this.modifiedBy = 0l;
    }

    public Date getTimeCreated() {
        return timeCreated;
    }

    public void setTimeCreated(Date timeCreated) {
        this.timeCreated = timeCreated;
    }

    @Override
    public abstract String toString();
}
lior
  • 1,127
  • 3
  • 24
  • 43

1 Answers1

0

You can't define same column as more than times. If two columns present there, You need to mention insert = "false" and update = "false"

@Entity
@AssociationOverrides({ @AssociationOverride(name = "pk.user", joinColumns = @JoinColumn(name = "id")),
@AssociationOverride(name = "pk.role", joinColumns = @JoinColumn(name = "id", insertable = false, updatable = false)) })
public class UserRole extends AbstractEntity {
    private UserRoleId pk;

    public UserRole(User user, Role role) {
        super();
        this.pk = new UserRoleId(user, role);
    }

    @EmbeddedId
    public UserRoleId getPk() {
        return pk;
    }

    public Long getUserId() {
        return pk.getUser().getId();
    }

    public Long getRoleId() {
        return pk.getRole().getId();
    }
}
ashokhein
  • 1,048
  • 12
  • 38