Spring Boot(七)Mybtis篇

Spring Boot(七)Mybatis篇


前面说了Spring Boot的JPA,现在来说说Mybatis

Mybatis 初期使用比较麻烦,需要各种配置文件、实体类、Dao 层映射关联、还有一大推其它配置。当然 Mybatis 也发现了这种弊端,初期开发了generator可以根据表结果自动生产实体类、配置文件和 Dao 层代码,可以减轻一部分开发量;后期也进行了大量的优化可以使用注解了,自动管理 Dao 层和配置文件等,发展到最顶端就是今天要讲的这种模式了,mybatis-spring-boot-starter 就是 Spring Boot+ Mybatis 可以完全注解不用配置文件,也可以简单配置轻松上手。

Mybatis-spring-boot-starter

mybatis-spring-boot-starter主要有两种使用方案,一种是使用注解解决一切问题,一种是简化后的老传统。

当然任何模式都需要首先引入mybatis-spring-boot-starter的 Pom 文件,现在最新版本是 2.0.0

Mybatis的依赖:

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.0.0</version>
</dependency>

无配置文件注解版

就是一切使用注解搞定。

1.添加相关 Maven 文件

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

2.application.properties添加相关配置

#为实体类设置别名
mybatis.type-aliases-package=com.example.demo.pojo

spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Spring Boot 会自动加载 spring.datasource. ,相关配置数据源就会自动注入到 sqlSessionFactory 中,sqlSessionFactory 会自动注入到 Mapper 中,对了,你一切都不用管了,直接拿起来使用就行了。*

3.开发 Mapper

@Component
public interface UserMapper2 {
    @Select("select * from user")
    List<User> getAllUsers();

    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "u"),
            @Result(property = "address", column = "a")
    })
    @Select("select username as u,address as a,id as id from user where id=#{id}")
    User getUserById(Long id);

    @Select("select * from user where username like concat('%',#{name},'%')")
    List<User> getUsersByName(String name);

    @Insert({"insert into user(username,address) values(#{username},#{address})"})
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class)
    Integer addUser(User user);

    @Update("update user set username=#{username},address=#{address} where id=#{id}")
    Integer updateUserById(User user);

    @Delete("delete from user where id=#{id}")
    Integer deleteUserById(Integer id);
}

注意,使用#符号和$符号的不同:

// This example creates a prepared statement, something like select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);

// This example creates n inlined statement, something like select * from teacher where name = 'someName';
@Select("Select * from teacher where name = '${name}'")
Teacher selectTeachForGivenName(@Param("name") String name);

4.添加Mapper导容器

添加到容器有两种方法

1.在启动类中添加对 mapper 包扫描@MapperScan

2.直接在 Mapper 类上面添加注解@Mapper

建议使用第一种,不然每个 mapper 加个注解也挺麻烦的

5.使用

上面三步就基本完成了相关 Mapper 层开发,使用的时候当作普通的类注入进入就可以了

@RunWith(SpringRunner.class) //用容器方式运行
@SpringBootTest
public class MybatisTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test(){
        User user=new User();
        user.setName("彦");
        user.setPwd("彦锅");
        userMapper.addUser(user);
    }

}

极简 xml 版本

极简 xml 版本保持映射文件的老传统,接口层只需要定义空方法,系统会自动根据方法名在映射文件中找对应的 Sql .

1、配置

pom 文件和注释版本一样,只是application.properties新增以下配置。

mybatis.config-location=classpath:mybatis/mybatis-config.xml 
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
#指定了 Mybatis 基础配置文件和实体类映射文件的地址

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>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases>
</configuration>
#这里也可以添加一些 Mybatis 基础的配置

2.添加 User 的映射文件

<?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.demo.mapper.UserMapper" >
    <resultMap id="BaseResultMap" type="com.example.demo.pojo.User" >
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="pwd" property="pwd" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="Base_Column_List" >
        id, name, pwd
    </sql>

    <select id="getAll" resultMap="BaseResultMap"  >
        SELECT
        <include refid="Base_Column_List" />
        FROM user
    </select>

    <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
        SELECT
        <include refid="Base_Column_List" />
        FROM user
        WHERE id = #{id}
    </select>

    <insert id="insert" parameterType="com.example.demo.pojo.User" >
       INSERT INTO
       		user
       		(name,pwd)
       	VALUES
       		(#{name}, #{pwd})
    </insert>

    <update id="update" parameterType="com.example.demo.pojo.User" >
        UPDATE
        user
        SET
        <if test="name != null">name = #{name},</if>
        <if test="pwd != null">pwd = #{pwd},</if>
        WHERE
        id = #{id}
    </update>

    <delete id="delete" parameterType="java.lang.Long" >
       DELETE FROM
       		 user
       WHERE
       		 id =#{id}
    </delete>
</mapper>

其实就是把上个版本中 Mapper 的 Sql 搬到了这里的 xml 中了

3.编写 Mapper 层的代码

package com.example.demo.mapper;


import com.example.demo.pojo.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public interface UserMapper {


    List<User> getAll();

    User getOne(Long id);

    void insert(User user);

    void update(User user);

    void delete(Long id);


}

对比上一步,这里只需要定义接口方法

4、使用

package com.example.demo;

import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class) //用容器方式运行
@SpringBootTest
public class MybatisTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test(){
        User user=new User();
        user.setName("彦");
        user.setPwd("彦锅");
        User u = userMapper.getOne(111111L);
        System.out.println(u);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值