Extending Entity with Custom Properties

JavaJavaBeginner
Practice Now

Introduction

In this project, you will learn how to add custom properties to an entity class and use a custom type handler to convert between Boolean and Integer values in a MyBatis application.

👀 Preview

-------------------------------------------------------
 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

ðŸŽŊ Tasks

In this project, you will learn:

  • How to add a property to the Course entity class to represent the course property (Boolean cProperties, where true represents a required course and false represents an elective course)
  • How to create a custom type handler to convert between Boolean and Integer values
  • How to register the custom type handler in the MyBatis configuration file
  • How to update the course table and the CourseMapper to use the new cProperties field
  • How to use the custom type handler to update the course information in the database

🏆 Achievements

After completing this project, you will be able to:

  • Extend the BaseTypeHandler class to create a custom type handler
  • Register a custom type handler in the MyBatis configuration file
  • Update the database schema and the corresponding mapper file to use a custom field
  • Use the custom type handler to update data in the database

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) mysql(("`MySQL`")) -.-> mysql/BasicKeywordsandStatementsGroup(["`Basic Keywords and Statements`"]) java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inheritance("`Inheritance`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") mysql/BasicKeywordsandStatementsGroup -.-> mysql/insert("`Data Insertion`") mysql/BasicKeywordsandStatementsGroup -.-> mysql/update("`Data Update`") subgraph Lab Skills java/class_methods -.-> lab-300358{{"`Extending Entity with Custom Properties`"}} java/inheritance -.-> lab-300358{{"`Extending Entity with Custom Properties`"}} java/data_types -.-> lab-300358{{"`Extending Entity with Custom Properties`"}} mysql/insert -.-> lab-300358{{"`Extending Entity with Custom Properties`"}} mysql/update -.-> lab-300358{{"`Extending Entity with Custom Properties`"}} end

Add Course Property to the Entity Class

In this step, you will learn how to add a property to the entity class Course.java to represent the course property (Boolean cProperties, where true represents a required course and false represents an elective course).

  1. Open the Course.java file located in the org.lanqiao.pojo package.

  2. Add a private Boolean field cProperties to the Course class:

private Boolean cProperties;
  1. Generate the getter and setter methods for the cProperties field:
public Boolean getcProperties() {
    return cProperties;
}

public void setcProperties(Boolean cProperties) {
    this.cProperties = cProperties;
}
  1. Update the constructor to include the cProperties parameter:
public Course(int cNo, String cName, String teacher, Boolean cProperties) {
    this.cNo = cNo;
    this.cName = cName;
    this.teacher = teacher;
    this.cProperties = cProperties;
}
  1. Update the toString() method to include the cProperties information:
@Override
public String toString() {
    return "Course Number: " + this.cNo + "\tCourse Name: " + this.cName + "\tInstructor: " + this.teacher + "\tCompulsory Course: " + (this.cProperties ? "true" : "false");
}
âœĻ Check Solution and Practice

Create a Custom Type Handler

In this step, you will learn how to create a custom type handler to convert between Boolean and Integer values.

  1. Create a new Java class BooleanAndIntConverter in the org.lanqiao.converter package.

  2. Extend the BaseTypeHandler<Boolean> class and implement the following methods:

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;
    }
}

The setNonNullParameter() method converts a Boolean value to an Integer value (1 for true, 0 for false), and the getNullableResult() methods convert an Integer value to a Boolean value (1 for true, 0 for false).

âœĻ Check Solution and Practice

Register the Custom Type Handler

In this step, you will learn how to register the custom type handler in the MyBatis configuration file mybatis-config.xml.

  1. Open the mybatis-config.xml file located in the root directory of the project.

  2. Add the following configuration to register the custom type handler:

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

This configuration tells MyBatis to use the BooleanAndIntConverter class to handle the conversion between Boolean and Integer values.

âœĻ Check Solution and Practice

Update the Course Table and Mapper

In this step, you will learn how to update the course table and the CourseMapper to use the new cProperties field.

  1. Open the CourseMapper.xml file and update the SQL statements to use the cProperties field:
<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>

The insertCourse and updateCourse statements now include the cProperties field.

âœĻ Check Solution and Practice

Update the Course Information

In this step, you will learn how to use the custom type handler to update the course information.

  1. Open the MyBatisTest.java file.

  2. In the testUpd() method, update the course information for the course with course number 1:

@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();
}

The cProperties field is set to true, which represents a required course.

  1. In the testIns() method, insert a new course with course number 8:
@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();
}

The cProperties field is set to true, which represents a required course.

  1. In the testDEl() method, delete the course with course number 7:
@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();
}

After completing these steps, you have successfully added a course property to the entity class, created a custom type handler to convert between Boolean and Integer values, and used the custom type handler to update the course information in the database.

  1. Test the application.
cd ~/project/MyBatisCourseDemo02/
mvn test
echo "USE MyBatisDemo; SELECT * FROM course;" | mysql -u root > course_data.txt
cat course_data.txt

The output should look like this:

-------------------------------------------------------
 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
âœĻ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Java Tutorials you may like