0

I have some tables in my database that represent Java Maps. They have two columns (key and value):

+---+-------+---------+
|   |  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 |
+---+-------+---------+

Now suppose that I have this class:

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;
    }

}

How can I map the table to the params variable using JPA/Hibernate annotations?

P.S.

I don't know if it is important, but I want to sub-class HashMap for the params, so that it becomes like this:

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;
    }

}
stevecross
  • 5,588
  • 7
  • 47
  • 85
  • You will get a list of Entities when you fetch from table which contains your key as well as value. In this case, I don't think its possible to do generate map through annotations. Basically you will have list of your key-value pairs but in separate objects. so you can use that. – Sushant Tambare Oct 08 '14 at 07:01
  • @javadev hibernate queries return `List` http://stackoverflow.com/a/417029/892994 – erencan Oct 08 '14 at 07:09
  • yes List. I was telling that key-value will be there in separate variables of object. But they will be present there. – Sushant Tambare Oct 08 '14 at 07:12

1 Answers1

2

I have found the solution. It can be done using only JPA annotations. Here is the code:

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "module_parameter")
@MapKeyColumn(name = "key")
@Column(name = "value")
private Map<String, String> params = new HashMap<>();
stevecross
  • 5,588
  • 7
  • 47
  • 85