简体   繁体   中英

How to use java.util.Date as a map key in Groovy

here's my problem: I am trying to fill the following map:

class Driver extends User{


final UserRole role = UserRole.DRIVER
Map<Date, Route> routes = [:]

static hasMany = [
    assignedJobs:Job
]

static mappedBy = [
    assignedJobs:'assignedUser'
]
static constraints = {
}
}

Here's the code filling it:

def private addStationToRoute(driver, station){
    def route = driver.routes.get(station?.estimatedArrival.clearTime())
    if(route == null)
        route = new Route()
//      route.stations.add(station)
//      route.stations.sort({it.position})
    def key = station?.estimatedArrival.clearTime()
    driver.routes.put(key, route)
}

which leads me to a ClassCastException:

java.util.Date cannot be cast to java.lang.String. Stacktrace follows:
Message: java.util.Date cannot be cast to java.lang.String
Line | Method
->>   97 | $tt__save in elektrova.JobController
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|    200 | doFilter  in grails.plugin.cache.web.filter.PageFragmentCachingFilter
|     63 | doFilter  in grails.plugin.cache.web.filter.AbstractFilter
|   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    744 | run       in java.lang.Thread

after some research I found that putting the key in paranthesis should do the trick (sources: http://groovy.codehaus.org/Collections The Maps section http://mrhaki.blogspot.de/2009/11/groovy-goodness-complex-keys-in-maps.html

which lead me to trying this:

def private addStationToRoute(driver, station){
    def route = driver.routes.get(station?.estimatedArrival.clearTime())
    if(route == null)
        route = new Route()
//      route.stations.add(station)
//      route.stations.sort({it.position})
    def key = station?.estimatedArrival.clearTime()
    driver.routes[(key)] = (route)
}

Any suggestions what to do? (BTW, I tried changing it to key.toString(), which makes the exception disappear) Thanks in advance!

EDIT: The error occurs while saving:

@Transactional
def save(Job jobInstance) {
    if (jobInstance == null) {
        notFound()
        logNotFound("save", Job.class)

        return
    }

    setSaveConditions(jobInstance)
    setUpdateConditions(jobInstance)
    jobService.createStationsForJob(jobInstance)
    if(jobInstance.assignedUser)
        jobService.addStationsToRoute(jobInstance)
    jobInstance.validate()
    if (jobInstance.hasErrors()) {
        respond jobInstance.errors, view:'create'
        return
    }
    println 'routes: ' + jobInstance.assignedUser.routes.toString()
    jobInstance.save flush:true
    println 'routes: ' + jobInstance.assignedUser.routes.toString()
    logSaving(jobInstance)
    request.withFormat {
        form {
            flash.message = message(code: 'default.created.message', args: [
                message(code: 'job.label', default: 'Job'),
                jobInstance.encodeAsHTML()
            ])
            redirect jobInstance
        }
        '*' { respond jobInstance, [status: CREATED] }
    }
}

grails tells me error line is the one containing jobInstance.save flush:true. The jobInstance has a driver attribute, which contains the Map. When I use the String representation the same error occurs for the route object:

Message: elektrova.Route cannot be cast to java.lang.String
Line | Method
->>   97 | $tt__save in elektrova.JobController$$EOZiJFlq
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|    200 | doFilter  in grails.plugin.cache.web.filter.PageFragmentCachingFilter
|     63 | doFilter  in grails.plugin.cache.web.filter.AbstractFilter
|   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^    744 | run       in java.lang.Thread

and when I use the String representation of the route the saving is done. But why in the world would the Map expect two Strings?

EDIT2:

The Domain classes:

class Job implements Serializable{


JobStatus status = JobStatus.ACTIVE
Station startStation
Station endStation


String containerNumber
String loadingIndicator = false
String containerISO
String oversizeIndicator = false
Double grossWeight = 0
Boolean nonOperatingReeferIndicator = false
String iReference
String consigneeReference
String quayAccountNumber
String carrierCode
String bookingReference
String releaseNumber
String transportMeansIdentification
Boolean trainTransportIndicator = false
Boolean dangerousGoodsIndicator = false
String gegisReference
Boolean customsIndicator = false
String registrationNumber
String registrationPositon


Date creationTimeStamp
User updateUser
Date updateTimeStamp

boolean deleted = false

static belongsTo = [
    hauler:Hauler,
    assignedUser:Driver,
    creationUser:Disponent
]




static constraints = {
    hauler(blank:false, nullable:false)
    status(blank:false, nullable:false)
    endStation(nullable:true)
    startStation(nullable:true)     

    assignedUser(nullable:true)
    containerNumber(nullable:true)
    containerISO(nullable:true)
    iReference(nullable:true)
    consigneeReference(nullable:true)
    quayAccountNumber(nullable:true)
    carrierCode(nullable:true)
    bookingReference(nullable:true)
    releaseNumber(nullable:true)
    transportMeansIdentification(nullable:true)
    gegisReference(nullable:true)
    registrationNumber(nullable:true)
    registrationPositon(nullable:true)


    updateUser(nullable:true)
    updateTimeStamp(nullable:true)

    creationTimeStamp(blank:false, nullable:false)
    creationUser(blank:false, nullable:false)
}



def cancel(){
    this.status = JobStatus.CANCELLED
}

def finish(){
    this.status = JobStatus.DONE
}

//  @Override
//  def encodeAsHTML(){
 ////       destination.locationName + " (" + containerNumber + ") " + plannedArrivalTime.toString()
//  }
}

class Route {

//  List<Station> stations = []
//  
//  static belongsTo = [
//      hauler:Hauler,
//      driver:Driver
//  ]

//  static hasMany = [
//      jobs:Job
//  ]
}

您可以在声明地图时使用日期作为地图键,但是您的问题实际上是关于解决将其存储在数据库中的问题。

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