0

マップを含む単純な JPA マッピングの例があります。TestEntity には、SubEntity-Object といくつかのキーのマップがあります。マップキーが保存されていることを期待していました。代わりに、それらは null です。コードは次のとおりです。

@Entity
public class TestEntity {

    @OneToMany
    public Map<String, SubEntity> map = new HashMap<String, SubEntity>();

    @Id
    @GeneratedValue(strategy = AUTO)
    protected long id;

    public String name;

    public TestEntity() {
    }

    public TestEntity(String name) {
        this.name = name;
    }
}

サブエンティティは次のとおりです。

@Entity
public class SubEntity {

    @Id
    @GeneratedValue(strategy = AUTO)
    protected long id;

    public SubEntity() {
    }

    String subEntityName;

    public SubEntity(String name) {
        this.subEntityName = name;
    }
}

そして、ここにテストコードがあります:

EntityManager em = EntityManagerService.getEntityManager();
em.getTransaction().begin();

for (int i = 0; i < 10; i++) {
    TestEntity e = new TestEntity("MyNameIs" + i);
    for (int j = 0; j < 8; j++) {
        SubEntity se = new SubEntity("IamNo" + j + "." + i);
        e.map.put("Key" + i * 100 + j, se);
        em.persist(se);
    }
    em.persist(e);
}

em.getTransaction().commit();

すべてのオブジェクトが作成され、保存されます。マッピング テーブルのキー値だけがすべて null です。私の間違いはどこですか?JPA2 を eclipselink2.4.1 と Derby 10 で使用しています。

4

3 に答える 3

0

JPA 2.0 は、java.util.Map コレクションのサポートと組み合わせて使用​​できる @ElementCollection アノテーションを通じて、プリミティブのコレクションをサポートします。このようなものが動作するはずです:

@Entity
public class Example {
    @Id long id;
    // ....
    @ElementCollection
    @MapKeyColumn(name="name")
    @Column(name="value")
    @CollectionTable(name="example_attributes", joinColumns=@JoinColumn(name="example_id"))
    Map<String, String> attributes = new HashMap<String, String>(); // maps from attribute name to value

}
于 2013-08-17T11:59:48.940 に答える