我在我的Spring Boot应用程序中使用Kotlin,并且在使用Spring-JPA。我已经这样定义了我的实体
@Entity
@Table(name = "customer")
data class Customer(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
@NotNull
@Size(max = 255)
@Column
val firstName: String,
@NotNull
@Size(max = 255)
@Column
val lastName: String,
@NotNull
@Size(max = 255)
@Column
val email: String,
@NotNull
@Temporal(TemporalType.TIMESTAMP)
val createdAt: Date,
@Temporal(TemporalType.TIMESTAMP)
val updatedAt: Date? = null
)
@Repository
interface CustomerRepository : CrudRepository<Customer, Long> {
fun findById(id: Long): Customer
}
@Service
class MyService(private val repository: CustomerRepository) {
fun update(id: Long, firstName: String, lastName: String, email: String):Customer {
val customer = repository.findById(id)
return repository.save(customer.copy(firstName=firstName, lastName=lastName, email=email)) // the reason for the copy as the attributes are val
}
}
以上示例是处理更新的一种方法。另一种方法是使实体使用var
而不是val
,以便可以对其进行修改。在Kotlin中推荐的方法是什么?