如何在 Play Framework 2.3.8 中保留字符串集合?

How to persist a collection of Strings in Play Framework 2.3.8?

我有这样的模型:

import play.db.ebean.Model;
import javax.persistence.*;
import java.util.*;

@Entity
public class Translation extends Model {

    @Id
    public Long id;

    @ElementCollection
    public Set<String> languages = new HashSet<>();
}

我编译和运行的时候,数据库演进没有languages。数据库是 Heroku 上的 PostgreSQL 9.3.6。

我试过 ListArrayList,但这没有帮助。

如何在 Play Framework 2.3.8 中持久化字符串集合?

EBean 尚不支持。

如您所知,Play Framework 2.X 附带 EBean 作为其 ORM 框架。 EBean 显然实现了 JPA 规范的一个子集,并且似乎缺少一些 JPA2 功能。

但是 GitHub 上有一个关于 @ElementCollection 功能的公开增强请求,它似乎也已经实现,但尚未发布:

https://github.com/ebean-orm/avaje-ebeanorm/issues/115

因此,无聊的答案是等到 Play 附带支持注释的 ORM 实现。另一种选择是使用支持 @ElementCollection.

的 JPA 提供程序修补(如果可能)您的 Play 发行版

作为方便的解决方案,您可以使用 @com.avaje.ebean.annotation.DbJson 注释。它以 json 格式将任何类型的对象存储为数据库中的 clob 类型。

@Entity
public class Offer extends Model {
    @Id
    public Long id;
    public Double price;

    @DbJson
    public Map<String, String> meta = new HashMap<>();

    public static Find<Long,Offer> find = new Find<Long,Offer>(){};
}

测试代码:

@Test
public void createAndFindOffer() {
    running(fakeApplication(), new Runnable() {
        @Override
        public void run() {
            Offer offer = new Offer();
            Map<String, String> map = new HashMap<>();
            map.put("key", "value");
            offer.meta = map;
            offer.save();

            Offer found = Offer.find.byId(offer.id);
            assertNotNull(found);
            assertEquals(found.meta.get("key"), "value");
        }
    });
}

数据库中存储的实体:

ID、价格、META

1,空,{"key":"value"}