How to persist a map inside a map in Hibernate? - java

So I have a class similar to this
public class MyClass{
...
#ElementCollection
private Map<Long,Map<Long,Double>> Vs = new HashMap<Long, Map<Long,Double>>();
...
}
This returns an error when I try to persist the class:
org.hibernate.MappingException: Could not determine type for: java.util.Map, at table: MyClass_Vs, for columns: [org.hibernate.mapping.Column(Vs)]
I think the error is because there is a map inside the original map that has the annotation of #ElementCollection. Any idea of how to solve this?

I really doubt Hibernate will be able to handle this type of mapping for you with just #ElementCollection. You probably will need to define a new composite key, containing both of those Long map keys as #Id fields, then use an element collection on a Map<CompositeLong, Double>. Granted, I'm making some assumptions about what those Long values represent, but it's hard to tell without more context.

Related

How to map an EnumMap to a cassandra column?

I need to map an EnumMap to a cassandra data column. The entity class looks like this:
#Table
class ContainingEnumMap {
#PrimaryKey
String key;
#Column
Map<SomeEnum, String> map;
}
If i register an EnumNameCodec, the instances of the above class are properly written to the database, however, if they are read back, i get a ClassCastException, as the map keys are in fact Strings.
If i explicitly use an EnumMap attribute, i get similar exceptions, as the keys are still Strings (and not enum instances).
Trying to annotate the map column with
#CassandraType(type = DataType.Name.MAP)
did not lead anywhere, as there are no proper DataType.Name constants for enums.
Is there a way to achieve this?

Mapping a complex Map in JPA

i just can't obtain a persistence with an entity which has a field like this:
private Map<String, List<String>> filterValueRange;
i've tried so far:
#ElementCollection
#JoinTable(name="ATTRIBUTE_VALUE_RANGE", joinColumns=#JoinColumn(name="ID"))
#MapKeyColumn (name="Filter_Id")
#Column(name="FILTER")
private Map<String, List<String>> filterValueRange;
But it seems there is still something missing.
Can anybody point me to the right direction?
I'm using jpa as interface, but there's Hibernate under the hood.
thanks!
Mapping nested collection relationship is not supported with JPA however you can easily overcome this by changing the object model a little, for example:
#OneToMany(mappedBy = "parent")
#MapKeyColumn (name="Filter_Id")
private Map<String, ValueRange> filterValueRange;
and in the corresponding ValueRange entity:
#ManyToOne
private Parent parent;
Alternatively you may also take a look at the following post:
JPA Map<String,String[]> mapping
I don't believe it is possible. What you are trying to achieve is to map element collection of element collections.
In case I am wrong, you should use the
#CollectionTable annotation to define your jointable.
But I think you need to define Embedable that represent value range and has its own ElementCollection of values. Than you can map this embedable to your filterValueRange and access the list of values through it.
If you don't need to query by your filterValueRange you can serialize it simply to Blob.

SortedMap Key Persistance in Hibernate

I'm hoping someone can help me with my hibernate issue as I've been banging my head against Google for around an hour without result.
So the issue is that I have a SortedMap in a class, using Integer as the Key (and its natural built-in compareTo method) and another class as the value type. I'm using the key to keep the user-defined order of the value type and trying to get Hibernate to persist this.
For whatever reason, Hibernate has defaulted to disregarding the key I have inputted and instead using the value type's primary key as the key instead. When I load my Map back out of the database all of my keys have been changed in this way.
Definition of the Map is shown below (I'm using annotation-style Hibernate);
#ManyToMany(cascade = CascadeType.ALL)
#MapKey
#Sort(type = SortType.NATURAL)
private SortedMap<Integer, Column> columnOrder;
I can't use the Column type to store the order itself as the Column may be used in many instances of the containing type, with a different key value each time. Any guidance would be most appreciated.
So I found the answer after discovering this StackOverflow question with a similar issue: Sorted map of Java primitives using JPA2 and Hibernate?
By changing the #MapKey annotation to the #MapKeyColumn annotation, I was able to give Hibernate the instruction to persist the key in the column name I specified, as below;
#ManyToMany(cascade = CascadeType.ALL)
#MapKeyColumn(name = "hierarchyOrdering")
#Sort(type = SortType.NATURAL)
private SortedMap<Integer, Column> columnOrder;
Thanks for the help.
From the javadoc of javax.persistence.OrderColumn:
Specifies a column that is used to maintain the persistent order of a list. The persistence provider is responsible for maintaining the order upon retrieval and in the database. The persistence provider is responsible for updating the ordering upon flushing to the database to reflect any insertion, deletion, or reordering affecting the list.
So it is possible to use a list for that.
The JPA 2.0 spec states in section 2.2 Persistent Fields and Properties:
Collection-valued persistent fields and properties must be defined in terms of one of the following collection-
valued interfaces regardless of whether the entity class otherwise adheres to the JavaBeans
method conventions noted above and whether field or property access is used: java.util.Collection,
java.util.Set, java.util.List[3], java.util.Map. The collection implementation
type may be used by the application to initialize fields or properties before the entity is made
persistent. Once the entity becomes managed (or detached), subsequent access must be through the
interface type.
So it seems as if a SortedMap is not supported by JPA.

Hibernate: Obtaining Map with a column's value as "key", and as "value" a list of rows containing "key"

Good afternoon,
I have the following entity:
#Entity(name = "t_test")
public class Test {
private int id;
private String name;
private String type;
....
I basically want to create a query/criteria that returns just one Map, where the keys are the distinct values of Test.type, and the values of the map are Lists of Test objects with the corresponding type property.
E.g: Map>
Can this be done in one query? Right now I'm just fetching everything and creating the map by code.
Thanks in advance!
You could write a ResultTransformer to create and return the map, but it wouldn't be much different than what you're doing now. The code would just be in a different place.
To produce the Map<String, List<Test>>, you need to load all the test entries from the database anyway. There's no processing related to the map creation that can be moved closer to the DB except maybe ordering by type. You basically have to make the map in your code.

Hibernate mapping a UserType inside a Map

I have come across a problem where I cannot persist a Map<UUID, Integer> using Hibernate. I'm not sure how to properly annotate this collection such that it may be properly mapped into our database. We control the schema, so any way this will work will be fine. Do i need to specify what UserType the key is in my Map somehow? Do I need one? I know the Type annotation is used for individual fields. Perhaps not collections? I am receiving the following exception on my call to session.flush()
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.UUID
#ElementCollection
#Type(type="org.hibernate.type.UUIDCharType")
private Map<UUID, Boolean> orderCount = new HashMap<UUID, Integer>();
I believe you will have to write a UserType to handle Map<UUID, Boolean> .. This UserType should then use org.hibernate.type.UUIDCharType to map the key column.

Categories

Resources