第一篇文章。绝对的菜鸟。善待
我正在和夸克和科特琳玩耍。
我有这个kotlin实体类:
@Entity
data class Fruit (
var name: String = "",
var description: String = ""
) : PanacheEntity()
我具有基于Java教程的资源类:
@Path("/fruits")
@ApplicationScoped
public class FruitJResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Fruit> getAll() {
return Fruit.listAll();
}
}
这里一切都很好,Fruit继承自PanacheEntityBase,我可以访问listAll()
但是, Kotlin中的同一个班级没有:
@Path("/fruits")
@ApplicationScoped
class FruitResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
fun getAll(): List<Fruit> = Fruit.listAll()
}
现在我已经知道,这可能是由于kotlin无法从Super Class继承静态方法。 我读到,应该直接从超类调用静态方法,但这在这里不起作用。
因此,我需要一个可能的解决方法的建议。
答案 0 :(得分:1)
目前(1.4.1)对于kotlin
和scala
语言的唯一解决方案是使用存储库模式:
请参阅文档:https://quarkus.io/guides/hibernate-orm-panache#solution-2-using-the-repository-pattern
这是由于引用的问题github.com/quarkusio/quarkus/issues/4394。
因此,如果使用Kotlin,则只需定义一个新的FruitRepository
@ApplicationScoped
class FruitRepository: PanacheRepository<Fruit> {
fun all(): List<Fruit> = findAll(Sort.by("name")).list<Fruit>()
}
答案 1 :(得分:0)
Quarkus发布了一个扩展,该扩展将Kotlin支持引入了panache(我认为它仍处于预览状态)。
在Gradle中(如果您在项目中使用Gradle),您需要添加依赖项implementation 'io.quarkus:quarkus-hibernate-orm-panache-kotlin'
要定义“静态”方法(Kotlin使用Companion对象来处理静态方法),您需要定义一个伴随对象,如下所示:
@Entity
open class Category : PanacheEntityBase {
@Id
@GeneratedValue
lateinit var id: UUID
// ...
companion object : PanacheCompanion<Category, UUID> {
fun findByName(name: String) = find("name", name).firstResult()
fun findActive() = list("active", true)
fun deleteInactive() = delete("active", false)
}
}
有关更多信息,您可以查看官方文档: https://quarkus.io/guides/hibernate-orm-panache-kotlin
如果您使用单元测试,请当心:至少对我而言,panache-mock扩展不适用于Kotlin版本的panache。