사용자 정의 속성으로 엔티티 확장

JavaBeginner
지금 연습하기

소개

이 프로젝트에서는 엔티티 클래스에 사용자 정의 속성을 추가하고 MyBatis 애플리케이션에서 Boolean 값과 Integer 값 간을 변환하기 위해 사용자 정의 타입 핸들러를 사용하는 방법을 배우게 됩니다.

👀 미리보기

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running org.lanqiao.test.MyBatisTest
Data deleted successfully
Data added successfully
[Course Number: 1       Course Name: Data Structures    Instructor: Zoe Compulsory Course: false, Course Number: 2      Course Name: JAVA       Instructor: William     Compulsory Course: true, Course Number: 3  Course Name: Python     Instructor: Olivia      Compulsory Course: true, Course Number: 4       Course Name: C++        Instructor: Brian  Compulsory Course: false, Course Number: 6      Course Name: C  Instructor: Lisa        Compulsory Course: true, Course Number: 8       Course Name: Artificial Intelligence       Instructor: Tom Compulsory Course: true]
Data updated successfully
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.119 sec
...
cNo     cName   teacher cProperties
1       Software Testing        Jack    1
2       JAVA    William 1
3       Python  Olivia  1
4       C++     Brian   0
6       C       Lisa    1
8       Artificial Intelligence Tom     1

🎯 과제

이 프로젝트에서는 다음을 배우게 됩니다:

  • 필수 과목 여부를 나타내기 위해 Course 엔티티 클래스에 속성 (Boolean cProperties, 여기서 true는 필수 과목, false는 선택 과목을 나타냄) 을 추가하는 방법
  • Boolean 값과 Integer 값 간을 변환하기 위해 사용자 정의 타입 핸들러를 생성하는 방법
  • MyBatis 설정 파일에 사용자 정의 타입 핸들러를 등록하는 방법
  • 새로운 cProperties 필드를 사용하도록 코스 테이블과 CourseMapper를 업데이트하는 방법
  • 데이터베이스에서 코스 정보를 업데이트하기 위해 사용자 정의 타입 핸들러를 사용하는 방법

🏆 성과

이 프로젝트를 완료하면 다음을 수행할 수 있습니다:

  • BaseTypeHandler 클래스를 확장하여 사용자 정의 타입 핸들러를 생성합니다.
  • MyBatis 설정 파일에 사용자 정의 타입 핸들러를 등록합니다.
  • 사용자 정의 필드를 사용하도록 데이터베이스 스키마와 해당 매퍼 파일을 업데이트합니다.
  • 사용자 정의 타입 핸들러를 사용하여 데이터베이스에서 데이터를 업데이트합니다.

엔티티 클래스에 Course 속성 추가

이 단계에서는 코스 속성 (Boolean cProperties, 여기서 true는 필수 과목, false는 선택 과목을 나타냄) 을 나타내기 위해 Course.java 엔티티 클래스에 속성을 추가하는 방법을 배우게 됩니다.

  1. org.lanqiao.pojo 패키지에 있는 Course.java 파일을 엽니다.

  2. Course 클래스에 private Boolean 필드 cProperties를 추가합니다:

private Boolean cProperties;
  1. cProperties 필드에 대한 gettersetter 메서드를 생성합니다:
public Boolean getcProperties() {
    return cProperties;
}

public void setcProperties(Boolean cProperties) {
    this.cProperties = cProperties;
}
  1. 생성자를 업데이트하여 cProperties 매개변수를 포함합니다:
public Course(int cNo, String cName, String teacher, Boolean cProperties) {
    this.cNo = cNo;
    this.cName = cName;
    this.teacher = teacher;
    this.cProperties = cProperties;
}
  1. toString() 메서드를 업데이트하여 cProperties 정보를 포함합니다:
@Override
public String toString() {
    return "Course Number: " + this.cNo + "\tCourse Name: " + this.cName + "\tInstructor: " + this.teacher + "\tCompulsory Course: " + (this.cProperties ? "true" : "false");
}
✨ 솔루션 확인 및 연습

사용자 정의 타입 핸들러 생성

이 단계에서는 Boolean 값과 Integer 값 간을 변환하기 위해 사용자 정의 타입 핸들러를 생성하는 방법을 배우게 됩니다.

  1. org.lanqiao.converter 패키지에 새로운 Java 클래스 BooleanAndIntConverter를 생성합니다.

  2. BaseTypeHandler<Boolean> 클래스를 확장하고 다음 메서드를 구현합니다:

public class BooleanAndIntConverter extends BaseTypeHandler<Boolean> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Boolean aBoolean, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i, aBoolean ? 1 : 0);
    }

    @Override
    public Boolean getNullableResult(ResultSet resultSet, String s) throws SQLException {
        int result = resultSet.getInt(s);
        return result == 1;
    }

    @Override
    public Boolean getNullableResult(ResultSet resultSet, int i) throws SQLException {
        int result = resultSet.getInt(i);
        return result == 1;
    }

    @Override
    public Boolean getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        int result = callableStatement.getInt(i);
        return result == 1;
    }
}

