在Spring Boot + Kotlin中使用JPA + H2 - 错误启动

时间:2018-01-11 01:40:08

标签: spring jpa spring-boot kotlin h2

我有一个非常简单的sample Spring Boot + Kotlin项目。 我添加了所有基本依赖项:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-stdlib-jdk8</artifactId>
        <version>${kotlin.version}</version>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-reflect</artifactId>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-test</artifactId>
        <version>${kotlin.version}</version>
        <scope>test</scope>
    </dependency>

我使用JPA注释注释了两个模型类:

@Entity
class Author(
     @Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Long,
     val firstName: String,
     val lastName: String,
     @ManyToMany(mappedBy = "authors") val books: Set<Book> = emptySet()
)

@Entity
class Book(
     @Id @GeneratedValue(strategy = GenerationType.AUTO)
     val id: Long,
     @ManyToMany @JoinTable(
          name = "author_book",
          joinColumns = [JoinColumn(name = "book_id")],
          inverseJoinColumns = [(JoinColumn(name = "author_id"))])
     val author: Set<Author> = emptySet(),
     val title: String,
     val label: String,
     val publisher: String
)

我有一个基本的主要:

@SpringBootApplication
open class Spring5webappApplication {

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            SpringApplication.run(Spring5webappApplication::class.java, *args)
        }
    }
}

But when I boot, I get a bit error stack.

你可以给我一些线索吗?我搜索了错误,但答案太无关紧要了。感谢。

1 个答案:

答案 0 :(得分:2)

您的代码中有拼写错误。 书中的属性称为作者而不是作者。

所以这是正确的代码。

val authors: Set<Author> = emptySet(),

始终查看stacktrace中的最后一个异常

Caused by: org.hibernate.AnnotationException: 
    mappedBy reference an unknown target entity property: 
    guru.springframework.spring5webapp.model.Book.authors in guru.springframework.spring5webapp.model.Author.books