本文整理汇总了Scala中slick.jdbc.JdbcProfile类的典型用法代码示例。如果您正苦于以下问题:Scala JdbcProfile类的具体用法?Scala JdbcProfile怎么用?Scala JdbcProfile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JdbcProfile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: UserSlickDBIOStorageDriver
//设置package包名称以及导入依赖的类
package com.github.j5ik2o.scala.ddd.functional.example.driver.cats
import cats.data.Kleisli
import com.github.j5ik2o.scala.ddd.functional.driver.StorageDriver
import com.github.j5ik2o.scala.ddd.functional.example.domain.{ User, UserId }
import com.github.j5ik2o.scala.ddd.functional.example.driver.slick3.UserDaoComponent
import slick.jdbc.JdbcProfile
import scala.concurrent.ExecutionContext
case class UserSlickDBIOStorageDriver(profile: JdbcProfile, db: JdbcProfile#Backend#Database)
extends UserDaoComponent {
type EvalType[A] = Kleisli[profile.api.DBIO, ExecutionContext, A]
implicit object InternalDriver extends StorageDriver[User, EvalType] {
override type RecordType = UserRecord
protected val dao = UserDao
import profile.api._
override protected def convertToRecord(aggregate: User): UserRecord =
UserRecord(id = aggregate.id.value, name = aggregate.name)
override protected def convertToAggregate(record: Option[UserRecord]): Option[User] =
record.map(e => User(id = UserId(e.id), name = e.name))
override def store(aggregate: User): EvalType[Unit] = Kleisli { implicit ec =>
val record = convertToRecord(aggregate)
val action = (for {
n <- dao.filter(_.id === aggregate.id.value).update(record)
_ <- if (n == 0) dao.forceInsert(record) else DBIO.successful(n)
} yield ()).transactionally
action.asInstanceOf[DBIO[Unit]]
}
override def resolveBy(id: UserId): EvalType[Option[User]] = Kleisli { implicit ec =>
val action =
dao
.filter(_.id === id.value)
.result
.headOption
.map(convertToAggregate)
action.asInstanceOf[DBIO[Option[User]]]
}
override def deleteById(id: UserId): EvalType[Unit] = Kleisli { implicit ec =>
val action = dao.filter(_.id === id.value).delete
action
.flatMap { v =>
if (v == 1)
DBIO.successful(())
else
DBIO.failed(new Exception())
}
.asInstanceOf[DBIO[Unit]]
}
}
}
示例2: DatabaseInitializer
//设置package包名称以及导入依赖的类
package essentials.petstore.database
import slick.basic.DatabaseConfig
import slick.jdbc.meta.MTable
import slick.jdbc.JdbcProfile
import com.typesafe.scalalogging.LazyLogging
import scala.concurrent.duration._
import scala.concurrent.Await
class DatabaseInitializer(val dbConfig: DatabaseConfig[JdbcProfile], petsRepo: PetsRepository, recordsRepo: PetRecordsRepository) extends Db with LazyLogging {
import dbConfig.profile.api._
def initDatabaseTables(): Unit = {
logger.info("Setting up database")
// Get all existing tables
val tables = Await.result(db.run(MTable.getTables), 10 seconds)
val petsTableName = petsRepo.pets.baseTableRow.tableName
if (!tables.exists(existingTable => existingTable.name.name == petsTableName)) {
logger.info(s"Creating table '$petsTableName'")
Await.result(db.run(petsRepo.pets.schema.create), 10 seconds)
} else {
logger.info(s"Table '$petsTableName' already exists")
}
val recordsTableName = recordsRepo.records.baseTableRow.tableName
if (!tables.exists(existingTable => existingTable.name.name == recordsTableName)) {
logger.info(s"Creating table '$recordsTableName'")
Await.result(db.run(recordsRepo.records.schema.create), 10 seconds)
} else {
logger.info(s"Table '$recordsTableName' already exists")
}
logger.info("Finished setting up database")
}
}
示例3: LocalDateTimeColumnType
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.slick
import java.time.LocalDateTime
import cats.~>
import com.dbrsn.datatrain.dsl.meta.ResourceDSL
import com.dbrsn.datatrain.dsl.meta.ResourceDSL.Create
import com.dbrsn.datatrain.model.Resource
import com.dbrsn.datatrain.model.ResourceId
import shapeless.Generic
import shapeless.HNil
import slick.jdbc.JdbcProfile
import slick.lifted.ProvenShape
import slickless._
case class LocalDateTimeColumnType[P <: JdbcProfile](implicit columnType: P#BaseColumnType[LocalDateTime])
trait ResourceJdbcComponent[P <: JdbcProfile] {
val localDateTimeColumnType: LocalDateTimeColumnType[P]
val profile: P
import profile.api._
import localDateTimeColumnType._
type ResourceJdbcDSL[A] = ResourceDSL[A]
def resourceTableName: String = "dt_resource"
class ResourceTable(tag: Tag) extends Table[Resource](tag, resourceTableName) {
def id: Rep[ResourceId] = column[ResourceId]("id", O.PrimaryKey)
def createdAt: Rep[LocalDateTime] = column[LocalDateTime]("created_at")
override def * : ProvenShape[Resource] = (id :: createdAt :: HNil).mappedWith(Generic[Resource])
}
lazy val resourceTableQuery: TableQuery[ResourceTable] = TableQuery[ResourceTable]
object ResourceInterpreter extends (ResourceJdbcDSL ~> DBIO) {
override def apply[A](fa: ResourceJdbcDSL[A]): DBIO[A] = fa match {
case Create(resource) => (resourceTableQuery returning resourceTableQuery.map(_.id) into ((v, _) => v)) += resource
}
}
}
示例4: contentTableName
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.slick
import java.time.LocalDateTime
import cats.~>
import com.dbrsn.datatrain.dsl.meta.ContentDSL
import com.dbrsn.datatrain.dsl.meta.ContentDSL.Create
import com.dbrsn.datatrain.model.Content
import com.dbrsn.datatrain.model.ContentId
import com.dbrsn.datatrain.model.ContentType
import com.dbrsn.datatrain.model.Resource
import com.dbrsn.datatrain.model.ResourceId
import shapeless.Generic
import shapeless.HNil
import slick.jdbc.JdbcProfile
import slick.lifted.ForeignKeyQuery
import slick.lifted.ProvenShape
import slickless._
trait ContentJdbcComponent[P <: JdbcProfile] {
self: ResourceJdbcComponent[P] =>
val profile: P
import profile.api._
import localDateTimeColumnType._
type ContentJdbcDSL[A] = ContentDSL[A]
def contentTableName: String = "dt_content"
class ContentTable(tag: Tag) extends Table[Content](tag, contentTableName) {
def id: Rep[ContentId] = column[ContentId]("id", O.PrimaryKey)
def createdAt: Rep[LocalDateTime] = column[LocalDateTime]("created_at")
def resourceId: Rep[ResourceId] = column[ResourceId]("resource_id")
def contentType: Rep[Option[ContentType]] = column[Option[ContentType]]("content_type")
def contentName: Rep[String] = column[String]("content_name")
override def * : ProvenShape[Content] = (id :: createdAt :: resourceId :: contentType :: contentName :: HNil).mappedWith(Generic[Content])
def resourceIdFk: ForeignKeyQuery[ResourceTable, Resource] = foreignKey(s"fk_${contentTableName}_resource_id", resourceId, resourceTableQuery)(_.id)
}
lazy val contentTableQuery: TableQuery[ContentTable] = TableQuery[ContentTable]
object ContentInterpreter extends (ContentJdbcDSL ~> DBIO) {
override def apply[A](fa: ContentJdbcDSL[A]): DBIO[A] = fa match {
case Create(content) => (contentTableQuery returning contentTableQuery.map(_.id) into ((v, _) => v)) += content
}
}
}
示例5: contentMetadataTableName
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.slick
import cats.~>
import com.dbrsn.datatrain.dsl.meta.ContentMetadataDSL
import com.dbrsn.datatrain.model.Content
import com.dbrsn.datatrain.model.ContentId
import com.dbrsn.datatrain.model.Metadata
import com.dbrsn.datatrain.model.MetadataKey
import com.dbrsn.datatrain.model.MetadataValue
import shapeless.Generic
import shapeless.HNil
import slick.jdbc.JdbcProfile
import slick.lifted.ForeignKeyQuery
import slick.lifted.ProvenShape
import slickless._
trait ContentMetadataJdbcComponent[P <: JdbcProfile] {
self: ContentJdbcComponent[P] =>
val profile: P
val metadataKeyColumnType: MetadataKeyColumnType[P]
import ContentMetadataDSL._
import profile.api._
import metadataKeyColumnType._
type ContentMetadataJdbcDSL[A] = ContentMetadataDSL[A]
def contentMetadataTableName: String = "dt_content_metadata"
class ContentMetadataTable(tag: Tag) extends Table[Metadata[Content]](tag, contentMetadataTableName) {
def id: Rep[ContentId] = column[ContentId]("id", O.PrimaryKey)
def key: Rep[MetadataKey] = column[MetadataKey]("key")
def value: Rep[MetadataValue] = column[MetadataValue]("value")
override def * : ProvenShape[Metadata[Content]] = (id :: key :: value :: HNil).mappedWith(Generic[Metadata[Content]])
def idFk: ForeignKeyQuery[ContentTable, Content] = foreignKey(s"fk_dt_${contentMetadataTableName}_id", id, contentTableQuery)(_.id)
}
lazy val contentMetadataTableQuery: TableQuery[ContentMetadataTable] = TableQuery[ContentMetadataTable]
object ContentMetadataInterpreter extends (ContentMetadataJdbcDSL ~> DBIO) {
override def apply[A](fa: ContentMetadataJdbcDSL[A]): DBIO[A] = fa match {
case Create(metadata) => (contentMetadataTableQuery returning contentMetadataTableQuery.map(_.id) into ((v, _) => v)) += metadata
}
}
}
示例6: MetadataKeyColumnType
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.slick
import cats.~>
import com.dbrsn.datatrain.dsl.meta.ResourceMetadataDSL
import com.dbrsn.datatrain.model.Metadata
import com.dbrsn.datatrain.model.MetadataKey
import com.dbrsn.datatrain.model.MetadataValue
import com.dbrsn.datatrain.model.Resource
import com.dbrsn.datatrain.model.ResourceId
import shapeless.Generic
import shapeless.HNil
import slick.jdbc.JdbcProfile
import slick.lifted.ForeignKeyQuery
import slick.lifted.ProvenShape
import slickless._
case class MetadataKeyColumnType[P <: JdbcProfile](implicit columnType: P#BaseColumnType[MetadataKey])
trait ResourceMetadataJdbcComponent[P <: JdbcProfile] {
self: ResourceJdbcComponent[P] =>
val profile: P
val metadataKeyColumnType: MetadataKeyColumnType[P]
import ResourceMetadataDSL._
import profile.api._
import metadataKeyColumnType._
type ResourceMetadataJdbcDSL[A] = ResourceMetadataDSL[A]
def resourceMetadataTableName: String = "dt_resource_metadata"
class ResourceMetadataTable(tag: Tag) extends Table[Metadata[Resource]](tag, resourceMetadataTableName) {
def id: Rep[ResourceId] = column[ResourceId]("id", O.PrimaryKey)
def key: Rep[MetadataKey] = column[MetadataKey]("key")
def value: Rep[MetadataValue] = column[MetadataValue]("value")
override def * : ProvenShape[Metadata[Resource]] = (id :: key :: value :: HNil).mappedWith(Generic[Metadata[Resource]])
def idFk: ForeignKeyQuery[ResourceTable, Resource] = foreignKey(s"fk_dt_${resourceMetadataTableName}_id", id, resourceTableQuery)(_.id)
}
lazy val resourceMetadataTableQuery: TableQuery[ResourceMetadataTable] = TableQuery[ResourceMetadataTable]
object ResourceMetadataInterpreter extends (ResourceMetadataJdbcDSL ~> DBIO) {
override def apply[A](fa: ResourceMetadataJdbcDSL[A]): DBIO[A] = fa match {
case Create(metadata) => (resourceMetadataTableQuery returning resourceMetadataTableQuery.map(_.id) into ((v, _) => v)) += metadata
}
}
}
示例7: Boot
//设置package包名称以及导入依赖的类
package boot
import controllers.DevicesController
import play.api.ApplicationLoader.Context
import play.api.db.evolutions.EvolutionsComponents
import play.api.db.slick.evolutions.SlickEvolutionsComponents
import play.api.db.slick.{DbName, DefaultSlickApi}
import play.api.{Application, ApplicationLoader, BuiltInComponentsFromContext}
import play.filters.HttpFiltersComponents
import router.Routes
import services.DataSource
import slick.basic.DatabaseConfig
import services.DataSourceJdbc
import slick.jdbc.JdbcProfile
class Boot extends ApplicationLoader {
def load(context: Context): Application = {
val components = new BootComponents(context)
components.applicationEvolutions // Run the evolutions
components.application
}
}
class BootComponents(context: Context)
extends BuiltInComponentsFromContext(context)
with HttpFiltersComponents
with controllers.AssetsComponents
with EvolutionsComponents
with SlickEvolutionsComponents {
override def api: DefaultSlickApi = new DefaultSlickApi(environment, configuration, applicationLifecycle)
private[this] val defaultDBName: DbName = DbName("devices")
private[this] val dbConfig: DatabaseConfig[JdbcProfile] = slickApi.dbConfig[JdbcProfile](defaultDBName)
// TODO put this into config
private[this] val dbPoolSize = 10
private[this] lazy val dataSource: DataSource = new DataSourceJdbc(dbConfig, dbPoolSize)
private[this] lazy val devicesController: DevicesController = new DevicesController(controllerComponents, dataSource)
override lazy val router: Routes = new Routes(httpErrorHandler, devicesController, assets)
}
示例8: DeleteAction
//设置package包名称以及导入依赖的类
package eventsource.slick
import akka.actor.Scheduler
import eventsource.models.{Action, Entity, Event}
import play.api.Logger
import slick.dbio.DBIOAction
import slick.jdbc.JdbcProfile
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
class DeleteAction[Key, ETT, E <: Entity[Key]](
adapter: SlickAdapter[Key, ETT, E],
val driver: JdbcProfile,
db: JdbcProfile#Backend#Database,
override val logger: Logger
)(implicit ec: ExecutionContext, s: Scheduler)
extends Action[Key, ETT, Option[E]]
with Retrying {
import driver.api._
def errorHandler: PartialFunction[(Throwable, Int), Future[Option[E]]] =
PartialFunction.empty
override def processEvent(event: Event[Key, ETT]): Future[Option[E]] =
retry(10, 100.millis, errorHandler) {
db.run(adapter
.findByEventWithLock(event)
.flatMap {
case Some(entity) if event.version.isNewerThan(entity.lastModifiedVersion) =>
logger.debug(
s"Got newer lastModifiedVersion ${event.version} > ${entity.lastModifiedVersion} for ${event.key}. Deleting ...")
adapter.deleteByEvent(event).map(_ => Some(entity))
case Some(entity) =>
logger.debug(
s"Got older lastModifiedVersion ${event.version} <= ${entity.lastModifiedVersion} for ${event.key}. Ignoreing ...")
DBIOAction.successful(None)
case None =>
logger.debug(s"Entity ${event.key} does not exists, ignore delete")
DBIOAction.successful(None)
}
.transactionally)
}
}
示例9: CreateAction
//设置package包名称以及导入依赖的类
package eventsource.slick
import akka.actor.Scheduler
import eventsource.models.{Action, Entity, Event}
import play.api.Logger
import slick.dbio.DBIOAction
import slick.jdbc.JdbcProfile
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
abstract class CreateAction[Key, ETT, E <: Entity[Key]](
adapter: SlickAdapter[Key, ETT, E],
val driver: JdbcProfile,
db: JdbcProfile#Backend#Database,
override val logger: Logger
)(implicit ec: ExecutionContext, s: Scheduler)
extends Action[Key, ETT, Option[E]]
with Retrying {
protected def entityFromEvent(event: Event[Key, ETT]): E
import driver.api._
def errorHandler: PartialFunction[(Throwable, Int), Future[Option[E]]] =
PartialFunction.empty
override def processEvent(event: Event[Key, ETT]): Future[Option[E]] =
retry(10, 100.millis, errorHandler) {
db.run(adapter
.findByEventWithLock(event)
.flatMap {
case Some(entity) if entity.createdVersion == event.version =>
logger.debug(s"createdVersion=${event.version} already exists. Nothing to do...")
DBIOAction.successful(Some(entity))
case Some(entity) if entity.createdVersion.isNewerThan(event.version) =>
logger.debug(
s"Got older createdVersion ${event.version} < ${entity.createdVersion} for ${event.key}. Updating ...")
val olderEntity = entityFromEvent(event)
logger.debug(s"Update with $olderEntity")
adapter.update(olderEntity).map(_ => Some(olderEntity))
case Some(entity) =>
logger.debug(
s"Got newer createdVersion ${event.version} >= ${entity.createdVersion} for ${event.key}. Ignoring ...")
DBIOAction.successful(None)
case None =>
val entity = entityFromEvent(event)
logger.debug(s"Insert new $entity")
adapter.insert(entity).map(_ => Some(entity))
}
.transactionally)
}
}
示例10: SimpleUpdateAction
//设置package包名称以及导入依赖的类
package eventsource.slick
import akka.actor.Scheduler
import eventsource.models.{Action, Entity, Event}
import play.api.Logger
import slick.dbio.DBIOAction
import slick.jdbc.JdbcProfile
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
abstract class SimpleUpdateAction[Key, ETT, E <: Entity[Key]](
adapter: SlickAdapter[Key, ETT, E],
val driver: JdbcProfile,
db: JdbcProfile#Backend#Database,
override val logger: Logger
)(implicit ec: ExecutionContext, s: Scheduler)
extends Action[Key, ETT, Option[E]]
with Retrying {
import driver.api._
def updateEntity(entity: E, event: Event[Key, ETT]): E
def errorHandler: PartialFunction[(Throwable, Int), Future[Option[E]]] =
PartialFunction.empty
override def processEvent(event: Event[Key, ETT]): Future[Option[E]] =
retry(10, 100.millis, errorHandler) {
db.run(adapter
.findByEventWithLock(event)
.flatMap {
case Some(entity) if event.version == entity.lastModifiedVersion =>
logger.debug(s"lastModifiedVersion=${event.version} already exists. Nothing to do")
DBIOAction.successful(Some(entity))
case Some(entity) if event.version.isNewerThan(entity.lastModifiedVersion) =>
logger.debug(
s"Got newer lastModifiedVersion ${event.version} > ${entity.lastModifiedVersion} for ${event.key}. Updating ...")
val newerEntity = updateEntity(entity, event)
logger.debug(s"Update with $newerEntity")
adapter.update(newerEntity).map(_ => Some(newerEntity))
case Some(entity) =>
logger.debug(
s"Got older lastModifiedVersion ${event.version} <= ${entity.lastModifiedVersion} for ${event.key}. Ignoreing ...")
DBIOAction.successful(None)
case None =>
logger.debug(s"Entity ${event.key} does not exists, ignore update")
DBIOAction.successful(None)
}
.transactionally)
}
}
示例11: ChangeAction
//设置package包名称以及导入依赖的类
package eventsource.slick
import akka.actor.Scheduler
import eventsource.models.{Action, Event, VersionedEntity}
import play.api.Logger
import slick.jdbc.JdbcProfile
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
abstract class ChangeAction[Key, ETT, E <: VersionedEntity](
val driver: JdbcProfile,
db: JdbcProfile#Backend#Database,
override val logger: Logger)(implicit ec: ExecutionContext, s: Scheduler)
extends Action[Key, ETT, Option[E]]
with Retrying {
import driver.api._
def findByEventWithLock(event: Event[Key, ETT]): DBIOAction[Option[E], NoStream, Effect.Read]
def applyChange(currentEntity: Option[E],
event: Event[Key, ETT]): DBIOAction[Option[E], NoStream, Effect.All]
def errorHandler: PartialFunction[(Throwable, Int), Future[Option[E]]] =
PartialFunction.empty
override def processEvent(event: Event[Key, ETT]): Future[Option[E]] = {
retry(10, 100.millis, errorHandler) {
db.run(findByEventWithLock(event).flatMap {
case Some(entity) if event.version == entity.lastModifiedVersion =>
logger.debug(s"lastModifiedVersion=${event.version} already exists. Nothing to do")
DBIO.successful(Some(entity))
case Some(entity) if event.version.isNewerThan(entity.lastModifiedVersion) =>
logger.debug(
s"Got newer lastModifiedVersion ${event.version} > ${entity.lastModifiedVersion} for ${event.key}. Updating ...")
applyChange(Some(entity), event)
case Some(entity) =>
logger.debug(
s"Got older lastModifiedVersion ${event.version} <= ${entity.lastModifiedVersion} for ${event.key}. Ignoreing ...")
DBIO.successful(None)
case None =>
logger.debug(s"Entity ${event.key} does not exists, ignore update")
applyChange(None, event)
}.transactionally)
}
}
}
示例12: UpdateAction
//设置package包名称以及导入依赖的类
package eventsource.slick
import akka.actor.Scheduler
import eventsource.models.{Action, Entity, Event}
import play.api.Logger
import slick.jdbc.JdbcProfile
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
abstract class UpdateAction[Key, ETT, E <: Entity[Key]](
adapter: SlickAdapter[Key, ETT, E],
val driver: JdbcProfile,
db: JdbcProfile#Backend#Database,
override val logger: Logger
)(implicit ec: ExecutionContext, s: Scheduler)
extends Action[Key, ETT, Option[E]]
with Retrying {
import driver.api._
def errorHandler: PartialFunction[(Throwable, Int), Future[Option[E]]] =
PartialFunction.empty
def applyUpdate(currentEntity: E,
event: Event[Key, ETT]): DBIOAction[Option[E], NoStream, Effect.All]
override def processEvent(event: Event[Key, ETT]): Future[Option[E]] =
retry(10, 100.millis, errorHandler) {
db.run(adapter
.findByEventWithLock(event)
.flatMap {
case Some(entity) if event.version == entity.lastModifiedVersion =>
logger.debug(s"lastModifiedVersion=${event.version} already exists. Nothing to do")
DBIO.successful(Some(entity))
case Some(entity) if event.version.isNewerThan(entity.lastModifiedVersion) =>
logger.debug(
s"Got newer lastModifiedVersion ${event.version} > ${entity.lastModifiedVersion} for ${event.key}. Updating ...")
applyUpdate(entity, event)
case Some(entity) =>
logger.debug(
s"Got older lastModifiedVersion ${event.version} <= ${entity.lastModifiedVersion} for ${event.key}. Ignoreing ...")
DBIO.successful(None)
case None =>
logger.debug(s"Entity ${event.key} does not exists, ignore update")
DBIO.successful(None)
}
.transactionally)
}
}
示例13: run
//设置package包名称以及导入依赖的类
package tutor.repo
import slick.dbio.{DBIOAction, NoStream}
import slick.jdbc.{H2Profile, JdbcProfile, OracleProfile}
import scala.concurrent.Future
trait DBConfigProvider {
val jdbcProfile: JdbcProfile
def run[T](action: DBIOAction[T, NoStream, Nothing]):Future[T]
}
trait OracleDB extends DBConfigProvider {
val jdbcProfile: JdbcProfile = OracleProfile
}
trait H2DB extends DBConfigProvider {
val jdbcProfile: JdbcProfile = H2Profile
def run[T](action: DBIOAction[T, NoStream, Nothing]):Future[T] = {
import jdbcProfile.api._
val db = Database.forConfig("h2mem1")
try {
db.run(action)
}finally db.close()
}
}
示例14: currentJdbcProfile
//设置package包名称以及导入依赖的类
package db
import slick.jdbc.{JdbcProfile, PostgresProfile}
import currentJdbcProfile.profile
private[db] sealed trait DatabaseConfigProvider[P <: JdbcProfile] {
val db: P#Backend#Database
}
private[db] trait JdbcDatabaseConfigProvider extends DatabaseConfigProvider[profile.type] {
import currentJdbcProfile.api.Database
override lazy val db = Database.forConfig("database")
}
private[db] object currentJdbcProfile {
val profile = PostgresProfile
lazy val api = profile.api
}
示例15: instantToTimeStamp
//设置package包名称以及导入依赖的类
package de.twentyone.slick.mappings
import java.sql.Timestamp
import java.time.Instant
import slick.jdbc.JdbcProfile
import slick.jdbc.{GetResult, PositionedParameters, PositionedResult, SetParameter}
trait JavaInstantMappings {
protected val driver: JdbcProfile
import driver.api._
// scalastyle:off
private def instantToTimeStamp(instant: Instant) =
if (instant == null) null else new Timestamp(instant.toEpochMilli)
private def timeStampToInstant(timestamp: Timestamp) =
if (timestamp == null) null else timestamp.toInstant
// scalastyle:on
protected implicit val instantMappedColumnType: JdbcProfile#BaseColumnType[Instant] =
MappedColumnType.base[Instant, Timestamp](
d => instantToTimeStamp(d),
d => timeStampToInstant(d)
)
protected implicit val instantGetResult: GetResult[Instant] = new GetResult[Instant] {
override def apply(positionedResult: PositionedResult): Instant =
timeStampToInstant(positionedResult.nextTimestamp())
}
protected implicit val instantOptionGetResult: GetResult[Option[Instant]] =
new GetResult[Option[Instant]] {
override def apply(positionedResult: PositionedResult): Option[Instant] =
positionedResult.nextTimestampOption().map(timestamp => timeStampToInstant(timestamp))
}
protected implicit val instantSetParameter: SetParameter[Instant] = new SetParameter[Instant] {
override def apply(instant: Instant, positionedParameter: PositionedParameters): Unit =
positionedParameter.setTimestamp(instantToTimeStamp(instant))
}
protected implicit val instantOptionSetParameter: SetParameter[Option[Instant]] =
new SetParameter[Option[Instant]] {
override def apply(instantOption: Option[Instant],
positionedParameter: PositionedParameters): Unit =
positionedParameter.setTimestampOption(
instantOption.map(instant => instantToTimeStamp(instant)))
}
}