簡體   English   中英

如何使用Hibernate / JPA保留自定義地圖?

[英]How to persist a custom map with Hibernate/JPA?

我試圖使用Hibernate和JPA批注將子類HashMap保留在數據庫中。

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MapKeyColumn;
import javax.persistence.Table;

@Entity
@Table(name = "module")
public class Module {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "version")
    private String version;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "module_parameter")
    @MapKeyColumn(name = "key")
    @Column(name = "value")
    private Parameters params = new Parameters();

    // Getters & setters

}

嘗試存儲參數時,這給了我以下異常:

org.hibernate.AnnotationException: Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: Module.params

當我將聲明更改為

private Map<String, String> params = new Parameters();

public Parameters getParams() {
    return (Parameters) params;
}

我得到以下輸出:

Hibernate: select module0_.id as id1_0_, module0_.description as descript2_0_, module0_.name as name3_0_, module0_.version as version4_0_ from module module0_
Hibernate: select params0_.Module_id as Module_i1_0_0_, params0_.value as value2_1_0_, params0_.key as key3_0_ from module_parameter params0_ where params0_.Module_id=?
Exception in thread "main" java.lang.ClassCastException: org.hibernate.collection.internal.PersistentMap cannot be cast to Parameters

如果我將其更改為

private Map<String, String> params = new HashMap<>();

一切正常。

那么我如何告訴Hibernate Parameters是一個集合呢?

您必須創建一個實現UserCollectionType接口的類,然后提供此類以使其休眠以告知您要使用自定義集合。

請參閱以下鏈接以了解如何創建自定義集合:

如何在JPA中映射自定義集合?

休眠:自定義集合類型

這是未經測試的 也許您可以嘗試看看是否可行:為什么不只返回Map<String, String>

JPA使用常見的收集接口工作: ListSetMap 因此,如果Parameters IS-A Map ,則可以將其作為Map返回。

更改:

public Parameters getParams() {
    return (Parameters) params;
}

至:

public Map<String, String> getParams() {
    return params;
}

另外,由於Hibernate具有允許延遲加載的類,即PersistentListPersistentSetPersistentMap等,因此您可以使用composition返回由Hibernate返回的Parameters

因此,您實質上可以自定義方法,以從返回的Hibernate集合返回值。

這種效果:

public Map<String, String> getParams() {
    return new Parameters(params); //params is injected with Hibernate's PersistentMap.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM