避免 MySQL 在 Slick 3.x 中显式声明

Avoiding MySQL explicit declaration in Slick 3.x

在 Slick 3.x 中,我使用下面的代码来包装数据库是 MySQL 的事实。这允许我在整个应用程序中只声明一次 MySQLDriver

package util

import slick.driver.MySQLDriver

trait DbDriver extends MySQLDriver {
  val dbApi = api
}

object DbDriver extends DbDriver

然后在使用 Slick 的 classes 中,我按如下方式导入(而不是特定于数据库的驱动程序):

import util.DbDriver.api._

现在,我需要捕获重复的插入异常。为此,我使用 MySql class:

case Success(res) => 
  // insert succeeded, no duplicate exception
case Failure(e: MySQLIntegrityConstraintViolationException) =>
  // duplicate exception
case Failure(e) => 
  // other failures

但这迫使我在每个 class com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException 中导入。 有没有办法将它包含在通用特征声明中 DbDriver

这是我的尝试(有效):

正在声明:

class Duplicate extends        
  com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException

并赶上:

case Failure(e: Duplicate) => // print something

您可以定义类型别名:

trait DbDriver extends MySQLDriver {
  val dbApi = api
}

object DbDriver extends DbDriver {
  type Duplicate = com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
}

导入此类型,您可以对其进行模式匹配:

case Success(res) => 
  // insert succeeded, no duplicate exception
case Failure(e: Duplicate) =>
  // duplicate exception
case Failure(e) => 
  // other failures