【问题标题】:How to map a collection Map<String,List<String>> type using Hibernate如何使用 Hibernate 映射集合 Map<String,List<String>> 类型
【发布时间】:2021-04-10 18:18:09
【问题描述】:

问题是使用 Hibernate 持久化以下类。

Public class Album{
Private int albumid;
Private String aname;
Private Map<String,List<String>> photos;
}

我试过了

@Entity
public class Album {
    @Id
    private int albumId;
    @Column(name= "Album_Name")
    private String aname;
    
    @ElementCollection
    @MapKeyColumn(name= "Event_Name")
    @Column(name="Values")
    private Map<String, List<String>> photos;

但它显示错误,例如


    Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.List, at table: Album_photos, for columns: [org.hibernate.mapping.Column(Values)]
        at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:336)
        at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:310)
        at org.hibernate.mapping.Collection.validate(Collection.java:315)
        at org.hibernate.mapping.IndexedCollection.validate(IndexedCollection.java:89)
        at org.hibernate.cfg.Configuration.validate(Configuration.java:1362)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
        at com.wipro.Insert.main(Insert.java:17)

【问题讨论】:

标签: java hibernate-mapping hibernate-annotations


【解决方案1】:

此映射不适用于 Hibernate ORM。

原因是您试图拥有两个嵌套的元素集合,而 Hibernate ORM 不支持这一点(第一个集合是 Map,第二个集合是 List)。

你必须使用实体。

您可以通过以下映射获得类似于@ElementCollection 的内容:


@Entity
public static class PhotoEvent {
    @Id
    @Column(name = "Event_Name")
    public String eventName;

    @ElementCollection
    @Column(name = "`Values`")
    public List<String> values;

    @ManyToOne
    public Album album;
...
// getter/setter/hascode/equals...
}


@Entity
public static class Album {
    ...
    
    @OneToMany(mappedBy = "album", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @MapKey(name = "eventName")
    public Map<String, PhotoEvent> photoEvents;
    
    ...
}

请注意,我设置了FetchType.EAGER,因为它模拟@ElementCollection,但您可能希望将其设置为LAZY(默认值)。

您将找到有关此类映射in the Hibernate ORM documentation 的更多详细信息。

【讨论】:

    猜你喜欢
    • 2011-10-20
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 2011-06-27
    • 2018-12-07
    • 2011-08-31
    • 2015-06-19
    相关资源
    最近更新 更多