Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Getting Started with MyBatis and Core Configuration

Tools May 17 2

Understanding ORM and MyBatis

Object-Relational Mapping (ORM) bridges the gap between object-oriented programming and relational databases by linking persistent data to entity objects. A schematic illustrates the correspondence between database tables and class fields, while another diagram depicts how data columns map to object properties.

MyBatis serves as a Java-based persistence framework that encapsulates JDBC. Developers concentrate on SQL statements rather than handling driver registration, connection creation, or statement management manually. Configuration occurs through XML or annotations, mapping dynamic parameters in SQL to Java objects. The framework executes SQL, converts results into Java objects, and returns them, employing ORM principles to abstract away low-level JDBC details.

Project Setup and Initial Steps

Development workflow:

  1. Include the MyBatis JAR dependency
  2. Create the target database table
  3. Write the corresponding entity class
  4. Prepare the mapper XML file
  5. Configure the MyBatis core XML
  6. Implement a test class

Environment preparation:

Add the required JAR files:

  • mysql-connector-java-5.1.37-bin.jar
  • mybatis-3.5.3.jar
  • log4j-1.2.17.jar

Define a student table, then build the entity:

public class Student {
    private Integer id;
    private String name;
    private Integer age;
    // getters and setters omitted
}

Mapper file (StudentMapper.xml):

<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="StudentMapper">
    <select id="fetchAllStudents" resultType="student">
        SELECT * FROM student
    </select>
</mapper>

Core configuration:

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <properties resource="jdbc.properties"/>
    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>
    <typeAliases>
        <typeAlias type="com.itheima.bean.Student" alias="student"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>

Test class example:

public class StudentControllerTest {
    private StudentService service = new StudentServiceImpl();

    @Test
    public void fetchAllStudents() {
        List<Student> students = service.fetchAllStudents();
        for (Student stu : students) {
            System.out.println(stu);
        }
    }
}

Key API Components

  • Resources (org.apache.ibatis.io.Resources): utility for loading configuration files from classpath, filesystem, or URLs.
  • SqlSessionFactoryBuilder (org.apache.ibatis.session.SqlSessionFactoryBuilder): constructs a SqlSessionFactory from an input stream.
String resource = "org/mybatis/builder/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
  • SqlSessionFactory: factory interface to open SqlSession instances.
  • SqlSession: provides methods to execute SQL statements, manage transactions, and retrieve mapper interfaces.

Mapper Configuration Details

Mapper files define the mapping between data and objects alongside the executable SQL.

Query examples:

<select id="getById" resultType="student">
    SELECT * FROM student WHERE id = #{id}
</select>

Insert example:

<insert id="save" parameterType="student">
    INSERT INTO student (name, age) VALUES (#{name}, #{age})
</insert>

Update example:

<update id="modify" parameterType="student">
    UPDATE student SET name = #{name}, age = #{age} WHERE id = #{id}
</update>

Delete example:

<delete id="remove" parameterType="int">
    DELETE FROM student WHERE id = #{id}
</delete>

Parameter Handling

  • Single parameter: MyBatis does not special-case the naming; any placeholder name works.
  • Multiple parameters: automatically wrapped into a map with keys param1, param2, etc., or positional indices 0, 1.
<select id="findByIdAndName" resultType="student">
    SELECT * FROM student WHERE id = #{0} AND name = #{1}
</select>
  • @Param annotation: clarifeis map keys.
List<Student> fetch(@Param("studentId") int id, @Param("studentName") String name);
<select id="fetch" resultType="student">
    SELECT * FROM student WHERE id = #{studentId} AND name = #{studentName}
</select>

#{} versus ${}

#{} uses prepared statements (safe). ${} concatenates values directly and risks SQL injection; suitable only for dynamic sorting (ORDER BY ${column}) with sanitized input.

Advanced Placeholder Attributes

Specify Java type, JDBC type, numeric scale, or mode for stored procedures:

#{email, javaType=String, jdbcType=NUMERIC}
#{height, javaType=double, jdbcType=NUMERIC, numericScale=2}

For nullable columns with databases like Oracle, explicitly set jdbcType:

<insert id="insertEmployee">
    insert into employees(EMPLOYEE_ID, LAST_NAME, EMAIL)
    values (#{id}, #{lastName}, #{email, jdbcType=NULL})
</insert>

MySQL tolerates the default handling, but Oracle requires this specificity.

Dynamic SQL Features

  • bind tag: binds an OGNL expression to a variable for later use.
  • discriminator and prefix/suffix helpers enable conditional mappings.
  • Bulk inserts for Oracle often require special XML constructs.
  • Built-in dynamic parameters (_parameter, _databaseId) simplify condition checks.

Map-based result query:

@MapKey("id")
public Map<Integer, BrandEntity> selectBrandMap(@Param("name") String name);
public Map<String, Object> selectSingleMap(String name);
<select id="selectBrandMap" resultType="java.util.Map">
    select * from pms_brand where name is not null
</select>
<select id="selectSingleMap" resultType="java.util.Map">
    select brand_id, name from pms_brand where name = #{name}
</select>

Core Configuration File

The core XML file declares environments, transaction managers, data sources, and mapper locations:

<configuration>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql:///db1" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>

External properties:

<properties resource="jdbc.properties"/>
<!-- Then reference as ${driver}, ${url}, ${username}, ${password} -->

Type aliases:

<typeAliases>
    <typeAlias type="com.itheima.bean.Student" alias="student"/>
    <!-- or scan a package <package name="com.itheima.bean"/> -->
</typeAliases>

Traditional Dao Layer Development

A three-tier architecture (controller → service → dao) structures the application. The traditional dao implementation invokes SqlSession methods directly, while a service layer orchestrates business logic.

LOG4J Integration

When debugging, logging the executed SQL, parameters, and results is invaluable. Configure LOG4J via the <settings> element (logImpl="log4j") and provide a log4j.properties file on the classpath.

Tags: mybatis

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.