likes
comments
collection
share

Mybatis是如何操作动态sql的,又如何与spring集成

作者站长头像
站长
· 阅读数 16

@[TOC] Mybatis是如何操作动态sql的,又如何与spring集成

MyBatis的基本架构

MyBatis由三个主要组件组成:SqlSessionFactory,SqlSession和Mapper。SqlSessionFactory是创建SqlSession的工厂,SqlSession是与数据库交互的主要接口,Mapper是将Java方法调用转换为SQL语句的接口。

1. SqlSessionFactory:

SqlSessionFactory是MyBatis初始化的入口,是创建SqlSession的工厂。它通过加载mybatis-config.xml配置文件和Mapper映射文件来初始化MyBatis运行环境,并提供了创建SqlSession对象的方法。SqlSessionFactory的主要作用是管理数据库连接池和缓存。

以下是一个SqlSessionFactory的示例代码:

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

2. SqlSession:

SqlSession是与数据库交互的主要接口,它提供了多种操作数据库的方法,如selectOne、selectList、insert、update、delete等。SqlSession的生命周期是比较短暂的,每个请求都应该使用一个新的SqlSession对象。

以下是一个SqlSession的示例代码:

SqlSession sqlSession = sqlSessionFactory.openSession();
try {
    User user = sqlSession.selectOne("com.example.mapper.UserMapper.selectUserById", 1);
    System.out.println(user);
} finally {
    sqlSession.close();
}

3. Mapper:

Mapper是将Java方法调用转换为SQL语句的接口。它提供了一组方法,可以将Java方法映射成对应的SQL语句,并且通过SqlSession执行SQL语句。Mapper通常定义在一个接口中,并且需要编写对应的Mapper映射文件。

以下是一个Mapper的示例代码:

public interface UserMapper {
    User selectUserById(Integer id);
}

对应的Mapper映射文件userMapper.xml:

<mapper namespace="com.example.mapper.UserMapper">
    <select id="selectUserById" parameterType="java.lang.Integer" resultType="com.example.entity.User">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>

MyBatis的配置文件

MyBatis使用XML格式的配置文件来配置SqlSessionFactory和Mapper。配置文件包含数据库连接信息、事务管理器、映射文件位置等信息。 MyBatis的配置文件是一个XML格式的文件,它用于配置SqlSessionFactory和Mapper等组件。下面是对MyBatis配置文件中常见概念的详细解释。

1. configuration元素:

configuration元素是所有其他元素的根元素。它包含了所有需要装配的组件的信息。

2. properties元素:

properties元素用来定义属性。可以在属性文件、环境变量或JVM系统属性中配置属性值,并通过${}语法引用它们。

例如:

<properties resource="jdbc.properties">
    <property name="username" value="root"/>
    <property name="password" value="${my.password}"/>
</properties>

3. typeAliases元素:

typeAliases元素用来设置Java类型和数据库列类型之间的映射关系。可以通过别名来减少XML配置文件中的重复代码。

例如:

<typeAliases>
    <typeAlias alias="int" type="java.lang.Integer"/>
    <typeAlias alias="user" type="com.example.entity.User"/>
</typeAliases>

4. environments元素:

environments元素用来定义不同的数据库环境。每个环境都包含一个数据源和事务管理器。

例如:

<environments default="dev">
    <environment id="dev">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </dataSource>
    </environment>
</environments>

5. mappers元素:

mappers元素用来定义Mapper映射文件位置。可以使用相对路径或classpath路径来指定位置。

例如:

<mappers>
    <mapper resource="com/example/mapper/UserMapper.xml"/>
    <mapper class="com.example.mapper.OrderMapper"/>
</mappers>

以上就是MyBatis配置文件中常见概念的详细解释。通过配置文件,我们可以配置数据库连接信息、事务管理器、映射文件位置等信息,从而初始化SqlSessionFactory并创建SqlSession对象。

MyBatis的动态SQL

MyBatis支持动态SQL,可以根据需要构建不同的SQL语句。动态SQL包括if、choose、where、foreach等标签。 MyBatis支持动态SQL,可以根据需要构建不同的SQL语句。以下是MyBatis中常用的动态SQL标签及其作用:

1. if元素:

if元素用于条件判断,类似于Java中的if语句。它可以嵌套在其他标签之内,用于构建复杂的SQL语句。

例如:

<select id="findUser" resultType="User">
  SELECT * FROM user
  <where>
    <if test="name != null and name != ''">
      AND name = #{name}
    </if>
    <if test="age != null">
      AND age = #{age}
    </if>
  </where>
