实体异常映射中的重复列

时间:2014-09-09 11:26:47

标签: java mysql hibernate

我尝试实施以下内容:Many to Many Hibernate Mapping for additional property in the join table

用于创建多个与额外字段的连接。我一直得到这个异常:org.hibernate.MappingException:实体映射中的重复列:UserRole列:id(应该用insert =&#34映射; false&#34; update =&#34; false&#34;)< / p>

为什么?

我使用的是Spring 4和MySQL 我的代码:

@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();

}

1 个答案:

答案 0 :(得分:0)

您不能将同一列定义为多次。如果存在两列,则需要提及insert =“false”和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();
        }
    }