Kotlin对JPA静态元模型的支持

12

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

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

如何解决这个问题?

编辑

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

3个回答

8

我不得不使用 kapt插件

我必须在我的build.gradle文件中添加以下行。

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

7
当使用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>

3
我推荐使用这个库。您可以像使用querydsl一样编写查询,而无需使用静态元模型来管理jpa实体。 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"))
}

and表达式

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))))
    // ...
}

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