java.lang.IllegalArgumentException: Can not set java.util.TreeMap field

89 Views Asked by At

I have a Points Object with a property of Map<Round, Integer>. Everything worked fine! I then decided to swap this for a TreeMap so that all Points records were sorted by the Round key. Implemented Round with Comparable Interface as part of this. I'm getting an Illegal Argument Exception error:

Can not set java.util.TreeMap field to org.hibernate.collection.spi.PersistentSortedMap

I can't see what the issue is - any clues?

Field:

private TreeMap<Round, Integer> points;

Constructor:

this.points = new TreeMap<>();

Setter:

public void setPoints(TreeMap<Round, Integer> points) {
  this.points = points;
}
3

There are 3 best solutions below

1
samabcde On

Refer to collections-semantics

The semantics of a collection describes how to handle the collection, including
-the collection subtype to use - java.util.List, java.util.Set, java.util.SortedSet, etc.

SORTED_MAP
A map that is sorted by keys according to a Comparator defined on its mapping

By default, Hibernate interprets the defined type of the plural attribute and makes an interpretation as to which classification it fits in to, using the following checks:
...
if a SortedMap → SORTED_MAP

You should use interface Map(if sorting doesn't matter)/SortedMap instead of implementation TreeMap when defining your field.

i.e.

private SortedMap<Round, Integer> points;

public void setPoints(SortedMap<Round, Integer> points) {
  this.points = points;
}

public SortedMap getPoints() {
  return this.points;
}
1
iheb ali On

it seems like a it's an hibernate issue, first try to add those annotations on your map field

@CollectionTable(name = "attributes_tags" ,joinColumns = @JoinColumn(name = "swift_configuration_id" )  )
@MapKeyColumn(name = "attribute_name" )
@Column(name = "attribute_tag")
private TreeMap<String, String> attributesTags = new HashMap <> (); // used to map the attributes name with their tags 

in this case hibernate will stock the fields in they're natural order in the data base but when you retrive the data it wil be sorted (depending on the implemented Comparable)

0
abdlost On

Just to close the loop. Either use SortedMap as per samabcde answer. Alternatively, if retaining the Map Interface, use @SortNatural as the annotation. They do not need used together.

@SortNatural
private Map<Round, Integer> points;