Playframework + Slick + PostgreSQL + GraphQL
前段时间钻研公司大佬写的代码,看到了 graphql 的部分,就把这一部分做了一个小项目,实现的功能是给服务器发送一个graphql的post请求,服务器能读取数据库,并返回相应的json。使用的服务器框架是用scala写的play,数据库用postgresql,以及play-slick的插件
先附上git:https://github.com/MattieuWang/graphQL
数据结构
对于 user 来说,一个user可以有多条experience,但只有一个现在所在的enterprise(或没有),查找experience通过exp.user_id,而查找enterprise就用 user.enterprise_id
付一段简单的sql,这里我选择手动填入数据,利用 slick 的 evolution,只需要把sql放在 conf/evolutions/default中
# --- !Ups
CREATE TABLE users (
id varchar(36) primary key,
name text NOT NULL,
age integer NOT NULL,
sex text NOT NULL,
enterprise_id varchar(36)
);
CREATE TABLE exps (
id varchar(36) primary key,
name text NOT NULL,
location text NOT NULL,
start_at date NOT NULL,
end_at date,
user_id
);
CREATE TABLE enterprises (
id varchar(36) primary key,
name text NOT NULL,
location text NOT NULL
);
# --- !Downs
DROP TABLE users;
DROP TABLE exps;
DROP TABLE enterprises;
项目框架
在项目中新建了3个小的 sub modules,具体过程可以看这篇文章:https://blog.csdn.net/qq_19206521/article/details/107825437
添加配置
主项目的 build.sbt
"org.sangria-graphql" %% "sangria-play-json" % "2.0.1",
"org.sangria-graphql" %% "sangria" % "2.0.0",
"org.sangria-graphql" %% "sangria-slowlog" % "2.0.0-M1",
添加 sangria 的依赖,用于实现graphql
"com.typesafe.play" %% "play-slick" % "5.0.0",
"com.typesafe.play" %% "play-slick-evolutions" % "5.0.0",
"org.postgresql" % "postgresql" % "42.2.16",
"com.typesafe.play" %% "play-slick-evolutions" % "5.0.0"
添加数据库依赖和slick
添加数据库配置:
slick.dbs.default {
profile="slick.jdbc.PostgresProfile$"
db.driver=org.postgresql.Driver
db.url="jdbc:postgresql://localhost/TestBase"
db.user=app
db.password="app"
}
完善modules,使用slick访问数据库
case class User(id: String, name: String, age: Int, sex: String, enterprise_id: Option[String] = None)
class UserDao(dbConfigProvider: DatabaseConfigProvider) {
private val dbConfig = dbConfigProvider.get[JdbcProfile]
import dbConfig._
import profile.api._
private class UserTable(tag: Tag) extends Table[User](tag, "users") {
val id = column[String]("id", O.PrimaryKey)
val name = column[String]("name")
val age = column[Int]("age")
val sex