Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist a HashMap with hibernate

Hello I am very new to the hibernate world and seem to have hit a roadblock. The object I need to store has a hashmap in it.

private Map<String, SentimentFrequencyCounts> modelData = null;

The thing is I will never need to search, sort or do any thing with this map I just need to save it with the object and load it when the object is loaded, so I was hoping there was some way that hibernate could just serializes it and then store it in a CLOB or BLOB field but I can not seem to find any way to do that.

So I next tried to have hibernate save this like so

    @OneToMany(mappedBy="ngram_data", fetch = FetchType.EAGER) 
 @MapKey(name = "attributeName") 
 public Map<String, SentimentFrequencyCounts> getModelData() {
  return modelData;
 }

But this gives me the following exception at runtime org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class:

The SentimentFrequencyCounts class is an inner class of the one I am trying to persist. So basically I think I really am not understanding how hibernate works for hashmap. Really a shame I can not just get it to serialize this and lump it up in a single column.

Thanks in advance for your help and time.

like image 850
JNR Avatar asked Jan 15 '11 14:01

JNR


People also ask

How do you persist objects in hibernate?

All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table. All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style.

How do you persist in JPA?

The persist operation must be used only for new entities. From JPA perspective, an entity is new when it has never been associated with a database row, meaning that there is no table record in the database to match the entity in question. Post post = new Post();

What is the difference between Merge and persist in hibernate?

Persist should be called only on new entities, while merge is meant to reattach detached entities. If you're using the assigned generator, using merge instead of persist can cause a redundant SQL statement.


1 Answers

@org.hibernate.annotations.Type(
        type = "org.hibernate.type.SerializableToBlobType", 
        parameters = { @Parameter( name = "classname", value = "java.util.HashMap" ) }
)
public Map<String, SentimentFrequencyCounts> getModelData() {
  return modelData;
}

Or even just this will work in most cases (distributed caching might be a problem):

@org.hibernate.annotations.Type( type = "org.hibernate.type.SerializableType" )
public Map<String, SentimentFrequencyCounts> getModelData() {
  return modelData;
}
like image 196
Steve Ebersole Avatar answered Oct 20 '22 23:10

Steve Ebersole