setNonNullParameter() 메서드는 Boolean 값을 Integer 값으로 변환합니다 ( true는 1, false는 0). getNullableResult() 메서드는 Integer 값을 Boolean 값으로 변환합니다 ( true는 1, false는 0).

✨ 솔루션 확인 및 연습

사용자 정의 타입 핸들러 등록

이 단계에서는 MyBatis 설정 파일 mybatis-config.xml에 사용자 정의 타입 핸들러를 등록하는 방법을 배우게 됩니다.

  1. 프로젝트의 루트 디렉토리에 있는 mybatis-config.xml 파일을 엽니다.

  2. 사용자 정의 타입 핸들러를 등록하기 위해 다음 설정을 추가합니다:

<typeHandlers>
    <typeHandler handler="org.lanqiao.converter.BooleanAndIntConverter"/>
</typeHandlers>

이 설정은 MyBatis 에게 BooleanAndIntConverter 클래스를 사용하여 Boolean 값과 Integer 값 간의 변환을 처리하도록 지시합니다.

✨ 솔루션 확인 및 연습

강좌 테이블 및 Mapper 업데이트

이 단계에서는 새로운 cProperties 필드를 사용하도록 course 테이블과 CourseMapper를 업데이트하는 방법을 배우게 됩니다.

  1. CourseMapper.xml 파일을 열고 SQL 문을 업데이트하여 cProperties 필드를 사용합니다:
<insert id="insertCourse" parameterType="org.lanqiao.pojo.Course">
    insert into course(cNo,cName,teacher,cProperties)
    values(#{cNo},#{cName},#{teacher},#{cProperties})
</insert>

<update id="updateCourse" parameterType="org.lanqiao.pojo.Course">
    update course set cName=#{cName},teacher=#{teacher},cProperties=#{cProperties}
    where cNo=#{cNo}
</update>

insertCourseupdateCourse 문은 이제 cProperties 필드를 포함합니다.

✨ 솔루션 확인 및 연습

강좌 정보 업데이트

이 단계에서는 사용자 정의 타입 핸들러를 사용하여 course 정보를 업데이트하는 방법을 배우게 됩니다.

  1. MyBatisTest.java 파일을 엽니다.

  2. testUpd() 메서드에서, course 번호가 1 인 course 의 정보를 업데이트합니다:

@Test
public void testUpd() throws IOException {
    CourseMapper cMapper = session.getMapper(CourseMapper.class);

    Course course = new Course(1, "Software Testing", "Jack", true);

    int i = cMapper.updateCourse(course);

    session.commit();

    System.out.println((i != 0 ? "Data updated successfully" : "Failed to update data"));

    session.close();
}

cProperties 필드는 true로 설정되어 필수 course 를 나타냅니다.

  1. testIns() 메서드에서, course 번호가 8 인 새로운 course 를 삽입합니다:
@Test
public void testIns() throws IOException {
    CourseMapper cMapper = session.getMapper(CourseMapper.class);

    Course course = new Course(8, "Artificial Intelligence", "Tom", true);

    int i = cMapper.insertCourse(course);

    session.commit();

    System.out.println((i != 0 ? "Data added successfully" : "Failed to add data"));

    session.close();
}

cProperties 필드는 true로 설정되어 필수 course 를 나타냅니다.

  1. testDEl() 메서드에서, course 번호가 7 인 course 를 삭제합니다:
@Test
public void testDEl() throws IOException {
    CourseMapper cMapper = session.getMapper(CourseMapper.class);

    int i = cMapper.deleteCourse(7);

    session.commit();

    System.out.println((i != 0 ? "Data deleted successfully" : "Failed to delete data"));

    session.close();
}

이 단계를 완료하면, 엔티티 클래스에 course 속성을 성공적으로 추가하고, Boolean 값과 Integer 값 간의 변환을 위한 사용자 정의 타입 핸들러를 생성했으며, 사용자 정의 타입 핸들러를 사용하여 데이터베이스에서 course 정보를 업데이트했습니다.

  1. 애플리케이션을 테스트합니다.
cd ~/project/MyBatisCourseDemo02/
mvn test
echo "USE MyBatisDemo; SELECT * FROM course;" | mysql -u root > course_data.txt
cat course_data.txt

출력은 다음과 같아야 합니다:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running org.lanqiao.test.MyBatisTest
Data deleted successfully
Data added successfully
[Course Number: 1       Course Name: Data Structures    Instructor: Zoe Compulsory Course: false, Course Number: 2      Course Name: JAVA       Instructor: William     Compulsory Course: true, Course Number: 3  Course Name: Python     Instructor: Olivia      Compulsory Course: true, Course Number: 4       Course Name: C++        Instructor: Brian  Compulsory Course: false, Course Number: 6      Course Name: C  Instructor: Lisa        Compulsory Course: true, Course Number: 8       Course Name: Artificial Intelligence       Instructor: Tom Compulsory Course: true]
Data updated successfully
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.119 sec
...
cNo     cName   teacher cProperties
1       Software Testing        Jack    1
2       JAVA    William 1
3       Python  Olivia  1
4       C++     Brian   0
6       C       Lisa    1
8       Artificial Intelligence Tom     1
✨ 솔루션 확인 및 연습

요약

축하합니다! 이 프로젝트를 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 기술을 향상시킬 수 있습니다.