You need to enable JavaScript to run this app. Kotlin SpringBoot JPA 多Repository实体仅首存成功异常排查
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin SpringBoot JPA 多Repository实体仅首存成功异常排查

Kotlin + SpringBoot JPA 多实体持久化异常问题

问题核心

使用Kotlin开发集成JPA的SpringBoot应用时,无法将多个实体分别保存至对应Repository:仅第一个实体可正常落库,第二个实体始终无法持久化,暂未定位问题根因,需要排查方向指引。

相关代码与配置

Helper 业务类

@Component
class Helper @Autowired constructor(
    private val requestRepository: RequestRepository,
    private val exchangeRateRepository: ExchangeRateRepository,
    private val exchangeRateResultRepository: ExchangeRateResultRepository,
    private val responseRepository: ResponseRepository
) {
    fun processClientExchangeRateResponses(
        base: String, 
        listSymbols: List<String>, 
        clientResponses: List<ClientExchangeRateResponse>
    ) {
        requestRepository.save(Request("Test", "Test"))
        responseRepository.save(Response(10.0, "Test", 12, 12, "Hello"))
    }
}

Request 实体定义

@Entity
@Table(name = "requests")
class Request(
    @Column(name = "base", updatable = false, nullable = false)
    private val base: String,
    @Column(name = "requestObject", updatable = false, nullable = false)
    private val requestObject: String
) {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    @Column(name = "id", updatable = false, nullable = false)
    val id: Long = 0

    @CreationTimestamp
    @Column(name = "created_at", nullable = false, columnDefinition = "DATETIME")
    private val createdAt: ZonedDateTime? = getCurrentDateTime()

    @CreationTimestamp
    @Column(name = "updated_at", nullable = false, columnDefinition = "DATETIME")
    private val updatedAt: ZonedDateTime? = getCurrentDateTime()

    private fun getCurrentDateTime(): ZonedDateTime? = ZonedDateTime.now()
}

Response 实体定义

@Entity
@Table(name = "responses")
class Response(
    private val responseTime: Double,
    private val currencyType: String,
    private val exchangeId: Long,
    private val requestId: Long,
    private val responseObject: String
) {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    @Column(name = "id", updatable = false, nullable = false)
    val id: Long = 0

    @CreationTimestamp
    @Column(name = "created_at", nullable = false, columnDefinition = "DATETIME")
    private val createdAt: ZonedDateTime? = getCurrentDateTime()

    @CreationTimestamp
    @Column(name = "updated_at", nullable = false, columnDefinition = "DATETIME")
    private val updatedAt: ZonedDateTime? = getCurrentDateTime()
}

Repository 接口定义

@Repository
interface RequestRepository : JpaRepository<Request, Long>

@Repository
interface ResponseRepository : JpaRepository<Response, Long>

应用主类

@EnableScheduling
@SpringBootApplication
class RatesApplication

fun main(args: Array<String>) {
    runApplication<RatesApplication>(*args)
}

Maven 核心配置

<?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.3.3.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>globee</groupId>
    <artifactId>rates</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>rates</name>
    <description>Rates</description>

    <repositories>
        <repository>
            <id>jcenter</id>
            <url>https://jcenter.bintray.com/</url>
        </repository>
    </repositories>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>11</java.version>
        <kotlin.version>1.3.72</kotlin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.3.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-kotlin</artifactId>
        </dependency>
        <dependency>
            <groupId>khttp</groupId>
            <artifactId>khttp</artifactId>
            <version>1.0.0</version>
        </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.liquibase</groupId>
            <artifactId>liquibase-core</artifactId>
            <version>1.9.5</version>
        </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>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </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>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        <configuration>
                            <mainClass>globee.RatesApplication</mainClass>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.liquibase</groupId>
                <artifactId>liquibase-maven-plugin</artifactId>
                <version>3.10.2</version>
                <configuration>
                    <propertyFileWillOverride>true</propertyFileWillOverride>
                    <propertyFile>src/main/resources/liquibase.properties</propertyFile>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <configuration>
                    <args>
                        <arg>-Xjsr305=strict</arg>
                    </args>
                    <compilerPlugins>
                        <plugin>spring</plugin>
                    </compilerPlugins>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.jetbrains.kotlin</groupId>
                        <artifactId>kotlin-maven-allopen</artifactId>
                        <version>${kotlin.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

根因排查方向

  • 事务边界缺失:processClientExchangeRateResponses方法未添加事务注解,默认每个Repository的save操作是独立提交的事务,第二个save执行抛出的未捕获异常会直接中断流程,由于第一个事务已经提交,最终表现为仅第一个实体落库。可开启JPA SQL执行日志、全量异常日志确认第二个save操作的报错信息。
  • 实体字段映射异常:Response实体的构造函数参数未添加@Column注解,Kotlin环境下JPA无法正确将构造函数参数与表字段做映射,会生成缺列、列名不匹配的insert语句,触发数据库约束错误,导致操作失败。
  • 依赖版本冲突:POM中手动引入了spring-data-jpa 2.3.4.RELEASE,与Spring Boot 2.3.3.RELEASE自带的JPA版本不一致,会导致持久化上下文、EntityManager代理出现兼容问题,引发操作异常。
  • 数据库约束拦截:检查responses表的外键约束,传入的requestId、exchangeId字段值若不存在于关联表的主键中,插入操作会被数据库直接拒绝。

内容的提问来源于stack exchange,提问作者Eddie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.25 10:06:08