简体   繁体   中英

Cannot persist hashmap with JPA

I am struggling trying to persist a map to SQLserver with the code below and keep getting the following error:

* Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'OnlineReport_availabilities'. *

I use Play framework JPA for this have have managed to persist Maps before with similar code. I tried manually creating the table in the db to see if there was any issue with the name but all seems ok.

I am doing something non conventional or incorrect here?


   @Entity
    public class OnlineReport extends Model {

    @Temporal(TemporalType.DATE)
    public Date date;

    @ElementCollection
    public Map<Date, Double> availabilities;

    public OnlineReport(){
        this.date = new Date();
        this.availabilities = new HashMap<Date, Double>();         
    }

    public void addAvailability(double availability){
        TreeSet<Date> set = new TreeSet(availabilities.entrySet());

        Date lastEntry = null;
        if(!set.isEmpty())
            lastEntry = set.last();

        Date now = new Date();
        if(lastEntry != null){
            //Add availibility every 10mn
            if(DateUtil.getMinutesBetween(lastEntry, now) >= 10){
                availabilities.put(now, availability);
                save();
            }
        } else {
            availabilities.put(now, availability);
            save();
        }
    }
}


Update.

Running JPA in debugSQL I have noticed the following errors:

ERROR ~ Unsuccessful: create table OnlineReport_availabilities (OnlineReport_id numeric(19,0) not null, availabilities double precision null, availabilities_KEY datetime null, primary key (OnlineReport_id, availabilities_KEY))

ERROR ~ Cannot define PRIMARY KEY constraint on nullable column in table 'OnlineReport_availabilities'.

I am under the impression I am missing some annotation definition of 'availabilities'.

Likely you do not have such a table or it is not accessible via connection in use. Are object (tables, fields etc) names case sensitive in db?

So, after your update we know why you do not have table. Looks like it fails to create not null -constraint to the column that is part of the key. Dialect fails for SQL Server, because your mapping is minimal, but correct. You can try to force it by adding following annotation:

@MapKeyColumn(columnDefinition = "datetime not null")

Of course having datetime as part of the key will produce problems if it is possible that there is more than one entry per millisecond.

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