如何使用Hibernate将表映射到Map?

时间:2014-10-08 06:52:58

标签: java hibernate

我的数据库中有一些代表Java Map的表。它们有两列(键和值):

+---+-------+---------+
|   |  Key  |  Value  |
+---+-------+---------+
| 1 | key-1 | value-1 |
| 2 | key-2 | value-2 |
| 3 | key-3 | value-3 |
| 4 | key-4 | value-4 |
| 5 | key-5 | value-5 |
+---+-------+---------+

现在假设我有这门课程:

public class MyClass {

    private Map<String, String> params;

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

    public void setParams(Map<String, String> params) {
        this.params = params;
    }

}

如何使用JPA / Hibernate注释将表映射到params变量?

P.S。

我不知道它是否重要,但我想为HashMap分类params,以便它变成这样:

public class Params extends HashMap<String, String> {

}

public class MyClass {

    private Params params;

    public Params getParams() {
        return params;
    }

    public void setParams(Params params) {
        this.params = params;
    }

}

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。它只能使用JPA注释来完成。这是代码:

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "module_parameter")
@MapKeyColumn(name = "key")
@Column(name = "value")
private Map<String, String> params = new HashMap<>();