Spring Boot 集成Mybatis

193 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第19天,点击查看活动详情

前言

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis 。MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。

MyBatis优缺点

图片.png

简单集成

2.1引入jar包

       <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>${druid.version}</version>
		</dependency>

2.2 添加mybaties配置

 mybatis:
  mapper-locations: classpath:mapper/*
  type-aliases-package: com.fw.mybaties.pojo
  configuration:
    map-underscore-to-camel-case: true 

说明:map-underscore-to-camel-case 为 true 时表示开启驼峰命名自动映射,如将 user_name 映射为 userName。

2.3 编写Dao接口

public interface UserMapper
{
   TUser getUserByName(String name);
}

2.4 添加mapper扫码

@MapperScan("com.fw.mybaties.mapper")
@SpringBootApplication
public class MybatisApplication
{
   public static void main(String[] args)
    {
        SpringApplication.run(MybatisApplication.class, args);
   

@MapperScan:可以使用@Mapper注解但是需要在每个类都添加不太方面,通过@MapperScan注解来扫码注解包下面的mapper类。

2.5 编写Service


public interface UserService
{
    TUser getUserByName(String name);
}


@Transactional(rollbackFor=Exception.class)
@Service
public class UserServiceImpl implements UserService
{
 
    @Autowired
    private UserMapper userMapper;
    
    public TUser getUserByName(String name)
    {
        return userMapper.getUserByName(name);
    }
 
}

2.6 编写测试

@RestController
@RequestMapping("/sys/user/")
public class UserController
{
    private Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    
    @GetMapping("getUserByName")
    public TUser getUserByName(@RequestParam String name)
    {
       logger.info("getUserByName paramter name:"+name);
       TUser tUser = userService.getUserByName(name); 
       logger.info("tuser:"+tUser.toString());
       return tUser;
    }
}

Spring Boot集成MyBits基本的已经讲解完了,上述只是一个非常简单的例子,实际的项目中还会遇到很多不一样的特殊需求。

常用优化

利用resultMap、include 标签,减少重复字段的编写

通常情况下查询所有数据和根据主键ID查询数据返回的结果和字段都非常的类似,可以使用resultMap、include进行复用。

 
  <resultMap id="BaseResultMap" type="com.fw.mybaties.pojo.TUser">
        <!--fetchType="lazy"  懒加载策略  fetchType="eager"  立即加载策略 -->
        <result column="oid" jdbcType="INTEGER" property="oid"/>
        <result column="name" jdbcType="VARCHAR" property="name"/>
        <result column="age" jdbcType="INTEGER" property="age"/>
        <result column="address" jdbcType="VARCHAR" property="address"/>
        
    </resultMap>

   <sql id="Base_Column_List">
        oid, name, age, address
    </sql>
       
<select id="getUserByName" resultMap="BaseResultMap">
	  select  <include refid="Base_Column_List" /> from t_user  u 
	  <where>
	    u.name=#{name}
	  </where> 
</select>

不要在where后面在添加1=1了

新手写SQL语句,通常会在where条件后面添加1=1来确保SQL语句不报错,其实这种写法是非常错误的。Mybatis提供了Where标签来解决此问题

<select id="getUserByName" resultType="com.fw.mybaties.pojo.TUser">
	  select *from t_user  u 
	  <where>
	    u.name=#{name}
	  </where> 
</select>

批量查询使用forEach标签来简化SQL

<select id="selectByIds" resultMap="BaseResultMap" parameterType="User">
	   select * from t 
	   <foreach collection="ids" item="id" open="where id in(" separator="," close=")"> 
		  #{id} 
	   </foreach> 
	</select>

对于批量更新和新增的话,不建议使用foreach标签,后续会重点讲解。

全局开启或者mapper文件查询语句开启懒加载,减少数据库交互次数。

全局开启懒加载,只需要在mybatis的配置文件中添加lazy-loading-enabled为true。

mybatis:
  configuration:
    lazy-loading-enabled: true

mybatis的懒加载原理如果大家不清楚的话,可以到网上查询相关资料。

总结

本文讲解Spring Boot集成Mybatis,相对于Spring的集成已经简化了很多配置,MyBatis一个重要的知识点也是面试必问点,Mybatis的Mapper是面向接口编程,其原理利用java动态代理,后续源码讲解会重点说明这点。