JDK10升级后Lombok失效,Spring Boot项目Java转Kotlin数据类咨询
嗨,刚好我之前也遇到过类似的情况——升级JDK后Lombok闹脾气,转Kotlin后纠结JPA实体的写法,给你一套适配Spring Boot的Kotlin数据类方案,完美对应你原来的Java代码:
第一步:先搞定依赖和插件配置(Maven)
因为JPA实体需要无参构造、开放类这些特性,Kotlin需要借助插件来实现,在你的pom.xml里添加这些配置:
<!-- 确保Kotlin插件配置了JPA相关的AllOpen和NoArg插件 --> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <configuration> <compilerPlugins> <plugin>all-open</plugin> <plugin>no-arg</plugin> </compilerPlugins> <!-- 指定JDK10作为目标版本 --> <jvmTarget>10</jvmTarget> <pluginOptions> <!-- 让@Entity注解的类自动开放,满足JPA代理需求 --> <option>all-open:annotation=javax.persistence.Entity</option> <!-- 给@Entity注解的类生成无参构造 --> <option>no-arg:annotation=javax.persistence.Entity</option> </pluginOptions> </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>
第二步:写出对应你Java代码的Kotlin数据类
原来Java里的@Data、@EqualsAndHashCode(exclude)这些Lombok特性,用Kotlin的data class就能完美替代,而且更简洁:
import javax.persistence.* @Entity data class Document( // 主构造函数里放需要参与equals/hashCode的字段 @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator") val id: String? = null, // 这里补充你原来Java类里其他需要包含在equals/hashCode的字段,比如title、createTime等 val title: String, val createTime: Long ) { // 把需要排除在equals/hashCode之外的字段放在类体中,data class不会把这些纳入自动生成的方法 @ManyToOne var creator: User? = null @Column(length = 1000) var content: String? = null // 如果你需要全参构造函数,可以手动重载(或者直接用命名参数创建实例,更灵活) constructor( id: String?, title: String, createTime: Long, creator: User?, content: String? ) : this(id, title, createTime) { this.creator = creator this.content = content } }
关键细节解释
替代Lombok注解:
data class自动生成equals()、hashCode()、toString()、copy(),完全替代@Data- 通过把
creator、content放在类体中,实现了@EqualsAndHashCode(exclude = {"creator", "content"})的效果——这些字段不会参与equals和hashCode的计算 - NoArg插件自动为
@Entity类生成无参构造,替代@NoArgsConstructor
JPA适配:
- AllOpen插件让
@Entity类自动开放,避免JPA代理时的访问权限问题 - 懒加载的关联字段(比如
creator)放在类体里,还能避免调用equals时触发懒加载导致的异常
- AllOpen插件让
实例创建更灵活:
不需要依赖全参构造,用Kotlin的命名参数就能轻松创建实例:val doc = Document( title = "Spring Boot Kotlin指南", createTime = System.currentTimeMillis(), creator = currentUser, content = "这是一篇测试文档" )
这样写出来的Kotlin类既保留了Spring Boot JPA的特性,又利用了Kotlin的简洁性,完美解决你之前的痛点!
内容的提问来源于stack exchange,提问作者Unlucky
相关产品推荐
相关产品推荐

