Java JPA Map<String,String> 映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/853076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:13:21  来源:igfitidea点击:

JPA Map<String,String> mapping

javahibernatemappingpersistence

提问by Rafa de Castro

How can I map a Map in JPA without using Hibernate's classes?

如何在不使用 Hibernate 的类的情况下在 JPA 中映射 Map?

采纳答案by Chris K

Does not the following work for you?

以下不适合您吗?

@ManyToMany(cascade = CascadeType.ALL)
Map<String,EntityType> entitytMap = new HashMap<String, EntityType>();

EntityTypecould be any entity type, including a String.

EntityType可以是任何实体类型,包括String.

回答by Subhendu Mahanta

Suppose I have an entity named Book which is having a Map of chapters:

假设我有一个名为 Book 的实体,它有一个章节地图:

import java.io.Serializable;
import java.util.Map;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;    
import org.hibernate.annotations.CollectionOfElements;
import org.hibernate.annotations.MapKey;
@Entity
public class Book implements Serializable{
@Column(name="BOOK_ID")
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long bookId;    

@CollectionOfElements(targetElement=java.lang.String.class)
@JoinTable(name="BOOK_CHAPTER",
        joinColumns=@JoinColumn(name="BOOK_ID"))
@MapKey (columns=@Column(name="CHAPTER_KEY"))
@Column(name="CHAPTER")
private Map<String,String> chapters;
public Long getBookId() {
    return bookId;
}
public void setBookId(Long bookId) {
    this.bookId = bookId;
}
public Map<String,String> getChapters() {
    return chapters;
}
public void setChapters(Map<String,String> chapters) {
    this.chapters = chapters;
}               

}

It works for me.

这个对我有用。

回答by Jatin Sehgal

Although answer given by Subhendu Mahanta is correct. But @CollectionOfElementsis deprecated. You can use @ElementCollectioninstead:

尽管 Subhendu Mahanta 给出的答案是正确的。但@CollectionOfElements已弃用。您可以@ElementCollection改用:

@ElementCollection
@JoinTable(name="ATTRIBUTE_VALUE_RANGE", joinColumns=@JoinColumn(name="ID"))
@MapKeyColumn (name="RANGE_ID")
@Column(name="VALUE")
private Map<String, String> attributeValueRange = new HashMap<String, String>();

There is no need to create a separate Entity class for the Mapfield. It will be done automatically.

无需为该Map字段创建单独的实体类。它会自动完成。

回答by Taioli Francesco

A working example:

一个工作示例:

@ElementCollection(fetch=FetchType.EAGER)
@CollectionTable(name = "TABLENAME")
@MapKeyColumn(name = "KEY")
@Column(name = "VALUE")
public Map<String, String> getMap() {
    return _map;
}