我目前正在研究一个使用Kotlin编写的使用Spring Boot的项目。必须提到的是,我对来自Java的Kotlin还是比较陌生。我有一个小的数据库,其中包含一个用于查找文件的表。在此数据库中,我存储了文件的路径(出于测试目的,该路径仅存储在项目的资源中)。
有问题的对象如下:
@Entity
@Table(name = "NOTE_FILE")
class NoteFile {
@Id
@GeneratedValue
@Column(name = "id")
var id: Int
@Column(name = "note")
@Enumerated(EnumType.STRING)
var note: Note
@Column(name = "instrument")
var instrument: String
@Column(name = "file_name")
var fileName: String
set(fileName) {
field = fileName
try {
file = ClassPathResource(fileName).file
} catch (ignored: Exception) {
}
}
@Transient
var file: File? = null
private set
constructor(id: Int, instrument: String, note: Note, fileName: String) {
this.id = id
this.instrument = instrument
this.note = note
this.fileName = fileName
}
}
我已经创建了以下存储库,用于从数据库中检索该对象:
@Repository
interface NoteFileRepository : CrudRepository<NoteFile, Int>
以及以下服务:
@Service
class NoteFileService @Autowired constructor(private val noteFileRepository: NoteFileRepository) {
fun getNoteFile(id: Int): NoteFile? {
return noteFileRepository.findById(id).orElse(null)
}
}
我遇到的问题是,当我调用getNoteFile
函数时,构造的NoteFile对象的构造函数或设置方法都没有被调用。结果,file
字段保持为空,而我希望它包含一个值。解决此问题的方法是,将fileName
字段设置为该字段的值,但这看起来很奇怪,势必会引起问题:
val noteFile: NoteFile? = noteFileService.getNoteFile(id)
noteFile.fileName = noteFile.fileName
这样,将调用设置器,并且file
字段将获得正确的值。但是如上所述,这不是要走的路。原因可能是在Spring Data框架中,默认构造函数是必需的。我正在使用必要的here描述的Maven插件来使Kotlin和JPA一起工作。
通过Spring(数据)/ JPA框架构造对象时,构造函数和/或setter是否有某种被调用的方法?还是应该在检索对象的服务中显式调用fileName
的二传手?还是最好的做法是将file
字段作为一个整体删除,然后简单地将其转换为获取文件并像这样返回的函数?