JPA Map mapping

后端 未结 4 2166
孤城傲影
孤城傲影 2020-12-03 04:53

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

相关标签:
4条回答
  • 2020-12-03 05:06

    A working example:

    @ElementCollection(fetch=FetchType.EAGER)
    @CollectionTable(name = "TABLENAME")
    @MapKeyColumn(name = "KEY")
    @Column(name = "VALUE")
    public Map<String, String> getMap() {
        return _map;
    }
    
    0 讨论(0)
  • 2020-12-03 05:10

    Although answer given by Subhendu Mahanta is correct. But @CollectionOfElements is deprecated. You can use @ElementCollection instead:

    @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 Map field. It will be done automatically.

    0 讨论(0)
  • 2020-12-03 05:11

    Does not the following work for you?

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

    EntityType could be any entity type, including a String.

    0 讨论(0)
  • 2020-12-03 05:24

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

    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.

    0 讨论(0)
提交回复
热议问题