简体   繁体   中英

Grails Scaffold - Generated MySQL Column Type for JodaTime DateTime field

I am new to Grails and am using Grails 2.1 with a MySQL 5.5 backend to build a sample project to learn.

I installed JodaTime 1.4 Plug-in and then ran grails install-joda-time-templates

However, when I declared a Domain Class field to be of type org.joda.time.DateTime, I got an error when attempting to save a new entry.

In order to isolate the problem, I created a simple Domain Class:

import org.joda.time.DateTime

class Project
{
    String name
    DateTime startDate

    static constraints = {
        name(blank: false, maxSize: 50)
        startDate(validator: {return (it > new DateTime())})
    }
}

The controller just sets scaffold to use the Domain Class.

My DataSource.groovy specifies dbCreate = "create-drop" , as I am letting the tables get created by Grails.

Here is the error I get when I try to save:

Class:com.mysql.jdbc.MysqlDataTruncation
Message:Data truncation: Data too long for column 'start_date' at row 1

When I look at project.start_date column in the MySQL database that Grails created, the type is TINYBLOB.

My thought is that TINYBLOB may not be sufficient to store the data for a JodaTime DateTime field.

Does anyone know how I can make Grails create an appropriate type?

Thank you very much.

In your Config.groovy:

grails.gorm.default.mapping = {
    "user-type" type: PersistentDateTime, class: DateTime
    "user-type" type: PersistentLocalDate, class: LocalDate
}

And your mapping closure:

static mapping = {
    startDate type: PersistentDateTime
}

Take a look at this post for more info, see if it helps.

What I did to make it work (Grails 2.1):

1) add to buildConfig:

compile "org.jadira.usertype:usertype.jodatime:1.9"

2) refresh the dependencies

3) run this command to add the user-type supported:

grails install-joda-time-gorm-mappings

4) finally in the domain class:

import org.jadira.usertype.dateandtime.joda.*

static mapping = {
 column_name type: PersistentDateTime
}

Documentation was found here: persistence

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