首页 > 解决方案 > Kotlin SpringBoot 和 JPA - 如何创建 OneToOne 关系?

问题描述

我正在尝试在两个实体之间创建关系 OneToOne 并且总是得到错误(或非常相似,Error created bean with name 'entityManagerFactory' always):

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unknown mappedBy in: com.moises.kotlinstoreapi.model.Image.product, referenced property unknown: com.moises.kotlinstoreapi.model.Product.images
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1803) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]

...

[spring-boot-devtools-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    Caused by: org.hibernate.AnnotationException: Unknown mappedBy in: com.moises.kotlinstoreapi.model.Image.product, referenced property unknown: com.moises.kotlinstoreapi.model.Product.images
        at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:169) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]


如果我不放置关系,我可以毫无问题地创建表格。

我的代码:

package com.moises.kotlinstoreapi.model

import com.fasterxml.jackson.annotation.JsonManagedReference
import javax.persistence.*
import javax.validation.constraints.NotBlank

@Entity
@Table(name="images")
data class Image (
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0,
    val alt: String = "",
    @NotBlank
    val src: String = "",
    val tite: String = "",

    /**
     * Relations
     *
     */
    //@OneToOne(mappedBy="images")
    @OneToOne(mappedBy = "images", cascade = [(CascadeType.ALL)], fetch= FetchType.EAGER)
    @JsonManagedReference
    val product: Product = Product()
)


package com.moises.kotlinstoreapi.model

import com.fasterxml.jackson.annotation.JsonManagedReference
import java.time.LocalDateTime
import javax.persistence.*
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotEmpty
import javax.validation.constraints.NotNull

@Entity
@Table(name="products")
data class Product (
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0,
    @NotBlank
    val title: String = "",
    @NotBlank
    val description: String = "",
    @NotEmpty
    var price: Double = 999.99,
    @NotNull
    var created_at: LocalDateTime = LocalDateTime.now(),
    var update_at: LocalDateTime? = null,

    /**
     * Relations
     *
     */
    //@OneToOne(mappedBy="products", cascade = arrayOf(CascadeType.ALL))
    //@JoinColumn(name = "id")
    @OneToOne(cascade = [(CascadeType.ALL)], fetch= FetchType.EAGER)
    @JoinColumn(name = "image_id")
    @JsonManagedReference
    val image: Image? = null

    //@OneToOne(mappedBy="products", orphanRemoval=true, cascade=arrayOf(CascadeType.PERSIST))
    //private val image: Image?

    //@OneToOne(cascade = arrayOf(CascadeType.ALL))
    //@JoinColumn(name = "purchase_line_id")
    //val purchaseLine: PurchaseLine ?= null
)


我在 Ubuntu 中使用 IntelliJ 和 Maven 和 OpenJDK 11。

我的 pow.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.moises</groupId>
    <artifactId>kotlin-store-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>kotlin-store-api</name>
    <description>API store with Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <kotlin.version>1.3.50</kotlin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-kotlin</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-reflect</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
        <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <configuration>
                    <args>
                        <arg>-Xjsr305=strict</arg>
                    </args>
                    <compilerPlugins>
                        <plugin>spring</plugin>
                        <plugin>jpa</plugin>
                    </compilerPlugins>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.jetbrains.kotlin</groupId>
                        <artifactId>kotlin-maven-allopen</artifactId>
                        <version>${kotlin.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.jetbrains.kotlin</groupId>
                        <artifactId>kotlin-maven-noarg</artifactId>
                        <version>${kotlin.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>

标签: spring-bootjpakotlin

解决方案


你有错误的 mappedBy 值Image-mappedBy = "images"它应该是"image"

    @OneToOne(mappedBy = "image", cascade = [(CascadeType.ALL)], fetch= FetchType.EAGER)
    @JsonManagedReference
    val product: Product = Product()

因为Product有字段image

    @JsonManagedReference
    val image: Image? = null

推荐阅读