简体   繁体   中英

Problems with using java.sql.date in playframework

I have a table in my database that has an attribute "datecomplete" as type DATE. Something like this:

CREATE TABLE goal (
gid integer NOT NULL AUTO_INCREMENT,
datecomplete date DEFAULT NULL);

The date is given by the user through a helper form:

@inputDate(goalForm("datecomplete"),'_label -> "Due Date", '_showConstraints -> false)

I treat the inputDate as a string. Upon receiving the input from the user, it calls Goal.create(datecomplete) which does the following

 def create(datecomplete:String ) {
 DB.withConnection { implicit c =>
 SQL("INSERT INTO goal (datecomplete) VALUES ({datecomplete})"
    ).on(
    'datecomplete -> datecomplete
    ).executeUpdate()
}
}

Then when I try to print out my goals using some simple SQL code

 def all(): List[Goal] = DB.withConnection {
 implicit c => SQL("SELECT * FROM goal").as(goal *)}

It gives me this error

[RuntimeException: TypeDoesNotMatch(Cannot convert 2014-05-18:class java.sql.Date to String for column ColumnName(GOAL.DATECREATE,Some(DATECREATE)))]

I think the problem is that my Goal object has datecomplete as a String, but in the database it's a Date. So it cannot make a List[Goal] out of the resulting query. However, I don't know how to fix it.

I think you may not be using the right type in your Goal case class. Also by the looks of the create function, rather than using a String here, I'd advise to use a Date or better yet a org.joda.time.DateTime (which should be there by default in Play).

If I am not mistaken, Anorm should have the necessary converters in order to handle a DateTime input, also in the form.

For each methods a connection is not performance-wise. Notice that within a Connection you have a Session and within a Session there is a Transaction. To close and reopen these over and over is very "expensive".

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