@CreationTimestamp and @UpdateTimestamp don't

2019-06-26 03:52发布

问题:

This is my Tag and Post Entity classes:

@Entity
class Tag(
        @get:NotBlank
        @Column(unique = true)
        val name: String = "",
        val description: String = ""
) {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    val id: Int? = null


    @ManyToMany(mappedBy = "tags")
    val posts: MutableSet<Post> = mutableSetOf()

    @CreationTimestamp
    lateinit var createDate: Date

    @UpdateTimestamp
    lateinit var updateDate: Date

    fun addPost(post: Post) {
        this.posts.add(post)
        post.tags.add(this)
    }


}



@Entity
class Post(
        @get:NotBlank
        var name: String = "",
        val content: String = ""
) {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    val id: Int? = null
    @ManyToMany
    @Cascade(CascadeType.ALL)
    val tags: MutableSet<Tag> = mutableSetOf()

    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    lateinit var createDate: Date

    @UpdateTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    lateinit var updateDate: Date


    fun addTag(tag: Tag) {
        this.tags.add(tag)
        tag.posts.add(this)
    }
}

The query:

val post1 = Post( "Post 1", "Post 1 content");
val post2 = Post( "Post 2", "Post 2 content");
var tag = Tag( "news", "Tag description")
post1.addTag(tag)
post2.addTag(tag)
em.persist(post1)
em.persist(post2)
em.remove(post1)
em.flush()

But then, the createDate and updateDate return null (both tag and post):

I converted this code to Java and it works fine

Kotlin version: 1.2-M2

springBootVersion: '2.0.0.M7'

回答1:

The problem likely exists in the fact that those annotations are not limited to what they should annotate. This means kotlin does not know exactly where to put them in the final bytecode.

To get the same bytecode as would be generated by java, you need to specify the annotation target of the annotation in question:

@field:CreationTimestamp
lateinit var createDate: Date


回答2:

The context is not enough to provide any meaningful answer.

You have to give more context, in particular the application server, with its version, or even code for this specific use-case. To start with, I'd suggest first checking if the same Java code works.

My best guess so far, you're using Spring Data JPA while @CreationTimestamp and @UpdateTimestamp are Hibernate specific.