我在JPA中有一个实体,我有兴趣转换为枚举。
我面临的问题是我与该表之间存在关系,该关系由联接表映射。
@Entity
@Table(name = "user")
data class User(
@ManyToMany
@JoinTable(
name = "user_certificates",
joinColumns = [JoinColumn(name = "user_id")],
inverseJoinColumns = [JoinColumn(name = "certificate_id")]
)
var certificates: List<Certficate> = listOf()
)
这是我有兴趣过渡到的枚举,
enum class Certificate(val id: Int) {
FOO(1),
BAR(2),
BAZ(3)
}
是否可以将其转换为具有ID的枚举并使用相同的user_certificates
表来存储附加到具有现有关系的实体的枚举?
答案 0 :(得分:2)
同一表可以与用户实体类中的以下映射一起使用:
@ElementCollection(fetch = FetchType.EAGER, targetClass = Certificate::class)
@CollectionTable(name = "user_certificates", joinColumns = [JoinColumn(name = "user_id")])
@Column(name = "certificate_id")
@Convert(converter = CertificateEnumConverter::class)
var certificates: List<Certificate> = listOf(),
转换器看起来像
class CertificateEnumConverter : AttributeConverter<Certificate, Int> {
override fun convertToDatabaseColumn(attribute: Certificate?) = attribute!!.id
override fun convertToEntityAttribute(dbData: Int?) = Certificate.fromId(dbData!!)
}