Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

storing key value pairs in hibernate | can we use map?

Tags:

java

hibernate

I have a xml file and within which i have some key value pairs.I want to store them in form of key value pairs

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

Now i dont know how many key value will be coming from xml in advance.How can i map it to hibernate object? i can stor it in 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 map it to hibernate object? I want following structure class Parent{ int parentId; String parent Name KeyValue keyval ; //How do i model it?

}

AM using netbeans IDE.

like image 848
Akshay Avatar asked Aug 20 '11 11:08

Akshay


People also ask

What is the use of mapping in hibernate?

Association mappings are one of the key features of JPA and Hibernate. They model the relationship between two database tables as attributes in your domain model. That allows you to easily navigate the associations in your domain model and JPQL or Criteria queries.

Which object is used to store key value pair?

A bucket is used to store multiple key value pairs . In hash map, bucket used simple linked list to store objects. Each bucket has a unique number , that's what identifies the bucket.

How do I add a key value pair to a map?

put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.

Does hibernate have mapping?

hibernate mappings are one of the key features of hibernate . they establish the relationship between two database tables as attributes in your model. that allows you to easily navigate the associations in your model and criteria queries.


1 Answers

You may indeed 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 should also have a unique constraint on [parent_id - key].

like image 61
JB Nizet Avatar answered Oct 07 '22 01:10

JB Nizet