user504909
user504909

Reputation: 9549

How to map from List[String] to String in Slick 2.0?

Because the MySQL database not support Arrays, I want to map lists of strings like List("facebook","linkedin","local") to a string like "facebook, linkedin, local".

I want do the bidirectional mapping with slick 2.0, but I do not how to write an instance of TypeMapper.

Can anyone provide an example for me?

Upvotes: 2

Views: 1220

Answers (1)

Martin Ring
Martin Ring

Reputation: 5426

This is documented in the official slick doc here.

You can use MappedColumnType.base[T, U](tmap: (T) ⇒ U, tcomap: (U) ⇒ T) (see scaladoc).

It requires two function arguments tmap and tcomap which do the mapping in both directions.

For your specific use case this could be implemented like such:

implicit val stringListMapper = MappedColumnType.base[List[String],String](
  list => list.mkString(","),
  string => string.split(',').toList
)

Note that this is not safe because if there are commas contained in the Strings, the mapping is not bijective. You would have to make sure there are none or escape them in some way. I leave this to you.

Upvotes: 6

Related Questions