如何使用JPA存储Map<String, List<String>>?

5

我尝试使用JPA存储一个Map<String, List<String>>

我的实体看起来像:

@Entity
@Table(name = "Profiles_table")
public class Profiles {

    @Id
    @Column(name = "profile_ID", updatable = false, nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private final HashMap<String, List<String>> AllProfiles;
    ...
}

我尝试了很多地图设置,但它还是无法工作...
我尝试的最后一个设置是:
@ElementCollection
@MapKeyColumn(name = "Profil")
@Column(name = "Permissions")
@CollectionTable(name = "Profiles_permissions", joinColumns = @JoinColumn(name = "profile_ID"))

抛出以下异常:
org.hibernate.AnnotationException: Illegal attempt to map a non collection as a
@OneToMany, @ManyToMany or @CollectionOfElements: [...]Profiles.AllProfiles

感谢您提前的帮助。

看一下这个问题:https://dev59.com/wHNA5IYBdhLWcg3wfd8m貌似没有合适的方法来解决这个问题。恐怕你必须使用自定义类了。 - Cyrille Ka
谢谢你提供的信息,我在搜索时错过了!我会看一看。 - XioRcaL
3个回答

1

虽然这不是一个答案,但这是我使用的方法。

我将第二层集合存储为Blob。

@Entity
@Table(name = "Profiles_table")
public class Profiles {

@Id
@Column(name = "profile_ID", updatable = false, nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private int                                 id;

@Column(length = 16777210)
private final HashMap<String, Set<String>>  AllProfiles;

1

字符串不是实体,因此不应使用@OneToMany等...

你试过这个吗:

@CollectionOfElements
private Map<String, List<String>> allProfiles;

1
无法工作,出现错误:无法确定类型为java.util.List的表...... - Nawa
1
很确定这个答案是指@ElementCollection,它会出现与@Nawa提到的相同错误。 - nickb

0

你尝试过将AllProfiles声明为接口类型(比如Map)吗? 请查看{{link1:在使用ConcurrentHashMap进行注释时,在Hibernate中将非集合映射为@OneToMany、@ManyToMany或@CollectionOfElements的非法尝试}}。


在所有配置文件中使用接口类型会引发此问题(因为Hibernate不擅长处理接口):无法确定类型:java.util.Map,在表格profiles_table中的列[org.hibernate.mapping.Column(all_profiles)]。 - XioRcaL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接