I would like to map a LinkedHashMap with Hibernate (annotation driven).
I know the property @MapKey and @IndexColumn, but can I used both to map a linkedhashmap with basics strings ?
Please don't give a solution where I must externalize pet to a class and use a开发者_JAVA百科 Pet list instead of a LinkedHashMap (I know how to do that but I clearly don't want to do this).
my class :
@Entity
public class Person
{
private LinkedHashMap<String, String> pets;
// map definition ?
// id of the pet > name of the pet
public LinkedHashMap<String, String> getPets()
{
return pets;
}
...
}
You may use the @Lob
annotation: the LinkedHashMap will be serialized and stored in a BLOB column (and deserialized when read from the database).
But this is of course fragile, impossible to query, forces the use of Java to read the contents of the pets.
If you need a more traditional mapping to an additional Pet table, with a one-to-many association, then you'll need a Pet entity.
Just stubled upon this because I'm trying to learn Hibernate (version 3)
I've done something like this to sort on the database side: You can't map a LinkedHasMap directly to Hibernate because it's not a collection, it's an implementation of a collection.
You can do something like this:
@ElementCollection
@JoinTable(name = "PERSON_PET", joinColumns = @JoinColumn(name = "PERSON_ID"))
@MapKeyColumn(name = "PET_KEY")
@Column(name = "PET_NAME")
@OrderBy(clause = "lower(PET_NAME) asc")
private Map<String, String> pets = new LinkedHashMap<String, String>();
Quote from Java Persistence with Hibernate
You can order by any column of the collection table. Internally, Hibernate uses a LinkedHashMap, a variation of a map that preserves the insertion order of key elements. In other words, the order that Hibernate uses to add the elements to the collection, during loading of the collection, is the iteration order you see in your application. The same can be done with a set: Hibernate internally uses a LinkedHashSet. In your Java class, the property is a regular Set/HashSet, but Hibernate’s internal wrapping with a LinkedHashSet is again enabled with the order-by attribute
You may use @ElementCollection
annotation to map a map of basic types. Should look like
@ElementCollection(fetch=FetchType.EAGER)
@CollectionTable(name = "person_pets", joinColumns = @JoinColumn(name = "person_id"))
@MapKeyColumn(name = "name")
@OrderColumn(name = "name")
@Column(name = "pet")
private Map<String, String> pets = new LinkedHashMap<String, String>();
精彩评论