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
Courseentity class to represent the course property (BooleancProperties, wheretruerepresents a required course andfalserepresents 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
CourseMapperto use the newcPropertiesfield - 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
BaseTypeHandlerclass 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
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).
Open the
Course.javafile located in theorg.lanqiao.pojopackage.Add a private Boolean field
cPropertiesto theCourseclass:
private Boolean cProperties;
- Generate the
getterandsettermethods for thecPropertiesfield:
public Boolean getcProperties() {
return cProperties;
}
public void setcProperties(Boolean cProperties) {
this.cProperties = cProperties;
}
- Update the constructor to include the
cPropertiesparameter:
public Course(int cNo, String cName, String teacher, Boolean cProperties) {
this.cNo = cNo;
this.cName = cName;
this.teacher = teacher;
this.cProperties = cProperties;
}
- Update the
toString()method to include thecPropertiesinformation:
@Override
public String toString() {
return "Course Number: " + this.cNo + "\tCourse Name: " + this.cName + "\tInstructor: " + this.teacher + "\tCompulsory Course: " + (this.cProperties ? "true" : "false");
}
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.
Create a new Java class
BooleanAndIntConverterin theorg.lanqiao.converterpackage.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).
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.
Open the
mybatis-config.xmlfile located in the root directory of the project.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.
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.
- Open the
CourseMapper.xmlfile and update the SQL statements to use thecPropertiesfield:
<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.
Update the Course Information
In this step, you will learn how to use the custom type handler to update the course information.
Open the
MyBatisTest.javafile.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.
- 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.
- 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.
- 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
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



