You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin Spring Boot接口返回JSON如何包含@Embeddable修饰的关联属性

问题原因
  • authorities属性在Users类中被声明为private,Jackson序列化时默认只会读取带有公开getter方法的属性,私有字段不会被自动序列化。
  • @ElementCollection注解默认使用LAZY懒加载策略,若查询时没有主动加载该集合,序列化时无法获取到有效权限数据。
解决方案

步骤1:让Jackson可以读取authorities属性

两种可选方案,选其一即可:

  1. 移除authorities的private修饰符,设置为公开属性
@ElementCollection
@CollectionTable(name = "authorities", joinColumns = [JoinColumn(name = "username")])
@MapKeyColumn(name = "users")
var authorities : MutableSet<Authorities> = mutableSetOf()
  1. 保留private修饰符,为属性添加@JsonProperty注解,强制Jackson读取私有字段序列化
@ElementCollection
@CollectionTable(name = "authorities", joinColumns = [JoinColumn(name = "username")])
@MapKeyColumn(name = "users")
@JsonProperty
private var authorities : MutableSet<Authorities> = mutableSetOf()

步骤2:解决懒加载无法读取数据问题

两种可选方案,选其一即可:

方案A:修改集合加载策略为即时加载

直接给@ElementCollection设置fetch = FetchType.EAGER,查询用户时会同步加载权限集合

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "authorities", joinColumns = [JoinColumn(name = "username")])
@MapKeyColumn(name = "users")
var authorities : MutableSet<Authorities> = mutableSetOf()

方案B:在Repository查询方法中主动Fetch权限集合

如果不想全局修改加载策略,可自定义JPQL查询主动关联加载权限:

// 在你的UsersRepository接口中添加该方法
@Query("SELECT u FROM Users u JOIN FETCH u.authorities WHERE u.username = :username")
fun getByUsername(@Param("username") username: String): Optional<Users>

步骤3:修复Authorities类的无参构造问题

JPA要求@Embeddable类必须有无参构造方法,给属性添加默认值即可:

@Embeddable
class Authorities(
    var authority: String = ""
)

修改完成后调用接口即可返回包含权限的JSON:

{
    "username": "test@gmail.com",
    "authorities": [
        {"authority": "ROLE_USER"},
        {"authority": "ROLE_ADMIN"}
    ]
}

内容的提问来源于stack exchange,提问作者Marco Antonio Francis Pereira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:36:04