java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Mybatis优化检索

Mybatis优化检索的方法详解

作者:兔子队列

MyBatis是一款优秀的基于Java的持久层框架,它可以将 SQL 语句和数据库中的记录映射成为 Java 对象,并且支持灵活的 SQL 查询语句,在Mybatis中,可以使用动态SQL来灵活构造SQL语句,从而满足各种不同的检索需求,本文介绍Mybatis如何优化检索,需要的朋友可以参考下

1.SQL 映射

CREATE TABLE user (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255),
    email VARCHAR(255)
);

CREATE TABLE role (
    id INT AUTO_INCREMENT PRIMARY KEY,
    role_name VARCHAR(255)
);

CREATE TABLE user_role (
    user_id INT,
    role_id INT,
    FOREIGN KEY (user_id) REFERENCES user(id),
    FOREIGN KEY (role_id) REFERENCES role(id)
);
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
    <select id="selectUserById" resultType="com.example.model.User">
        SELECT * FROM user WHERE id = #{id}
    </select>

    <resultMap id="userRoleMap" type="com.example.model.User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <collection property="roles" ofType="com.example.model.Role">
            <id column="role_id" property="id"/>
            <result column="role_name" property="roleName"/>
        </collection>
    </resultMap>

    <select id="selectUserWithRoles" resultMap="userRoleMap">
        SELECT u.id, u.username, r.id AS role_id, r.role_name
        FROM user u
        LEFT JOIN user_role ur ON u.id = ur.user_id
        LEFT JOIN role r ON ur.role_id = r.id
        WHERE u.id = #{id}
    </select>
</mapper>

2.结果映射

<!-- Mapper XML 配置 -->
<mapper namespace="com.example.mapper.UserMapper">
    <!-- 定义结果映射 -->
    <resultMap id="BaseResultMap" type="com.example.model.User">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="email" property="email" />
    </resultMap>

    <!-- 使用定义好的结果映射查询用户 -->
    <select id="selectUserById" resultMap="BaseResultMap">
        SELECT id, username, email FROM user WHERE id = #{id}
    </select>
</mapper>

3.延迟加载

<settings>
    <setting name="lazyLoadingEnabled" value="true"/>
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>

4.缓存支持

一级缓存(Session Cache)

二级缓存(Global Cache)

示例配置

<!-- 开启当前 Mapper 的二级缓存 -->
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>

缓存策略

5.批量操作优化

6.动态 SQL

<!-- Mapper XML 文件中的示例 -->
<mapper namespace="com.example.mapper.UserMapper">
    <!-- 动态生成 SELECT 查询 -->
    <select id="findUsersByConditions" resultType="User">
        <where>
            <if test="username != null">
                AND username = #{username}
            </if>
            <if test="email != null">
                AND email = #{email}
            </if>
        </where>
    </select>

    <!-- 动态生成 UPDATE 查询 -->
    <update id="updateUser">
        UPDATE users
        <set>
            <if test="username != null">
                username = #{username},
            </if>
            <if test="email != null">
                email = #{email},
            </if>
        </set>
        WHERE id = #{id}
    </update>

    <!-- 使用 foreach 生成 IN 子句 -->
    <select id="findUsersByIds" resultType="User">
        SELECT * FROM users
        WHERE id IN
        <foreach item="id" collection="ids" open="(" separator="," close=")">
            #{id}
        </foreach>
    </select>
</mapper>

7.插件和拦截器

以上就是Mybatis优化检索的方法详解的详细内容,更多关于Mybatis优化检索的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文