Hibernate 4 -当Key是一个自定义的Hibernate UserType时,应该用什么来替换已弃用的@Map



考虑以下两个表:

| User      | UserAttribute     |
|---------- |-------------------|
| userId(PK)| attributeId(PK)   |
| firstName | userId            |
| lastName  | name              |
| other     | locale            |
| active    | value             |

在原始hibernate-3.2.2中,一对多的双向关系工作得很好:

@Entity
@Table(name = "User")
public class UserHbm {
    @Id
    @GeneratedValue(generator = "id-generator")
    @Column(name = "userId")
    private long id;
    @Column
    private String firstName;
    @Column
    private String lastName;
    @Column
    private String other;
    @Column
    private boolean active = true;
    @OneToMany (mappedBy = "user", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
    @MapKey(columns = { @Column(name = "name"), @Column(name = "locale") })
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    private Map<AttributeKeyHbm, UserAttributeHbm> attributes = null;
    //other methods, getter & setting, etc...
}

@Entity
@Table(name = "UserAttribute")
public class UserAttributeHbm {
    @Id
    @GeneratedValue(generator = "id-generator")
    @Column(name="attributeId")
    private long id;
    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
    @JoinColumn(name="userId")
    private UserHbm user;
    @Column
    private String name;
    @Column
    private Locale locale = Locale.ENGLISH;
    @Column
    private String value;
    // other methods...
}

public class AttributeKeyHbm implements UserType {
    protected static int[] SQL_TYPES = { Types.VARCHAR, Types.VARCHAR };
    private String name;
    private Locale locale;
    public AttributeKeyHbm(String name, Locale locale) {
        this.name = name;
        this.locale = locale;
    }
    //other override methods, assemble, deepCopy & nullSafeGet, etc...
}

hibernate从3.2.2迁移到4.3.11的困难之处在于UserHbm中作为attributes键的用户类型AttributeKeyHbm

AttributeKeyHbm是Hibernate的一个定制UserType,包含UserAttributeHbmnamelocal的两列。

由于hibernate注释@MapKey已弃用,我尝试逐一使用以下注释,以替换原来的@MapKey:

@MapKeyType(value=@Type(type="com.xxx.xxx.AttributeKeyHbm"))
@MapKeyJoinColumns(value={ @MapKeyJoinColumn(name = "name"),  @MapKeyJoinColumn(name = "locale")})
@MapKeyJoinColumn(name = "AttributeKeyHbm")

但最终都以这些异常结束:

org.hibernate.MappingException: collection index mapping has wrong number of columns: com.xxx.xxx.UserHbm.attributes type: com.xxx.xxx.AttributeKeyHbm

我的问题是:

  • 如何在UserHbmhibernate-4.3.11实现相同的功能,鉴于AttributeKeyHbm不能被放弃,因为它已经被其他API大量使用。
  • 由于AttributeKeyHbm有两列,是否正确或足够实现UserType接口而不是CompositeUserType

首先,它应该用MapKeyClass(JPA)替换MapKeyType(Hibernate),或者只是删除它,因为Hibernate会自动检测。

和MapKeyJoinColumns/MapKeyJoinColumn将跳过在这种情况下,参考JPA文档https://docs.oracle.com/javaee/6/api/javax/persistence/MapKeyJoinColumn.html我猜他们只用于实体。

该异常表示键UserType的列号与键列不相同。我找不到@MapKeyColumns,但我尝试了@MapKeyColumn(name="id"),并使AttributeKeyHbm只有"id",它可以工作。因此,所有这些都是为了找到MapKeyColumns-like注释

最新更新