Last active
May 3, 2025 20:23
-
-
Save djkeh/44ad061d2b3476f4af54f65ab57b84ee to your computer and use it in GitHub Desktop.
코틀린 코드로 하는 엔티티 디자인 제안
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jakarta.persistence.Column | |
import jakarta.persistence.Entity | |
import jakarta.persistence.GeneratedValue | |
import jakarta.persistence.GenerationType | |
import jakarta.persistence.Id | |
import java.util.Objects | |
@Table( | |
uniqueConstraints = [ | |
UniqueConstraint(name = "udx_name_email", columnNames = ["name", "email"]), | |
], | |
indexes = [ | |
Index(name = "idx_created_at", columnList = "createdAt"), | |
Index(name = "idx_modified_at", columnList = "modifiedAt"), | |
] | |
) | |
@Entity | |
class Student( | |
@Column(nullable = false) var name: String, | |
@Column(nullable = false) var age: Int, | |
@Column(nullable = false) var email: String, | |
) : AuditingFields() { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
val id: Long = 0L | |
var phone: String? = null | |
var address: String? = null | |
override fun equals(other: Any?): Boolean { | |
if (this === other) return true | |
if (other !is Student) return false | |
return when (id) { | |
0L -> { | |
if (name != other.name) return false | |
if (age != other.age) return false | |
if (email != other.email) return false | |
if (phone != other.phone) return false | |
if (address != other.address) return false | |
true | |
} | |
else -> this.id == other.id | |
} | |
} | |
override fun hashCode(): Int = when (id) { | |
0L -> Objects.hash(name, age, email, phone, address) | |
else -> id.hashCode() | |
} | |
override fun toString(): String { | |
return "Student(" + | |
"id=$id, " + | |
"name='$name', " + | |
"age=$age, " + | |
"email='$email', " + | |
"phone=$phone, " + | |
"address=$address, " + | |
super.toString() + | |
")" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Column
으로 명시, 생성자에 파라미터로 요구id
는 자동으로 채워넣는 정보일 경우 생성자에서 제외null
을 제시하여 편의성을 끌어올림equals()
,hashcode()
구현toString()
구현AuditingFields
와 같이 메타 정보를 분리하였을 경우,super.toString()
추가id
가 없을 경우,id
를 toString 출력 가장 앞부분으로 직접 위치시킴