代码之家  ›  专栏  ›  技术社区  ›  ps0604

避免在Slick 3中使用MySQL显式声明。x个

  •  2
  • ps0604  · 技术社区  · 8 年前

    在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
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Jeffrey Chung    8 年前

    可以定义类型别名:

    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
    
    推荐文章