Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@CreationTimestamp and @UpdateTimestamp don't work in Kotlin

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): enter image description here

I converted this code to Java and it works fine

Kotlin version: 1.2-M2

springBootVersion: '2.0.0.M7'

like image 352
cdxf Avatar asked Dec 03 '17 11:12

cdxf


1 Answers

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
like image 187
Kiskae Avatar answered Sep 29 '22 02:09

Kiskae