Saving key value pairs in sleep mode | can we use a card?

I have an xml file and inside which I have some key value pairs. I want to store them as key value pairs

<parent> <key1> value </1key> <key1> value </1key> <key1> value </1key> <key1> value </1key> ... <key1> value </1key> </parent> 

Now I do not know how many key values ​​will come from xml in advance. How can I correlate it with the hibernation of an object? I can write it in a table in

 primaryKey parentId key value 1 1 k1 val 2 1 k2 val 3 1 k3 val 4 2 k1 val 5 2 k2 val 6 3 k3 val 

How can I match it for a sleeping object? I want the following structure class Parent {int parentId; String parent name KeyValue keyval; // How to model it?

}

AM using the NetBeans IDE.

+6
source share
3 answers

You can really use a map:

 public class Parent { @Id private Integer id; @OneToMany(mappedBy = "parent") @MapKey(name = "key") private Map<String, KeyValuePair> keyValuePairs; } public class KeyValuePair { @Id private Integer id; @ManyToOne @JoinColumn(name = "parent_id") private Parent parent; @Column(name = "key") private String key; @Column(name = "value") private String value; } 

You must also have a unique restriction on [parent_id - key] .

+6
source

You can also directly map a table to a table without creating a KeyValuePair class

For the map property with key-value pairs stored in MY_MAP_TABLE, it is defined as a property with the name "settings":

Define a property:

 @ElementCollection (fetch=FetchType.EAGER) @CollectionTable(name="MY_MAP_TABLE" , joinColumns=@JoinColumn (name="ID")) @MapKeyColumn(name="name") @Column(name="value") public Map<String, String> getSettings() { return settings; } 

And a table for storing a card:

  CREATE TABLE MY_MAP_TABLE ( ID NUMBER not null REFERENCES MY_PARENT_TABLE(ID), NAME VARCHAR2(256) not null, VALUE VARCHAR2(256) not null, PRIMARY KEY (ID , NAME) ); 
+3
source

If KeyValuePair is strictly confidential to the parents, the best approach would be:

 @Entity public class Parent { @Id @GeneratedValue private long id; @ElementCollection(fetch=FetchType.EAGER) @MapKeyColumn(name="key") @CollectionTable(name="keyvaluepair", joinColumns= @JoinColumn(name="id")) private Map<String, KeyValuePair> keyValuePairMap = new HashMap<String, KeyValuePair>(); //getter and setter methods } @Embeddable public class KeyValuePair { //no need of declaring key //key column will be created by MapKeyColumn private String value; //getter and setter methods } 

In this approach, KeyValuePair is always saved, merged, deleted with its parent.

Cm:

+3
source

Source: https://habr.com/ru/post/895485/


All Articles