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

问题描述 投票:2回答:1

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

package util

import slick.driver.MySQLDriver

trait DbDriver extends MySQLDriver {
  val dbApi = api
}

object DbDriver extends DbDriver

然后在使用Slick I的类中导入如下(而不是特定于数据库的驱动程序):

import util.DbDriver.api._

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

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

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

这是我的尝试(这不起作用):

声明:

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

并抓住:

case Failure(e: Duplicate) => // print something
scala slick slick-3.0
1个回答
1
投票

您可以定义类型别名:

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
© www.soinside.com 2019 - 2024. All rights reserved.