Reputation: 347
So I have entity with UUID as primary key. After I create the entity in my service, the response return wrong id.
My Role entity
package denny.study.stock.entity
import denny.study.stock.util.converter.JsonToMapConverter
import org.hibernate.annotations.CreationTimestamp
import org.hibernate.annotations.GenericGenerator
import org.hibernate.annotations.Type
import org.hibernate.annotations.UpdateTimestamp
import java.util.*
import javax.persistence.*
@Entity
@Table(name = "roles")
class Role {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "id", columnDefinition = "CHAR(36)")
@Type(type = "uuid-char")
var id: UUID = UUID.randomUUID()
@Column
var name: String = ""
@Column
var slug: String = ""
@Column
@Convert(converter = JsonToMapConverter::class)
var permissions: MutableMap<String, Boolean>? = null
@Column(name = "created_at")
@CreationTimestamp
var createdAt: Date = Date()
@Column(name = "updated_at")
@UpdateTimestamp
var updatedAt: Date? = null
}
My store method in role service
override fun store(roleRequest: RoleRequest): RoleResponse {
val role = Role().apply {
name = roleRequest.name
slug = roleRequest.slug
permissions = roleRequest.permissions
}
roleRepository.save(role)
return RoleResponse(role)
}
My Role response
package denny.study.stock.model.response.role
import denny.study.stock.entity.Role
class RoleResponse(role: Role) {
var id = role.id
var name = role.name
var slug = role.slug
var permissions = role.permissions
}
the json response return id "f95bddf6-eb22-49bb-b8e6-5eb819603fa9"
{
"code": 200,
"status": "OK",
"data": {
"id": "f95bddf6-eb22-49bb-b8e6-5eb819603fa9",
"name": "Role 1",
"slug": "role-1",
"permissions": {
"asd": true,
"dsa": false
}
}
}
while in DB it stored as "87596692-7ee9-4ecb-a425-3b1372d901f4". Do you know why It return the wrong id? Thank you!
Upvotes: 1
Views: 2818
Reputation: 17460
You are using @GeneratedValue
annotation and also assigning UUID.randomUUID()
to the id
attribute. Either use one or the other, not both.
If you want the ID to be generated by the persistence provider then keep @GeneratedValue
and remove @GenericGenerator
(which is a Hibernate annotation) and UUID.randomUUID()
. If you want to do that on your own then remove @GeneratedValue
and @GenericGenerator
.
Upvotes: 2