SpringBoot整合mybatis的两种方式

SpringBoot整合mybatis的两种方式

1、通过配置去整合mybatis

添加依赖
<dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>2.1.1</version>
</dependency>
实现增删查改的mapper
/**
 * @Auther: ZQB
 * Date:2020/1/6
 */
@Mapper
public interface UserMapper {
    /**
     * 根据用户 id 查询
     *
     * @param uid
     * @return :返回查询结果,不存在时返回 null
     * @Select :等价于以前 xml 形式时的 <select 标签,sql写法仍然和以前一样
     */
    @Select(value = {"select * from user where u_id=#{uid}"})
    public User findUserById(Integer uid);

    /**
     * 查询所有用户
     *
     * @return :返回查询结果
     * @Select :等价于以前 xml 形式时的 <select 标签,sql写法仍然和以前一样
     */
    @Select(value = {"select * from user"})
    public List<User> findAllUsers();

    /**
     * 根据用户id删除用户
     *
     * @return :返回操作的行数,也可以不返回
     */
    @Delete("delete from user where uid = #{uid}")
    public Integer deleteUserById(Integer uid);

    /**
     * 添加用户
     *
     * @param user :因为主键 uid 自增,所以没设值
     * @return
     */
    @Insert("insert into user(name,age,birthday,salary) values(#{name},#{age},#{birthday},#{salary})")
    public Integer adduser(User user);

    /**
     * 根据用户 uid 修改用户
     *
     * @param user
     * @return
     */
    @Update("update user set name=#{name},age=#{age},birthday=#{birthday},salary=#{salary} where uid=#{uid}")
    public Integer updateUser(User user);

}

通过配置bean修改mybatis的属性:

/**
 * @Auther: ZQB
 * 自定义Mybatis的配置
 * Date:2020/1/6
 */
@Configuration
public class MyBatisConfig {
    /**
     * 将组建添加到bean的容器当中去
     * @return
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

注意:需要对每个mapper接口添加@Mapper,也可以在SpringBoot的启动类添加mapper的包名:
@MapperScan(value {“com.example.mybatismethods.mapper”}),这样就可以省略@Mapper注解

2、通过传统的配置文件整合mybatis

1、需要在resources目录中创建相应的mapper.xml配置文件,其次要添加mybatis-config.xml的主配置文件
在这里插入图片描述

mybatis-config.xml
<?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>
    <!--MyBatis 核心配置文件,就是以前的 sqlMapConfig.xml-->
    <!--可从官网获取本文件头:http://www.mybatis.org/mybatis-3/getting-started.html-->

    <!-- 文件中的配置都可以从官网获取:http://www.mybatis.org/mybatis-3/configuration.html#settings-->
    <settings>
        <!-- 开启驼峰命名,与注解方式的使用的 ConfigurationCustomizer 完全等效-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="multipleResultSetsEnabled" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="useGeneratedKeys" value="false"/>
        <setting name="autoMappingBehavior" value="PARTIAL"/>
        <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <setting name="defaultStatementTimeout" value="25"/>
        <setting name="defaultFetchSize" value="100"/>
        <setting name="safeRowBoundsEnabled" value="false"/>
        <setting name="mapUnderscoreToCamelCase" value="false"/>
        <setting name="localCacheScope" value="SESSION"/>
        <setting name="jdbcTypeForNull" value="OTHER"/>
        <setting name="lazyLoadTriggerMethods"
                 value="equals,clone,hashCode,toString"/>
    </settings>
    <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>
        <package name="com.example.mybatismethods.mapper"/>
    </mappers>
</configuration>

PartyMapper.xml
<?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">

<!--namespace同样指向对应的Mapper接口-->
<mapper namespace="com.example.mybatismethods.mapper.PartyMapper">
    <!-- myBatis sql 映射文件,可从官网获取:http://www.mybatis.org/mybatis-3/getting-started.html-->
    <!-- 和以前一样对应Mapper接口的方法写上sql-->

    <!-- 根据 partyId 查询党支部,可以不指定 parameterType,会自动根据接口方法的参数进行映射-->
    <select id="findPartyById" resultType="com.example.mybatismethods.domain.Party">
        select * from party where partyId = #{partyId}
    </select>

    <!-- 查询所有党支部-->
    <select id="findAllPartys" resultType="com.example.mybatismethods.domain.Party">
        select * from party;
    </select>

    <!-- 根据 partyId 删除,可以不指定 parameterType,会自动根据接口方法的参数进行映射-->
    <delete id="deletePartyById">
      DELETE FROM party where partyId = #{partyId}
    </delete>

    <!-- 其余 添加、修改完全与以前 spring 整合 myBatis 一样,在此不再累述-->
</mapper>

PartyMapper接口
package com.example.mybatismethods.mapper;

import com.example.mybatismethods.domain.Party;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @Auther: ZQB
 * Date:2020/1/6
 */
public interface PartyMapper {

    Party findPartyById(Integer partyId);
    List<Party> findAllPartys();
    Integer deletePartyById(Integer partyId);

};
发布了22 篇原创文章 · 获赞 6 · 访问量 586
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览