问题
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