使用Scala创建Spring Data JPA存储库的方法

3
@Repository
trait PersonRepository extends JpaRepository[Person, Long] {  }


error: trait Repository is abstract; cannot be instantiated
[ERROR] @Repository

这个小特性由于明显的原因无法编译。但是我怎样可以在Scala中定义Spring Data JPA存储库?(Scala 2.10.3)


使用scala-test的示例测试用例:

@RunWith(classOf[JUnitRunner])
@ContextConfiguration(locations = Array("classpath:/moduleContext.xml"), loader = classOf[AnnotationConfigContextLoader])
class PersonRepositoryTest extends FunSpec with Matchers {

  @Autowired var personRepository: PersonRepository = _

  describe("Person repository") {
    it("should persist a person") {
      val person = new Person()
      val persistedPerson = personRepository.save(person)
      assert(persistedPerson.id >= 0)
    }
  }
}
2个回答

1

Spring Data 的接口必须是接口:)。只需将您的存储库设置为接口,基础架构就应该能够捕获它。

确保正确设置存储库(使用 <jpa:repositories base-package="…" />@EnableJpaRepositories)。


嗯,我希望我能做一些类似于Neo4J的东西;) 比如说trait PersonRepository extends GraphRepository[Person]。但我不确定我是否完全理解这背后的魔力。有没有可能让某个trait扩展JPA CRUD接口,以使管道工作像在Neo4J中一样? - simou
仍然不明白为什么你坚持甚至需要特性。你可以扩展多个接口,而且既然你不需要为它们提供实现,我想知道背后的真正原因是什么。而且,我会首先尝试让它起作用。那么你的意思是说,使用interface而不是trait时它能工作吗? - Oliver Drotbohm
是的,它很好用。当然,你所建议的没有任何问题。也许我想更深入地了解为什么Scala traits在SDN中很好而在SDJPA中不好。此外,我希望代码库100%使用Scala。也许我应该在另一个线程中问这个问题。 - simou

1

只需删除 @Repository

这对我有效:

trait CityRepository extends JpaRepository[City, String] {
   def findById(id:String):java.util.List[City]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接