在JVM平台上访问数据库的全新外观:来自Typesafe的Slick

在今天的帖子中,我们将敞开胸怀,摆脱传统的基于Java EE / Java SE JPA的堆栈(我认为这是很棒的),并重新审视如何使用新的孩子访问Java应用程序中的数据库。块: Typesafe的 Slick 2.1 。 因此,如果JPA如此出色,为什么还要麻烦? 好吧,有时候您需要做一些非常简单的事情,而无需为此提供完整的,建模良好的持久层。 在这里, 油滑发光。

本质上, Slick是数据库访问库,而不是ORM 。 尽管它是用Scala编写的,但我们要看的示例并不需要对这种出色的语言有任何特定的了解(尽管,正是Scala使Slick的存在成为可能)。 我们的关系数据库模式将只有两个表, customersaddress ,通过一对多关系链接。 为简单起见, H2被选为内存数据库引擎。

出现的第一个问题是定义数据库表(模式),自然,特定于数据库的DDL是实现此目的的标准方法。 我们可以做些什么,然后尝试另一种方法吗? 如果您使用的是Slick 2.1 ,那么绝对是肯定的。 让我们仅将表描述为Scala类:

// The 'customers' relation table definition
class Customers( tag: Tag ) extends Table[ Customer ]( tag, "customers" ) {
  def id = column[ Int ]( "id", O.PrimaryKey, O.AutoInc )

  def email = column[ String ]( "email", O.Length( 512, true ), O.NotNull )
  def firstName = column[ String ]( "first_name", O.Length( 256, true ), O.Nullable )
  def lastName = column[ String ]( "last_name", O.Length( 256, true ), O.Nullable )

  // Unique index for customer's email
  def emailIndex = index( "idx_email", email, unique = true )
}

非常简单明了,类似于许多典型的CREATE TABLE构造。 地址表将以相同的方式定义,并通过外键引用用户表。

// The 'customers' relation table definition
class Addresses( tag: Tag ) extends Table[ Address ]( tag, "addresses" ) {
  def id = column[ Int ]( "id", O.PrimaryKey, O.AutoInc )

  def street = column[ String ]( "street", O.Length( 100, true ), O.NotNull )
  def city = column[ String ]( "city", O.Length( 50, true ), O.NotNull )
  def country = column[ String ]( "country", O.Length( 50, true ), O.NotNull )

  // Foreign key to 'customers' table
  def customerId = column[Int]( "customer_id", O.NotNull )
  def customer = foreignKey( "customer_fk", customerId, Customers )( _.id )
}

太好了,仅需保留一些细节即可:我们在纯Scala中定义了两个数据库表。 但是细节很重要,我们将密切关注以下两个声明: Table [Customer]Table [Address] 。 从本质上讲,每个表都可以表示为元组,其元素数量与其定义的列数相同。 例如, 客户(Int,String,String,String)的元组,而地址表是(Int,String,String,String,Int)的元组。 Scala中的元组很棒,但使用起来并不方便。 幸运的是, Slick通过提供所谓的“ 提升嵌入”技术,允许使用案例类而不是元组。 以下是我们的客户地址案例类:

case class Customer( id: Option[Int] = None, email: String, 
  firstName: Option[ String ] = None, lastName: Option[ String ] = None)

case class Address( id: Option[Int] = None,  street: String, city: String, 
  country: String, customer: Customer )

最后但并非最不重要的问题是, Slick将如何从元组转换为案例类,反之亦然? 开箱即用的转换非常棒,但在现阶段, Slick需要一些帮助。 使用Slick术语,我们将调整*表投影的形状(对应于SELECT * FROM… SQL构造)。 让我们来看看客户的情况

// Converts from Customer domain instance to table model and vice-versa
def * = ( id.?, email, firstName.?, lastName.? ).shaped <> ( 
  Customer.tupled, Customer.unapply )

对于地址表,由于Slick无法通过外键引用客户案例类实例,因此整形看起来有些冗长。 不过,这非常简单,我们只是从其标识符构造临时客户

// Converts from Customer domain instance to table model and vice-versa
def * = ( id.?, street, city, country, customerId ).shaped <> ( 
  tuple => {
    Address.apply(
      id = tuple._1,
      street = tuple._2,
      city = tuple._3,
      country = tuple._4,
      customer = Customer( Some( tuple._5 ), "" )
    )
  }, {
    (address: Address) =>
      Some { (
        address.id,
        address.street,
        address.city,
        address.country,
        address.customer.id getOrElse 0 
      )
    }
  }
)

现在,在解释完所有详细信息之后,我们如何才能将Scala表定义具体化为实际的数据库表? 幸运的是,对于Slick来说 ,这很容易:

implicit lazy val DB = Database.forURL( "jdbc:h2:mem:test", driver = "org.h2.Driver" )
  
DB withSession { implicit session =>
  ( Customers.ddl ++ Addresses.ddl ).create
}

Slick有许多查询和更新数据库中数据的方法。 最美丽,功能最强大的就是使用Scala语言的纯函数构造。 最简单的方法是定义伴随对象并在其中实现典型的CRUD操作。 例如,以下是将新客户记录插入客户表的方法:

object Customers extends TableQuery[ Customers ]( new Customers( _ ) ) {
  def create( customer: Customer )( implicit db: Database ): Customer = 
    db.withSession { implicit session =>
      val id = this.autoIncrement.insert( customer )
      customer.copy( id = Some( id ) )
    } 
}

它可以这样使用:

Customers.create( Customer( None, "tom@b.com",  Some( "Tom" ), Some( "Tommyknocker" ) ) )
Customers.create( Customer( None, "bob@b.com",  Some( "Bob" ), Some( "Bobbyknocker" ) ) )

同样, 找到函数的家庭可以使用常规的实施斯卡拉 理解:

def findByEmail( email: String )( implicit db: Database ) : Option[ Customer ] = 
  db.withSession { implicit session =>
    ( for { customer <- this if ( customer.email === email.toLowerCase ) } 
      yield customer ) firstOption
  }
   
def findAll( implicit db: Database ): Seq[ Customer ] = 
  db.withSession { implicit session =>      
    ( for { customer <- this } yield customer ) list
  }

这是用法示例:

val customers = Customers.findAll
val customer = Customers.findByEmail( "bob@b.com" )

更新和删除虽然也很简单,但还是有些不同,让我们看一下:

def update( customer: Customer )( implicit db: Database ): Boolean = 
  db.withSession { implicit session =>
    val query = for { c <- this if ( c.id === customer.id ) } 
      yield (c.email, c.firstName.?, c.lastName.?)
    query.update(customer.email, customer.firstName, customer.lastName) > 0
  }
  
def remove( customer: Customer )( implicit db: Database ) : Boolean = 
  db.withSession { implicit session =>
    ( for { c <- this if ( c.id === customer.id ) } yield c ).delete > 0
  }

让我们看看这两种方法的作用:

Customers.findByEmail( "bob@b.com" ) map { customer =>
  Customers.update( customer.copy( firstName = Some( "Tommy" ) ) )
  Customers.remove( customer )
}

看起来很整齐。 我个人仍在学习Slick,但是对此我感到非常兴奋。 它帮助我更快地完成工作,享受Scala语言和函数式编程的美。 毫无疑问,即将到来的3.0版将带来更多有趣的功能,我很期待它。

这篇文章只是对Slick世界的介绍,许多实现细节和用例已经放在一边,以使其简短而简单。 但是, Slick的文档非常好,请随时查阅。

翻译自: https://www.javacodegeeks.com/2015/03/a-fresh-look-on-accessing-database-on-jvm-platform-slick-from-typesafe.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值