|
import slick.driver.PostgresDriver |
|
import com.github.tminglei.slickpg._ |
|
|
|
/** |
|
* This class has the functionality to store |
|
* scala collection into postgreSQL |
|
* |
|
* For Example:- Suppose you have a table with columns having data types such as hstore(sets of key/value pairs) and Arrays |
|
* |
|
* CREATE EXTENSION hstore; |
|
* |
|
* CREATE TABLE student ( |
|
* id int, |
|
* name varchar(254) NOT NULL, |
|
* hobbies text[], |
|
* marks hstore |
|
* ); |
|
* |
|
* Then you can insert scala list in postgres Array and scala map in postgres hstore using this example. |
|
* |
|
* Here we have used Slick-pg [https://github.com/tminglei/slick-pg] (Slick extensions for PostgreSQL), |
|
* which also supports other pg types. |
|
* |
|
*/ |
|
trait MyPostgresDriver extends PostgresDriver |
|
with PgArraySupport |
|
with PgHStoreSupport { |
|
|
|
override lazy val Implicit = new ImplicitsPlus {} |
|
override val simple = new SimpleQLPlus {} |
|
|
|
trait ImplicitsPlus extends Implicits |
|
with ArrayImplicits |
|
with HStoreImplicits |
|
|
|
trait SimpleQLPlus extends SimpleQL |
|
with ImplicitsPlus |
|
} |
|
|
|
object MyPostgresDriver extends MyPostgresDriver |
|
|
|
import MyPostgresDriver.simple._ |
|
|
|
/** |
|
* Student Details |
|
*/ |
|
case class Student( |
|
id: Int, |
|
name: String, |
|
hobbies: List[String], |
|
marks: Map[String, String]) |
|
|
|
/** |
|
* Slick mapping of Student |
|
*/ |
|
class StudentTable(tag: Tag) extends Table[Student](tag, "student") { |
|
def id = column[Int]("id", O.PrimaryKey) |
|
def name = column[String]("name") |
|
def hobbies = column[List[String]]("hobbies", O.Default(Nil)) |
|
def marks = column[Map[String, String]]("marks") |
|
|
|
def * = (id, name, hobbies, marks) <> (Student.tupled, Student.unapply) |
|
} |
|
|
|
/** |
|
* Trait for RDS database connection details |
|
*/ |
|
trait RdsDbDetailsStudent { |
|
lazy val studentQuery: TableQuery[StudentTable] = TableQuery[StudentTable] |
|
val db = Database.forURL("jdbc:postgresql://localhost:5432/student", "root", "root", |
|
null, "org.postgresql.Driver") |
|
} |
|
|
|
object StudentData extends Application with RdsDbDetailsStudent { |
|
|
|
val student = Student(1, "Ayush", List("Study", "Coding"), Map("Scala" -> "90", "Java" -> "80", "PHP" -> "0")) |
|
db.withSession { implicit session => |
|
studentQuery += student |
|
} |
|
|
|
println("storing-----------------") |
|
|
|
} |
What happens if hobbies is Null, even if I used O.Default(Nil) it throws [SlickException: Read NULL value (null) for ResultSet column ]