</select>

2. choose、when、otherwise元素:

choose元素相当于Java中的switch语句,它包含多个when和一个otherwise元素。当满足某个条件时,执行对应的when元素中的SQL语句;否则,执行otherwise元素中的SQL语句。

例如:

<select id="findUser" resultType="User">
  SELECT * FROM user
  <where>
    <choose>
      <when test="name != null and name != ''">
        AND name = #{name}
      </when>
      <when test="age != null">
        AND age = #{age}
      </when>
      <otherwise>
        AND sex = #{sex}
      </otherwise>
    </choose>
  </where>
</select>

3. where元素:

where元素用于拼接WHERE子句,它会自动去掉第一个AND或OR关键字。如果条件都没有满足,则WHERE子句被省略。

例如:

<select id="findUser" resultType="User">
  SELECT * FROM user
  <where>
    <if test="name != null and name != ''">
      AND name = #{name}
    </if>
    <if test="age != null">
      AND age = #{age}
    </if>
  </where>
</select>

4. foreach元素:

foreach元素用于循环遍历集合,生成对应的SQL语句。它可以循环遍历数组、List、Set、Map等类型的集合。

例如:

<select id="getUsersByIds" resultType="User">
  SELECT * FROM user
  WHERE id IN
  <foreach collection="ids" item="id" open="(" separator="," close=")">
    #{id}
  </foreach>
</select>

以上就是MyBatis中常用的动态SQL标签及其作用。通过使用动态SQL标签,我们可以根据不同的条件构建不同的SQL语句,使得SQL语句更加灵活和可重用。

MyBatis的缓存机制

MyBatis带有一级缓存和二级缓存。一级缓存默认开启且不能关闭,只能在同一SqlSession内共享。二级缓存需要手动开启并配置,可跨SqlSession共享。 MyBatis的缓存机制主要包括一级缓存和二级缓存。

1. 一级缓存

一级缓存是SqlSession级别的缓存,它默认是开启的且无法关闭。当调用SqlSession的查询方法时,首先会检查缓存中是否存在相同的SQL语句以及参数,如果有则直接返回缓存中的结果,否则会执行SQL语句并将结果放入缓存中。

以下是一级缓存的示例代码:

SqlSession sqlSession = sqlSessionFactory.openSession();
try {
    User user1 = sqlSession.selectOne("com.example.mapper.UserMapper.selectUserById", 1);
    User user2 = sqlSession.selectOne("com.example.mapper.UserMapper.selectUserById", 1);
} finally {
    sqlSession.close();
}

在以上代码中,第一次执行查询时会从数据库中获取数据,并将结果放入缓存中。第二次执行查询时则直接从缓存中获取数据,不再向数据库中发送查询请求。

注意:一级缓存只在同一个SqlSession内共享。

2. 二级缓存

二级缓存是Mapper级别的缓存,它需要手动开启并配置。当开启二级缓存后,在同一个应用程序中的多个SqlSession之间可以共享缓存结果,从而减少数据库访问次数,提升系统性能。

以下是二级缓存的示例代码:

  1. 配置Mapper映射文件开启二级缓存:
<mapper namespace="com.example.mapper.UserMapper" >
  <cache eviction="LRU" flushInterval="60000" size="1024" readOnly="true"/>
  <select id="selectUserById" resultType="User" useCache="true">
    SELECT * FROM user WHERE id = #{id}
  </select>
</mapper>
  1. 配置mybatis-config.xml文件开启二级缓存:
<configuration>
  <settings>
    <setting name="cacheEnabled" value="true"/>
  </settings>
</configuration>

注意:在配置二级缓存时需要注意缓存的清空,否则可能会出现脏读数据的情况。

以上就是MyBatis中的缓存机制。了解和掌握它们可以帮助我们更好地使用MyBatis,并提高系统性能。

MyBatis的插件机制

MyBatis提供插件机制,允许在执行SQL语句时添加额外的逻辑处理。插件可以在StatementHandler、ResultSetHandler、ParameterHandler和Executor层面上拦截方法调用,对其进行增强。 MyBatis的插件机制可以在执行SQL语句时添加额外的逻辑处理,插件可以在四个层面上进行拦截和增强:StatementHandler、ResultSetHandler、ParameterHandler和Executor。

1. Interceptor接口

插件需要实现MyBatis提供的Interceptor接口,并覆盖其中的intercept方法。intercept方法中会传入一个Invocation对象,它包含了当前被拦截的方法、方法参数以及目标对象等信息,可以在该方法中对这些信息进行处理。

