如何使用sorm中的原始实体ID创建其他实体类型

如何使用sorm中的原始实体ID创建其他实体类型

本文介绍了如何使用sorm中的原始实体ID创建其他实体类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

case class Product( title : String, description: String, contract: Contract)
case class Contract(contractType: ContractType, price: Int )
case class ContractType(description: String)

和这些DTO:

case class ProductDto(id: Long, title: String, description: String, contractType: ContractTypeDto, price: Int)
case class ContractTypeDto(id: Long, description: String)

我需要创建一个返回产品列表但数据已填充在DTO中的方法,如下所示:

I need to create a method that returns the list of products but with the data filled in DTOs, something like this:

def list = Db.query[Product].fetch().toList.map(x => ProductDto(x.id, x.title,
    x.description, ContractTypeDto(x.contract.contractType.id,
    x.contract.contractType.description), x.contract.price))

问题是我无法访问x.contract.contractType.id,但是SORM允许我访问x.id(在第一级),有什么办法可以做到??

The thing is that I can't access to the x.contract.contractType.id but SORM allows me to access to x.id (at first level), there is any way to do it??

谢谢

推荐答案

铸造方法

如果需要,您始终可以使用强制转换来访问id

x.contract.contractType.asInstanceOf[ sorm.Persisted ].id

总体进近

使用模式匹配来生成 total 函数来做到这一点更干净:

Total Approach

It is cleaner though to utilize pattern matching to produce a total function to do it:

def asPersisted[ A ]( a : A ) : Option[ A with sorm.Persisted ]
  = a match {
      case a : A with sorm.Persisted => Some( a )
      case _ => None
    }

然后我们可以像这样使用它:

Then we can use it like so:

asPersisted( x.contract.contractType ).map( _.id ) // produces Option[ Long ]

total 方法的好处是,您可以保护自己免受运行时强制转换异常的影响,如果您尝试强制转换非持久性值,则会产生异常.

The benefit of the total approach is that you protect yourself from runtime casting exceptions, which will arise if you try to cast a non-persisted value.

如果您没有发现这种困扰,还可以使用值类将"asPersisted"拉皮条"到Any上:

You can also "pimp" asPersisted as a method onto Any using value-classes if you don't find this disturbing:

implicit class AnyAsPersisted[ A ]( val a : A ) extends AnyVal {
  def asPersisted : Option[ A with sorm.Persisted ]
    = a match {
        case a : A with sorm.Persisted => Some( a )
        case _ => None
      }
}

然后您将可以像这样使用它:

Then you'll be able to use it like so:

x.contract.contractType.asPersisted.map( _.id ) // produces Option[ Long ]

这篇关于如何使用sorm中的原始实体ID创建其他实体类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 17:13