JPA Map<String,String[]> mapping

半城伤御伤魂 提交于 2019-12-25 06:37:24

问题


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

public Map<String, String[]> parameters = new HashMap<String, String[]>();

Thanks in advance.


回答1:


An example implementation:

@Entity
@Table(name = "MAP") //optional
public class Parameters {

    @Id
    @Column(name = "\"KEY\"") //optional
    private String id;

    @ElementCollection
    @CollectionTable( //optional
        name = "MAP_VALUES", 
        joinColumns = { @JoinColumn(name="MAP_KEY") }
    ) 
    private Collection<String> collection;

    public Parameters() { }

    public Parameters(String key, Collection<String> values) {
        this.id = key;
        this.collection = values;
    }

    public Collection<String> values() {
        return collection;
    }

    // ...
}

The entity instances can be inserted into the database as follows:

em.persist(new Parameters("first", Arrays.asList("a", "b", "c")));
em.persist(new Parameters("second", Arrays.asList("d", "e", "f")));
...

This will produce two tables in the database:

MAP       MAP_VALUES

KEY       MAP_KEY COLLECTION
------    ------- ----------
first     first   a
second    first   b
          second  c
          second  d

MAP_KEY column in the MAP_VALUES table is the foreign key and refers to the MAP table.


Contents can be retrieved as follows:

Parameters entry = em.find(Parameters.class, "second");
List<String> values = entry.values();
...

or

String query = "SELECT p FROM Parameters p";
List<Parameters> entries = em.createQuery(query, Parameters.class)
                             .getResultList();
List<String> values = entry.values();
...


来源:https://stackoverflow.com/questions/23539117/jpa-mapstring-string-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!