실무 프로젝트로 배우는 Kotlin & Spring/자바 프로젝트(ToDo프로젝트) 코틀린으로 리팩토링 하기

도메인(Domain, Repository) 리펙토링

webmaster 2022. 11. 5. 18:29
728x90

Todo 도메인 

JavaCode

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder
@Entity
@Table(name = "todos")
public class Todo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "title")
    private String title;

    @Lob
    @Column(name = "description")
    private String description;

    @Column(name = "done")
    private Boolean done;

    @Column(name = "created_at")
    private LocalDateTime createdAt;

    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    public void update(String title, String description, Boolean done) {
        this.title = title;
        this.description = description;
        this.done = done != null && done;
        this.updatedAt = LocalDateTime.now();
    }
}

KotlinCode

@Entity
@Table(name = "todos")
class Todo(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long? = 0,

    @Column(name = "title")
    var title: String,

    @Lob
    @Column(name = "description")
    var description: String,

    @Column(name = "done")
    var done: Boolean,

    @Column(name = "created_at")
    var createdAt: LocalDateTime,

    @Column(name = "updated_at")
    var updatedAt: LocalDateTime? = null
) {

    fun update(title: String, description: String, done: Boolean) {
        this.title = title
        this.description = description
        this.done = done
        this.updatedAt = LocalDateTime.now()
    }
}
  • JPA를 사용하면 어쩔 수 없이 Emutable 하게 객체를 사용할 수밖에 없다(val 키워드 -> var 변경)
  • SpringDataJpa만 고집하지 말고, 다양한 프레임워크(exposed, SpringDataJdbc)등을 활용하면 코틀린의 장점을 유지하고 코드를 작성할 수 있다.

Repository

JavaCode

public interface TodoRepository extends JpaRepository<Todo, Long> {

    Optional<List<Todo>> findAllByDoneIsFalseOrderByIdDesc();
}

KotlinCode

interface TodoRepository : JpaRepository<Todo, Long> {
    fun findAllByDoneIsFalseOrderByIdDesc(): List<Todo>?
}
  • 더이상 Optional이 아닌 ?연산자를 통해 널 가능성 유무를 체크하면 된다.
728x90