springboot --Mybatis注解版和配置文件版

序言:

简单查询可以用JPA, 但复杂查询要用Mybatis,因为Mybatis的SQL语句相对于JPA灵活(有逻辑判断,对返回数据的多样性处理灵活等等)

1、相关依赖

		<dependency>
			<!--jdbc(可以不加,因为mybatis-spring-boot-starter中就包含了jdbc这个依赖)-->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		
		<!--mybatis-->
		<dependency>
		    <groupId>org.mybatis.spring.boot</groupId>
		    <artifactId>mybatis-spring-boot-starter</artifactId>
		    <version>2.1.1</version>
		</dependency>
		
		<!--mysql-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.11</version>
		</dependency>

2、数据库连接(application.yml)

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver

一、使用注解版Mybatis(很简单):

1、在主程序上添加注解让spring扫描这个包下所有mapper接口类

@MapperScan(value=“com.example.mapper”)

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan(value = "com.example.demo.dao")
@SpringBootApplication
public class MybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(MybatisApplication.class, args);
	}

}

2、创建一个Mapper接口类

package com.example.mapper;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.example.bean.Department;

public interface DepartmentMapper {
	@Select("select * from department where id=#{id}")
	public Department get(Integer id);
	
	@Delete("delete from department where id=#{id}")
	public Integer delete(Integer id);
	
	@Options(useGeneratedKeys = true,keyProperty = "id")
	@Insert("insert into department(departmentName) values(#{departmentName})")
	public Integer insert(Department department);
	
	@Update("update department set departmentName=#{departmentName} where id=#{id}")
	public Integer update(Department department);

}

3、调用并使用

	@Autowired
	DepartmentMapper mapper;
	
	@ResponseBody
	@GetMapping("/get/{id}")
	public Department BB(@PathVariable("id")int id) {
		return mapper.get(id);
	}

二、使用配置文件

1、在主程序上添加注解让spring扫描这个包下所有mapper接口类

@MapperScan(value=“com.example.mapper”)

2、创建一个Mapper接口类(接口类和Mapper.xml的文件名必须相同,否则Mapper.xml无法找到接口类的方法,原因不详

package com.example.demo.dao;

import com.example.demo.bean.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @author Huangyt
 * @version 1.0
 * @date 2020/5/12 20:15
 */
public interface UserMapper {
    List<User> findAll();
}

3、在resources文件夹下并且与Mapper接口同包名下创建×××Mapper.xml配置文件(或者在配置文件中指定mapper.xml的位置)(接口类和Mapper.xml的文件名必须相同,否则Mapper.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配置文件给哪个接口调用-->
<!--resultType指定封装返回数据的容器类型-->
<mapper namespace="com.example.demo.dao.UserMapper">
    <select id="findAll" resultType="com.example.demo.bean.User">
        select * from user;
    </select>
</mapper>

关于Mybatis配置文件默认的存放位置

1、mybatis的配置文件放在resource文件夹下

2、×××Mapper.xml文件放在resource文件夹下的和Mapper接口类同一个包下

3、也可以通过配置文件修改配置文件的存放路径:

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

mybatis-config.xml(不用配置数据源和Mappers标签 == 毫无作用 == 可以不用添加)

mybatis-config.xml不用配置数据源的原因:

要注意我们配置pom.xml的Mybatis依赖是sprringboot的,所以当启动springboot时会自动扫描

application.properties配置文件,并不会扫描mybatis-config.xmll配置文件中的数据源。所以你此时必须将

连接数据库的参数写在application.properties配置文件中。

<?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>
	//连接数据库相关操作之前已经在approperties.yml已经配置好, 以下连接数据库的操作可以省略
  <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>
  //扫描mapper的操作之前在主程序已经添加了MapperScan, 所以也可以省略
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

4、调用并使用

注意:此时会出现userMapper会爆红:无法注入的异常,但运行正常的现象,原因不详。有人说是

idea的问题还可以忽略,如果要解决可以以下方法解决

1、通过将@Autowired 改成@Resource即可

2、Mapper接口类上添加@Repository

package com.example.demo;

import com.example.demo.bean.User;
import com.example.demo.dao.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@SpringBootTest
class DemoApplicationTests {
    @Autowired
    UserMapper userMapper;

    @Test
    void contextLoads() {
        List<User> all = userMapper.findAll();
        for(User user : all){
            System.out.println(user);
        }
    }

}

当然注解和配置文件两种方式可以一起配合使用


关于Mybatis的Mapper文件和*xml文件的位置
1、在resources文件夹下创建和src相同的文件夹结构,Mapper文件和*.xml文件等同于一个文件夹下,固然生效
在这里插入图片描述

关于Mybatis复杂查询例子

<?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.xuecheng.manage_course.dao.TeachplanMapper">
    <!--    自定义查询结果返回体结构,就是将查询得到结果进一步去重构-->
    <resultMap id="teachplanMap" type="com.xuecheng.framework.domain.course.ext.TeachplanNode">
        <!--        一级节点映射-->
        <id column="one_id" property="id"></id>
        <result column="one_name" property="pname"></result>
        <!--Collection标签一对多,表明二级节点是在一级节点的children集合中-->
        <!--        ofType  list集合中的类型,注意:类型写全路径的-->
        <collection property="children" ofType="com.xuecheng.framework.domain.course.ext.TeachplanNode">
            <id column="two_id" property="id"></id>
            <result column="two_name" property="pname"></result>
            <collection property="children" ofType="com.xuecheng.framework.domain.course.ext.TeachplanNode">
                <id column="three_id" property="id"></id>
                <result column="three_name" property="pname"></result>
            </collection>
        </collection>
    </resultMap>

    <select id="selectList" parameterType="java.lang.String"
            resultMap="teachplanMap">
        SELECT
        a.id one_id,
        a.pname one_name,
        b.id two_id,
        b.pname two_name,
        c.id three_id,
        c.pname three_name
        FROM
        teachplan a
        LEFT JOIN
        teachplan b ON b.parentid = a.id
        LEFT JOIN
        teachplan c ON c.parentid = b.id
        WHERE
        a.parentid = '0'
        <!--        _parameter表示传入的参数-->
        <if test="_parameter!=null and _parameter!=''">
            AND a.courseid = #{courceId}
        </if>
    </select>

</mapper>

select标签:

id:对应mapper的方法名

parameterType:参数类型

resultMap:自定义查询结果的返回格式(因为复杂查询得到的数据形式是多变的,用resultMap自定义映射关系,手动映射,指定表的哪一列数据对应实体类的哪个属性)

和resultType的区别是:自动将表和类的属性映射,但字段名必须相同;因为resultMap已经设置表和类属性的映射关系,所以字段名不相同也没关系。

(Mybatis查询得到的结果都是map类型)

if标签

test:条件

_parameter:指传入的参数

resultMap标签

id:自定义resultMap的唯一id

type:将查询到的结果返回的实体类(类路径要写全)

id(主键)标签、result(属性)标签

column:表属性的字段名

property:实体类属性的字段名

collection标签(表示一个集合属性List—一对多的关系)

property:这个List集合对应实体类的属性

ofType:List集合中的类型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值