JPA Map mapping

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

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

4条回答
  •  盖世英雄少女心
    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 chapters;
    public Long getBookId() {
        return bookId;
    }
    public void setBookId(Long bookId) {
        this.bookId = bookId;
    }
    public Map getChapters() {
        return chapters;
    }
    public void setChapters(Map chapters) {
        this.chapters = chapters;
    }               
    
    }
    

    It works for me.

提交回复
热议问题