Kotlin 对 JPA 静态元模型的支持

Koitlin support for JPA static metamodel

当我使用 Java 创建 Entity class 时,会生成 JPA 静态元模型。

如果我将实体转换为 Kotlin JPA,则不会生成静态元模型。

如何解决这个问题?

编辑

我正在使用 Gradle 作为构建工具。

我不得不使用 kapt plugin

我不得不在我的 build.gradle 文件中添加以下行。

kapt "org.hibernate:hibernate-jpamodelgen:${hibernate_version}"

使用 Maven 时,将以下代码段添加到 kotlin-maven-plugin<executions>

<execution>
   <id>kapt</id>
   <goals>
      <goal>kapt</goal>
   </goals>
   <configuration>
      <sourceDirs>
         <sourceDir>src/main/kotlin</sourceDir>
      </sourceDirs>
      <annotationProcessorPaths>
         <annotationProcessorPath>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <version>5.3.2.Final</version>
         </annotationProcessorPath>
      </annotationProcessorPaths>
   </configuration>
</execution>

我推荐这个图书馆。 在管理 jpa 实体时,您可以在不使用静态元模型的情况下编写类似 querydsl 的查询。 https://github.com/line/kotlin-jdsl

将 Hibernate Kotlin JDSL 和 Hibernate 添加到依赖项

dependencies {
    implementation("com.linecorp.kotlin-jdsl:hibernate-kotlin-jdsl:x.y.z")
    implementation("org.hibernate:hibernate-core:x.y.z")
}

并像这样使用它

val books: List<Book> = queryFactory.listQuery {
    select(entity(Book::class))
    from(entity(Book::class))
    where(column(Book::author).equal("Shakespeare"))
}

和表达式

val max = max(column(Book::price))
val count = count(column(Book::price))
val greatest = greatest(column(Book::createdAt))

和交叉连接示例

val books = queryFactory.listQuery<Book> {
    select(entity(Book::class))
    from(entity(Book::class))
    join(entity(Author::class) on(column(Book::authorId).equal(column(Author::id))))
    // ...
}