Quick Start

Continuing from the previous section where we completed basic MyBatis configuration without relying on Spring. Here we supplement the CRUD operations.

Insert Data

<insert id="insert" parameterType="icu.wzk.model.UserInfo">
    INSERT INTO
        user_info
    VALUES(0, #{username}, #{password}, #{age})
</insert>

Java Code:

public class WzkIcu02 {
    public static void main(String[] args) throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserInfo userInfo = UserInfo
                .builder()
                .username("wzk2")
                .password("icu2")
                .age(25)
                .build();
        sqlSession.insert("icu.wzk.mapper.UserInfoMapper.insert", userInfo);
        sqlSession.commit();
        sqlSession.close();
    }
}

Important Notes:

  • Insert statements use the INSERT tag
  • Use the parameterType attribute in the mapping file to specify the data type to insert
  • SQL statements use #{} to reference entity property values
  • The API for insert operations is sqlSession.insert(“namespace.id”, entity object)
  • Insert operations involve database data changes, so you must explicitly commit the transaction using sqlSession.commit()

Update Data

<update id="update" parameterType="icu.wzk.model.UserInfo">
    UPDATE
        user_info
    SET
        username=#{username}, password=#{password}, age=#{age}
    WHERE
        id=#{id}
</update>

Java Code:

public class WzkIcu03 {
    public static void main(String[] args) throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserInfo userInfo = UserInfo
                .builder()
                .id(2L)
                .username("wzk2-update")
                .password("icu2-update")
                .age(25)
                .build();
        sqlSession.update("icu.wzk.mapper.UserInfoMapper.update", userInfo);
        sqlSession.commit();
        sqlSession.close();
    }
}

Important Notes:

  • Update statements use the update tag
  • The operation is sqlSession.update(“namespace.id”, entity object)

Delete Data

<delete id="delete" parameterType="icu.wzk.model.UserInfo">
  DELETE FROM
      user_info
  WHERE
      id=#{id}
</delete>

Java Code:

public class WzkIcu04 {
    public static void main(String[] args) throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserInfo userInfo = UserInfo
                .builder()
                .id(2L)
                .build();
        sqlSession.update("icu.wzk.mapper.UserInfoMapper.delete", userInfo);
        sqlSession.commit();
        sqlSession.close();
    }
}

Important Notes:

  • Delete uses the delete tag
  • The operation is sqlSession.delete(“namespace.id”, entity object)

Mapping Overview

MyBatis mapping is primarily implemented through XML mapping files and annotations, mapping database table structures to Java objects. MyBatis mapping provides flexible SQL control through XML and annotations, suitable for scenarios requiring manual SQL writing. XML mapping files are better for complex logic, while annotations are more suitable for simple scenarios. Mastering MyBatis mapping capabilities enables efficient data persistence operations while maintaining code maintainability and readability.

Core Concepts

XML Mapping File

XML is the core component of MyBatis mapping, typically existing as .xml files corresponding to mapped Java classes. It contains SQL statements, mapping relationships, and other configurations.

Annotation-Based Approach

Through Java annotations, SQL is directly embedded into the Mapper interface, suitable for simple CRUD operations.

Important Tags

  • mapper: Top-level tag that declares the file as a Mapper file, with namespace corresponding to the fully qualified name of the Java interface.
  • resultMap: Defines custom mapping between objects and database fields, supporting complex mappings.
  • select: Defines query statements, mapping results through resultType or resultMap.
  • insert: Defines insert statements, using #{} placeholders to pass parameters.
  • update: Defines update statements.
  • delete: Defines delete statements.

Common Configuration

environment

Database environment configuration supporting different environments. There are two types of transaction managers:

JDBC: JDBC transaction management directly uses Java database connection (JDBC) transaction control mechanisms. It manages transaction scope through the Connection object obtained from the data source, requiring developers to explicitly call connection.commit() to commit transactions or connection.rollback() to roll back transactions.

MANAGED: MANAGED transaction management completely delegates transaction management to the container (such as J2EE application server). It does not actively commit or roll back transactions; instead, the container automatically manages the transaction lifecycle based on the context.

DataSource

There are three different datasource configuration types:

  1. UNPOOLED (Unpooled DataSource): Creates a new connection for each database request and closes it immediately after use. Suitable for small applications or testing environments.

  2. POOLED (Pooled DataSource): Maintains a connection pool, pre-creating and caching multiple connections. Suitable for high-concurrency applications in production environments.

  3. JNDI (Java Naming and Directory Interface DataSource): Uses JNDI services to look up and use container-managed data sources, with connection management unified by the application server. Suitable for EJB or application server environments.

mapper

The mapper’s role is to load mappings, with several loading methods:

Using resource references relative to the classpath:

<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>

Using fully qualified resource locators (URL):

<mapper url="file:///var/mappers/AuthorMapper.xml"/>

Using the fully qualified class name of the mapper interface implementation class:

<mapper class="org.mybatis.builder.AuthorMapper"/>

Registering all mapper interface implementations in a package as mappers:

<package name="org.mybatis.builder"/>