以下是Interceptor接口的示例代码:

public interface Interceptor {
    Object intercept(Invocation invocation) throws Throwable;

    default Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    void setProperties(Properties properties);
}

2. Plugin类

MyBatis提供了Plugin类来包装插件和目标对象,并返回代理对象,从而实现拦截器的功能。

以下是Plugin类的示例代码:

public class MyPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 插件逻辑处理
        return invocation.proceed();
    }

    @Override
    public void setProperties(Properties properties) {}

    public static Object wrap(Object target, MyPlugin myPlugin) {
        return Plugin.wrap(target, myPlugin);
    }
}

3. 配置插件

在mybatis-config.xml配置文件中,需要配置插件的相关信息,如插件类名、插件属性等。

例如:

<plugins>
  <plugin interceptor="com.example.MyPlugin">
      <property name="username" value="root"/>
  </plugin>
</plugins>

以上就是MyBatis的插件机制。通过实现Interceptor接口和使用Plugin类,我们可以在MyBatis执行SQL语句时添加额外的逻辑处理,从而提高系统的可扩展性和灵活性。

MyBatis的注解配置

MyBatis支持通过注解来配置Mapper接口。@Select、@Insert、@Update、@Delete等注解可以将Java方法映射为SQL语句。 MyBatis支持通过注解来配置Mapper接口,使用注解可以使代码更加简洁易懂。以下是MyBatis中常用的注解及其作用:

1. @Select

@Select注解用于将Java方法映射为SELECT语句。

例如:

@Select("SELECT * FROM user WHERE id = #{id}")
User selectUserById(int id);

2. @Insert

@Insert注解用于将Java方法映射为INSERT语句。

例如:

@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
int insertUser(User user);

3. @Update

@Update注解用于将Java方法映射为UPDATE语句。

例如:

@Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")
int updateUser(User user);

4. @Delete

@Delete注解用于将Java方法映射为DELETE语句。

例如:

@Delete("DELETE FROM user WHERE id = #{id}")
int deleteUser(int id);

5. @Results

@Results注解用于指定查询结果集与Java对象之间的映射关系。

例如:

@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
    @Result(column = "user_id", property = "userId"),
    @Result(column = "user_name", property = "userName"),
    @Result(column = "user_age", property = "userAge")
})
User selectUserById(int id);

以上就是MyBatis中常用的注解及其作用。通过使用注解,我们可以将Java方法直接映射为SQL语句,使代码更加简洁易懂,并提高开发效率。

MyBatis的Spring集成

MyBatis可以与Spring框架无缝集成。Spring提供了SqlSessionFactoryBean、SqlSessionTemplate等组件,简化了MyBatis的配置和使用。 MyBatis可以与Spring框架无缝集成,通过Spring提供的SqlSessionFactoryBean、SqlSessionTemplate等组件,可以简化MyBatis的配置和使用。以下是MyBatis与Spring集成的常用组件及其作用:

1. SqlSessionFactoryBean

SqlSessionFactoryBean是一个FactoryBean,用于创建SqlSessionFactory对象。

例如:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="mapperLocations" value="classpath*:mapper/*.xml"/>
</bean>

在以上代码中,我们通过注入dataSource和mapperLocations属性来创建SqlSessionFactory对象。

2. MapperScannerConfigurer

MapperScannerConfigurer是一个BeanPostProcessor,它会自动扫描包路径下所有的Mapper接口,并将这些接口注册到Spring容器中。

例如:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.example.mapper"/>
</bean>

在以上代码中,我们通过设置basePackage属性来指定需要扫描的Mapper接口所在的包路径。

3. SqlSessionTemplate

SqlSessionTemplate是MyBatis-Spring提供的核心组件之一,它实现了Spring的SqlSession某些方法,同时整合了Spring的事务管理机制。

例如:

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="com.example.mapper.UserMapper"/>
  <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

<bean id="userService" class="com.example.service.impl.UserServiceImpl">
  <property name="userMapper" ref="userMapper"/>
</bean>

在以上代码中,我们通过注入sqlSessionFactory和mapperInterface属性来创建MapperFactoryBean对象,并将其配置为Spring容器中的一个Bean。然后再将MapperFactoryBean对象注入到UserService中。

以上就是MyBatis与Spring集成的常用组件及其作用。通过使用这些组件,我们可以简化MyBatis的配置和使用,使得开发更加方便和高效。

转载自:https://juejin.cn/post/7267441651186384956
评论
请登录