Hi guys, what is the best practice for Spring Data...
# spring
j
Hi guys, what is the best practice for Spring Data JPA Entity written in Kotlin, using
data class
or
class
with
lateinit var
, those field in entity mostly don’t have default value
t
summary, regular class and
var
are better off than data classes, you can also have
Copy code
class Entity(
  var id: String, 
  ..., 
  var middleName: String? = null)
and I suggest to have preinitialized values at the bottom of the constructor list, so you can do
Entity(mandatoryOne, mandatoryTwo)
. if you have optional values in the middle of the parameter list, you would have to pass them as well
c
I would avoid data classes for Entities. This is a good starting point with some nice in-depth explanations: https://kotlinexpertise.com/hibernate-with-kotlin-spring-boot/
👍 1
l
for JPA, i usually use kotlin no-arg plugin + data class, so it will generate the no-argument default constructor for you without the burden to specify default values or make them lateinit var, and still give you all the benefit of data class. @MyNoArgConstructorAnnotation data class MyEntity( var id: Long, var name: String )
👍 1
l
@leodeng that blog post specifically says don't do that? "Do not use data classes to define your @Entity classes - JPA doesn't work well with the generated equals/hashCode functions."
👍 1
l
@Luis Munoz ah, i guess you’re right. i should not use data class but only the no-arg plugin to avoid specifying default values or using lateinit var. so the class should look like this:
Copy code
@MyNoArgConstructorAnnotation
class MyEntity(
 var id: Long,
 var name: String
) : BaseEntity(id)
and btw, myself prefer using mybatis and spring jdbc