JPA Map <string,string> mapping </string,string>

时间:2009-05-12 14:27:37

标签: java hibernate mapping persistence

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

4 个答案:

答案 0 :(得分:22)

虽然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>();

无需为Map字段创建单独的Entity类。它将自动完成。

答案 1 :(得分:15)

以下不适合您吗?

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

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

答案 2 :(得分:10)

假设我有一个名为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;
}               

}

它对我有用。

答案 3 :(得分:2)

一个工作示例:

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