猿问

使用JPA存储Map <String,String>

我想知道是否可以使用批注attributes使用JPA2 将地图保留在以下类中


public class Example {

    long id;

    // ....

    Map<String, String> attributes = new HashMap<String, String>();

    // ....

}

由于我们已经有了一个现有的生产数据库,因此理想情况下,值attributes 可以映射到以下现有表:


create table example_attributes {

    example_id bigint,

    name varchar(100),

    value varchar(100));


饮歌长啸
浏览 1442回答 2
2回答

HUX布斯

JPA 2.0通过@ElementCollection注释可以支持原语集合,您可以将其与java.util.Map集合支持一起使用。这样的事情应该起作用:@Entitypublic class Example {&nbsp; &nbsp; @Id long id;&nbsp; &nbsp; // ....&nbsp; &nbsp; @ElementCollection&nbsp; &nbsp; @MapKeyColumn(name="name")&nbsp; &nbsp; @Column(name="value")&nbsp; &nbsp; @CollectionTable(name="example_attributes", joinColumns=@JoinColumn(name="example_id"))&nbsp; &nbsp; Map<String, String> attributes = new HashMap<String, String>(); // maps from attribute name to value}另请参见(在JPA 2.0规范中)2.6-可嵌入类和基本类型的集合2.7地图集10.1.11-ElementCollection批注11.1.29 MapKeyColumn注释

陪伴而非守候

&nbsp; @ElementCollection(fetch = FetchType.LAZY)&nbsp; @CollectionTable(name = "raw_events_custom", joinColumns = @JoinColumn(name =&nbsp; &nbsp; &nbsp;"raw_event_id"))&nbsp; @MapKeyColumn(name = "field_key", length = 50)&nbsp; @Column(name = "field_val", length = 100)&nbsp; @BatchSize(size = 20)&nbsp; private Map<String, String> customValues = new HashMap<String, String>();这是有关如何通过控制列和表名以及字段长度来设置映射的示例。
随时随地看视频慕课网APP

相关分类

Java
我要回答