FDFDGSFG DJDBM
FDFDGSFG DJDBM

Reputation: 11

Map having multiple values in spring hash Map

Is it possible to add multiple values to a map in spring, for example, I have the below spring map

 <property name="abcMap">
     <map>
         <entry key="615000" value="def"/>
     </map>
 </property>

What I am trying to achieve something like below

<property name="abcMap">
    <map>
        <entry key="615000" value="def" value="abc"/>
    </map>
</property>

Please advise how can we achieve the same in Spring.

Upvotes: 1

Views: 401

Answers (4)

Tamas Rev
Tamas Rev

Reputation: 7166

It would be cool to use a MultiValueMap. Unfortunately, they are not supported by the spring xsd. Here is the related excerpt:

<xsd:group name="collectionElements">
  <xsd:sequence>
    <xsd:element ref="description" minOccurs="0"/>
    <xsd:choice minOccurs="0" maxOccurs="unbounded">
      <xsd:element ref="bean"/>
      <xsd:element ref="ref"/>
      <xsd:element ref="idref"/>
      <xsd:element ref="value"/>
      <xsd:element ref="null"/>
      <xsd:element ref="list"/>
      <xsd:element ref="set"/>
      <xsd:element ref="map"/>
      <xsd:element ref="props"/>
      <xsd:any namespace="##other" processContents="strict" minOccurs="0" maxOccurs="unbounded"/>
    </xsd:choice>
  </xsd:sequence>
</xsd:group>

So as others suggested, you can use a map that has list as value.

Upvotes: 0

piy26
piy26

Reputation: 1592

The value need to be a list if you want to store multiple value for a given key something like :

<property name="abcMap">
    <map>
        <entry>
            <key>
                <value>615000</value>
            </key>
            <list>
                <value>def</value>
                <value>abc</value>
            </list>
        </entry>
    </map>
</property>

Upvotes: 1

Sagar Sahni
Sagar Sahni

Reputation: 412

You need to create list first. Then that list could be inserted in the map.

<list id="list1">
  <value>abc</value>
  <value>def</value>

<map id="emailMap" value-type="java.util.List">
  <!-- Map between String key and List -->
  <entry key="entry1" value-ref="list1" />
  <entry key="entry2" value-ref="list2" />
<map>

Then use this Map in any bean of yours like this:

    <bean id="myBean" class="com.sample.beans">
      <property name="emailMap" ref="emailMap" />
   </bean>

Upvotes: 0

Jorge.V
Jorge.V

Reputation: 1347

By definition a map can't have two values for the same key (if it was java you could put them on a list but this is not the case).

As a solution you can either concatenate them separated by a defined character like "," or use a different key for each value.

Upvotes: 1

Related Questions