Question

I have a project in Scala which uses Postresql. It involves the type money of Postresql. I did a research and found that I should avoid using money data type in Postgresql and better use NUMERIC.

Also I'm using BigDecimal at client (in Scala). But I can't make it work due to error:

could not find implicit value for parameter extractor: anorm.Column[BigDecimal]
[error]     SqlParser.get[BigDecimal]("due_price") ~

So the questions are:

  1. What datatypes should I use in both Play and Postgresql?
  2. If one of them is BigDecimal, how do I get rid of the error?

P.S. I'm aware about java.util.Currency, but I don't need it, I only need an amount of money which is should be BigDecimal.

Was it helpful?

Solution 2

You can use BigDecimal but the problem here is that BigDecimal type you are getting from Anorm is java.math.BigDecimal while in your case classes you are actually using scala.math.BigDecimal.

To make it work you can either:

1) Define your case classes with java.math.BigDecimal and use this type in your application.

OR

2) Convert between these two in your parser and keep the scala types in your application. This seems to be a better solution. We have used this approach in production. Example:

case class ABC (id: Int, price: BigDecimal, decimalPlaces: Int)

You parser will look like:

val simple = {
  get[Int]("id") ~ get[java.math.BigDecimal]("price") ~ get[Int]("decimalPlaces") map {
  case id ~ price ~ decimalPlaces  => ABC(id, BigDecimal(price), decimalPlaces)
}

And when you need to convert from Scala BigDecimal back to Java BigDecimal (for insert, update etc):

val priceAsJavaBD = priceAsScalaBD.bigDecimal //Returns java.math.BigDecimal

Also, you can have a field (e.g. decimalPlaces) to explicitly define how many decimal places you want when showing this price.

OTHER TIPS

It's quite common to use integer types to store money in cents to avoid rounding errors and penny shaving. You can use Int, Long, BigInt - whatever you prefer.

Your Anorm version doesn't provide Column[BigInt] extractor. Either you can upgrade it to master, or you copy actual Column definition from master (Column.scala) to your project so it's available at compile time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top