简体   繁体   中英

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

I have such model:

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<>();
}

When I compile and run, there are no languages in the database evolution. The database is PostgreSQL 9.3.6 on Heroku.

I tried with List and ArrayList , but this didn't help.

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

It is not yet supported by EBean.

As you know, Play Framework 2.X ships with EBean as its ORM framework. EBean apparently implements a subset of the JPA specification, and seems to be missing some of the JPA2 features.

There is however an open enhancement request on GitHub for the @ElementCollection feature, which also seems to already been implemented, but not released:

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

So, the boring answer is to wait until Play ships with an ORM implementation which supports the annotation. The other option is to patch (if possible) your Play distribution with a JPA provider that supports @ElementCollection .

as handy solution you can use @com.avaje.ebean.annotation.DbJson annotion. It stores any kind of object in a json format as clob type in the database.

@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>(){};
}

The test code:

@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");
        }
    });
}

Stored entity in database:

ID, PRICE,META

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM