我正在尝试实现一种使用单个数据库表来保存不同对象类型的多个应用程序设置的方法。
我想我应该使用泛型来完成这个任务,但是,我认为我做得不对。下面是我的实体目前的样子:
@Entity
@Table(name = "table_application_settings")
data class ApplicationSetting<T>(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "application_setting_id")
val id: Long? = null,
@Column(name = "application_setting_name")
var name: String = "",
@Column(name = "application_setting_value")
var value: T? = null,
)
我的存储库:
@Repository
interface ApplicationSettingsRepository : JpaRepository<ApplicationSetting<*>, Long> {
fun findApplicationSettingByName(name: String): ApplicationSetting<*>
}
我的服务:
@Service
@Transactional
class ApplicationSettingsServiceImpl(
private val applicationSettingsRepository: ApplicationSettingsRepository,
) : ApplicationSettingsService {
override fun saveBooleanApplicationSetting(applicationSetting: ApplicationSetting<Boolean>): ApplicationSetting<Boolean> {
return applicationSettingsRepository.save(applicationSetting)
}
override fun saveIntegerApplicationSetting(applicationSetting: ApplicationSetting<Int>): ApplicationSetting<Int> {
return applicationSettingsRepository.save(applicationSetting)
}
override fun getAllApplicationSettings(): MutableList<ApplicationSetting<*>> {
return applicationSettingsRepository.findAll()
}
}
但是,当我尝试运行该应用程序时,出现以下错误:
Caused by: org.hibernate.AnnotationException: Property com.jre.hireout.database.entities.application.ApplicationSetting.value has an unbound type and no explicit target entity. Resolve this Generic usage issue or set an explicit target attribute (eg @OneToMany(target=) or use an explicit @Type
我知道我有一个注解问题,但我不确定如何修复它沿着让这按预期工作。
1条答案
按热度按时间smtd7mpg1#
在JPA中不支持具有泛型的实体。
你能得到的最接近的可能是有一个实体,它把值保存为字符串,我猜这也是你在数据库中使用的。
然后有几个方法使用不同的类型返回值,例如
valueAsInt
。您需要自己进行转换。
另一种方法是继承层次结构,但默认情况下,
value
Map到不同的列,我不确定是否可以将其Map到同一列而不发生任何问题。