【问题标题】:Avoiding MySQL explicit declaration in Slick 3.x在 Slick 3.x 中避免 MySQL 显式声明
【发布时间】:2018-08-12 04:00:24
【问题描述】:

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

package util

import slick.driver.MySQLDriver

trait DbDriver extends MySQLDriver {
  val dbApi = api
}

object DbDriver extends DbDriver

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

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】:

    你可以定义一个类型别名:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      相关资源
      最近更新 更多