0

I am new to JPA/Hibernate and I have a situation similar to what is described in this post:

Is it possible to dynamically define column names in Hibernate / JPA?

Just that my table contains 50 key/value pairs which I want to declare as a single object and then compact all the columns into a collection (a map would work as well). The answer of the above question describes how to declare a custom naming strategy for the columns but I am having difficulties putting the whole thing together. I want to avoid having a model with 100 (50) fields and cannot imagine how exactly the collection of pairing classes (or map) will be declared to map the 50 individual pairs.

What I am trying to achieve is similar to this:

Using List or Set in JPA 2.1 for multiple columns in same table

Unfortunately the answer described does not work for me since I cannot afford to externalise the collection in another table.

My table looks like this:

id serial primary key,

name VARCHAR(255) NOT NULL,

key_1 BIGINT,

value_1 VARCHAR(255),

key_2 BIGINT,

value_2 VARCHAR(255),

. .

key_50 BIGINT,

value_50 VARCHAR(255)

I would like to compact it into something like:

@Entity
@Table(name="table")
public class MyModel {

    @Id
    Long id = null;

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

    Map<K,V> values; //Or a List<MyKeyValuePair> values; 
}

Any suggestions?

Thanks

Community
  • 1
  • 1
Boscaiolo
  • 3
  • 1
  • 4
  • 1
    That's a terrible table design. You should fix that first – Neil McGuigan Apr 07 '15 at 18:40
  • Are there really not a fixed number of columns, or are you just looking to not have to map them all? I also concur that it should be on another table if it is in your control to do so. If the columns are fixed, I would map each one out. Then you can create another method Map getValues() and annotate it as @Transient. Use Reflections or something like [BeanMap](https://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/BeanMap.html) to build the map and return it. – Paul Zepernick Apr 07 '15 at 19:34
  • Unfortunately I can not change the table structure. – Boscaiolo Apr 08 '15 at 09:55
  • @PaulZepernick after different experiments I will go with creating an Embedable class that contains the mapped columns and construct a Transient BeanMap from that on runtime (and accept one in the setter from which will reconstruct the embedded class) and public expose only the: public BeanMap getValues() public void setValues(BeanMap values) – Boscaiolo Apr 09 '15 at 12:40

0 Answers0