简体   繁体   中英

Types from Postgresql and types from Play (anorm)

I have a class representing a model:

class Payment(
  val id: Pk[Int] = NotAssigned,
  //.....
)

Here is how it is defined in a db:

CREATE TABLE payment
(
  id serial NOT NULL,
  //.........
)

It throws an exception java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer I got such the exception throughout a project pretty often. I figure it's because I use the wrong data types in Play (anorm) and Postgresql, meaning they don't correspond each other correctly.

So where how do I find out what type of Postresql corresponds to type of anorm? I found only small peaces of the information and they weren't on the official web sites. It seems like the table of such correspondence doesn't even exist, does it?

These are the corresponding types:

1) Int in scala and integer/serial in postgresql are 32 bits and both go up to 2,147,483,647. Postgresql serial is only an auto-incrementing integer.

2) Long in scala and bigint/bigserial in postgresql are 64 bits and both go up to 9,223,372,036,854,775,807. Postgresql bigserial is only an auto-incrementing bigint.

If you want to use the same types, you can use bigserial/Long or serial/Int.

However, for our projects, we ended up using Long in Scala and serial in postgresql and this works fine. This gives us the freedom to simply change the data type in postgresql from serial to bigserial if required in future.

As a side note, we could not see any real advantage for Pk[..] so decided to use Option[Long] instead of Pk[Long] and None instead of NotAssigned. Then you use the generic Option types and will never need to import anorm into your controllers.

Anorm is DB agnostic, it doesn't care about DB vendor specific type, but about JDBC types. You can find JDBC type mappings in Oracle doc: http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html#table1 .

Anorm included in Play 2.3 (latest release) take care of more numeric conversion. You can find details at http://applicius-en.tumblr.com/post/87829484643/anorm-whats-new-play-2-3 .

If you still have conversion issue with latest Anorm, you may add an issue on Play github project.

Best

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