I have an update method on a spring controller which takes in a request and uses copy to copy the contents into a loaded entity. As soon as copy() is called, the id property on the entity is changed to a new one.
@PutMapping("/{id}")
fun update(@PathVariable id: UUID, @RequestBody request: UpdateSocietyRequest): ResponseEntity<SocietyUpdatedResponse> {
val society = societyRepository.findById(id).orElse(null) ?: return notFound().build()
val updatedSociety = society.copy(
name = request.name,
phone = request.phone,
address = Address(
request.addressLine1,
request.addressLine2,
request.addressLine3,
request.city,
request.state,
request.zipCode
)
)
societyRepository.save(updatedSociety)
return ok(SocietyUpdatedResponse(updatedSociety.id, updatedSociety.name, updatedSociety.phone))
}
Entity.kt
@MappedSuperclass
@JsonIgnoreProperties(value = ["createdOn, updatedOn"], allowGetters = true)
@EntityListeners(AuditingEntityListener::class)
abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
val id: UUID = UUID.randomUUID()
@Column(nullable = false, updatable = false)
@CreatedDate
var createdOn: LocalDateTime = LocalDateTime.now()
@Column(nullable = true)
@LastModifiedDate
var updatedOn: LocalDateTime? = null
@Column(nullable = false, updatable = false)
@CreatedBy
var createdBy: String? = null
@Column(nullable = true)
@LastModifiedBy
var updatedBy: String? = null
}
@Embeddable
data class Address(val addressLine1: String,
val addressLine2: String,
val addressLine3: String,
val city: String,
val state: String,
val zipCode: Int)
@Entity
data class Society(
@NotNull
val name: String,
@NotNull
val phone: String,
@Embedded
val address: Address
) : BaseEntity()
As far as I know, copy shouldn't created a new object but changes the existing with the new valued from the request. Why id being assigned a new UUID?
Thanks