Gokul
07/23/2018, 5:51 AMEntity to DTO conversion
.
I created a data class
for the entity
and added a toDto
method on it. But here the Entity
is aware of the DTO, which isn't really required for the entity. It works fine. But I am not sure if this is the right way of doing it? Any thoughts? 🙏
A simpler version of my code is:
//Person DTO
data class PersonDto (
val name: String
)
//Person Entity
@Entity
@Table(name = "persons")
data class Person(
@Id
val id: Integer,
@Column
val firstName: String,
@Column
val lastName: String
)
{
internal fun toDto(): PersonDto = PersonDto(
name = "${this.firstName} ${this.lastName}"
)
}
dave
07/23/2018, 7:16 AMnfrankel
07/23/2018, 7:23 AMGokul
07/23/2018, 11:52 AMnfrankel
07/23/2018, 12:25 PMTodor Atanasov
07/23/2018, 12:39 PMnfrankel
07/23/2018, 12:43 PMandyb
07/23/2018, 1:57 PMTodor Atanasov
07/23/2018, 2:07 PMnfrankel
07/23/2018, 2:14 PMGokul
07/23/2018, 11:58 PMthin models
.dmulligan
07/25/2018, 4:29 PMUser
, which has a list of previous passwords. This User
is used in may other classed to track who created or updated that object. As a result, whenever we transfer those other objects over and back between DTOs we need to populate the lazy password history. We got around this by creating a UserSummary
, but it was still not ideal.
2) Parent child relationships were never simple. We got around this used init
blocks like before, but again I was never happy with them as any simple update to the user would result in the password history getting fetched from the database.
@Entity(name = "users")
data class User(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: PersistanceId = -1,
@OneToMany(mappedBy = "user", cascade = [CascadeType.ALL], orphanRemoval = true)
@OrderBy("id DESC")
val passwordHistory: List<Password> = mutableListOf(),
) {
constructor(
user: User,
passwordHistory: List<PersistedPassword>,
) : this( ... )
init {
passwordHistory.forEach { it.user = this }
}
fun toUserDto() = UserDto(...)
}