Map database table to a Hashtable
I have simple table in Oracle db with the columns : "KEY", "VALUE". I would like to map this table in my java code as a is there anyway of doing this straight开发者_如何学运维ly in JPA? or should I do it manually ?
Thanks, ray.
If key and value are basic or embedded types then you want to use
@ElementCollection
@CollectionTable(name = "table")
@MapKeyColumn(name = "KEY")
@Column(name = "VALUE")
protected Map<A,B> map;
If they are entites then you want to have a look at the docs for the following, so you can choose which is most appropriate.
@OneToMany
@ManyToMany
@MapKey
@MapKeyClass
You can use this piece of code:
public Map<String, String> getAll() {
Map<String, String> ret = new HashMap<String, String>();
Query query = em.createQuery("select kvp from KeyValuePair kvp");
for (KeyValuePair kvp : query.getResultList())
{
ret.put(kvp.getKey(), kvp.getValue());
}
return ret;
}
Do keep in mind that if your table is too big, you might end up having memory issues.
Commons Configuration has a DatabaseConfiguration class for mapping key value tables to a Java Properties like class.
精彩评论