Hibernate 在不引用其他表的情况下持久化 Map<String, String>

Hibernate persist Map<String, String> without referencing another tables

你能帮我用 Hibernate 持久化字符串映射吗?

地图值来自客户端并且是随机的,所以我不想为地图值单独存储 table

异常

Caused by: org.hibernate.AnnotationException: Associated class not found: java.lang.String

代码

@Entity
public class UserConfig {

    @Id
    @SequenceGenerator(sequenceName = "CONFIG_SEQ", name = "ConfigSeq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ConfigSeq")
    private Long id;

    @ElementCollection(targetClass = String.class)
    @CollectionTable(name = "MAP")
    @MapKey(name="key")
    @Column(name="value")
    private Map<String, String> map;

更新

如果 MyEnum 是未映射的 class?

,您能否也解释一下如何坚持 Map<MyEnum, String>

根据规范,您应该这样标注地图:

    @ElementCollection(targetClass = String.class)
    @CollectionTable(name = "MAP")
    @MapKeyColumn(name="key")
    @Column(name="value")
    private Map<String, String> map;

所以 @MapKeyColumn,而不是 @MapKey

当地图定义为:

private Map<Basic, Basic> map; // (i.e. Map<String, String>)

当您将地图定义为:

时,您可以使用 @MapKey 注释
private Map<Basic, Entity> map; // (i.e. Map<String, User>)

最后,当您有地图定义广告时,您可以使用 @MapKeyEnumerated 注释:

private Map<Enumeration, Basic> map; // (i.e. Map<MyEnum, String>)