使用Spring Data JPA在Scala中进行建模的最佳方式是什么

时间:2019-09-03 12:54:55

标签: scala spring-boot jpa spring-data-jpa

Scala在春季没有像Kotlin那样得到一流的支持。

我试图用Scala创建一个Spring Boot API应用程序。

  • Spring Boot 2.2.0.M5
  • Spring Data JPA
  • H2
  • Scala 2.13

我创建了一个JPA实体,其案例类如下:

@Entity
case class Post(@BeanProperty title: String, @BeanProperty content: String) {
  def this() {
    this(null, null)
  }

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @BeanProperty
  var id: Long = _

  @BeanProperty
  val createdOn: LocalDateTime = LocalDateTime.now()

  override def toString: String = s"Post[id:$id, title:$title, content:$content, createdOn:$createdOn]"
}

并使用trait创建存储库,它可以正常工作。

trait PostRepository extends JpaRepository[Post, Long]

我想尝试bean验证。

class PostForm {

  @NotNull
  @NotEmpty
  @BeanProperty var title: String = _
  @BeanProperty var content: String = _
}

然后在控制器中,创建一个POST方法,例如:

  @PostMapping
  def save(@RequestBody @Valid form: PostForm, errors: BindingResult) = errors.hasErrors match {
    case true => {
      badRequest().build()
    }
    case _ => {
      val data = Post(title = form.title, content = form.content)
      val saved = posts.save(data)
      created(ServletUriComponentsBuilder.fromCurrentContextPath().path("/{id}").buildAndExpand(saved.id).toUri).build()
    }
  }

有效。

但是模型类有点乏味。我正在尝试使用类似以下的case类:

case class PostForm(@NotNull @NotEmpty @BeanProperty title: String, @BeanProperty content: String)

验证无效。

  1. 当我们为JPA等建模时,案例类还是泛型类更好?
  2. 为什么我们不能在case类中将Bean验证批注应用为Kotlin数据分类?

更新:具有以下功能:

case class PostForm(@(NotNull@field) @(NotEmpty@field) @BeanProperty title: String, @BeanProperty content: String)

源代码托管在我的Github上。

1 个答案:

答案 0 :(得分:1)

案例类字段默认情况下被视为val,这意味着您无法为其设置新值。 @BeanProperty是用于自动生成字段设置者和获取器。

您可以尝试将var关键字显式添加到字段中。

case class PostForm(
  @NotNull @NotEmpty @BeanProperty var title: String,
  @BeanProperty var content: String
)