初学SpringBoot--ch05-SpringBoot 集成 MyBatis

使用MyBatis框架操作数据, 在SpringBoot框架集成MyBatis
使用步骤:

1.mybatis起步依赖 : 完成mybatis对象自动配置, 对象放在容器中
2.pom.xml 指定把 src/main/java 目录中的 xml 文件包含到 classpath 中
3.创建实体类 Student
4.创建 Dao 接口 StudentDao , 创建一个查询学生的方法
5.创建 Dao 接口对应的 Mapper 文件, xml 文件, 写sql语句
6.创建Service层对象,创建StudentService接口和他的实现类。 去dao对象的方法。完成数据库的操作
7.创建Controller对象,访问Service。
8.写application.properties文件,配置数据库的连接信息。

1.1 SpringBoot 集成 MyBatis 例子

1.1.1 创建数据库表

在这里插入图片描述
在这里插入图片描述

1.1.2 加入 Maven依赖

<dependencies>
        <!--web的起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mybatis的起步依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.1</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

1.1.3 加入 resources 插件

    <build>
        <!--加入 resource 插件-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
    </build>

1.1.4 配置数据源

server.port=9001
server.servlet.context-path=/orm

#连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456

1.1.5 创建 Student 实体类

package com.suyv.model;

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

1.1.6 创建 StudentDao 接口

package com.suyv.dao;

import com.suyv.model.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

/**
 * @mapper 告诉mybatis这是dao接口,创建此接口的代理对象
 */
@Mapper
public interface StudentDao {
    Student selectById(@Param("stuId") Integer id);
}

1.1.7 创建 StudentDao.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">
<mapper namespace="com.suyv.dao.StudentDao">
    <select id="selectById" resultType="com.suyv.model.Student">
        select * from student where id=#{stuId}
    </select>
</mapper>

1.1.8 创建StudentService 接口

package com.suyv.service;

import com.suyv.model.Student;

public interface StudentService {
    Student queryStudent(Integer id);
}

1.1.9 创建StudentServiceImpl 实现类

package com.suyv.service.impl;

import com.suyv.dao.StudentDao;
import com.suyv.model.Student;
import com.suyv.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentDao studentDao;

    @Override
    public Student queryStudent(Integer id) {
        Student student = studentDao.selectById(id);
        return student;
    }
}

1.1.10 创建 StudentController 类

package com.suyv.controller;

import com.suyv.model.Student;
import com.suyv.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;

@Controller
public class StudentController {

    @Resource
    private StudentService studentService;

    @RequestMapping("/student/query")
    @ResponseBody
    public String queryStudent(Integer id){
        Student student = studentService.queryStudent(id);
        return student.toString();
    }
}

1.2 使用@MapperScan

在 Dao 接口上面加入@Mapper,需要在每个接口都加入注解。 当 Dao 接口多的时候不方便。可以使用如下的方式解决。
主类上添加注解包扫描:@MapperScan(“com.suyv.dao”)

package com.suyv;

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

/**
 *  @MapperScan : 扫描所有的 mybatis 的 dao 接口
 * 			位置:在主类的上面
 * 			属性:basePackages:指定 dao 接口的所在的包名。
 * 			dao 接口和 mapper 文件依然在同一目录
 */
@SpringBootApplication
@MapperScan(basePackages = "com.suyv.dao")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

1.3 Mapper文件和Dao接口分开管理

现在把Mapper文件放在resources目录下
1)在resources目录中创建子目录(自定义的), 例如mapper
2)把mapper文件放到 mapper目录中
3)在application.properties文件中,指定mapper文件的目录

#指定mapper文件位置
mybatis.mapper-locations=classpath:mapper/*.xml
#mybatis日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4)在pom.xml中指定 把resources目录中的文件 , 编译到目标目录中

<!--resources插件-->
<resources>
   <resource>
      <directory>src/main/resources</directory>
      <includes>
         <include>**/*.*</include>
      </includes>
   </resource>
</resources>

1.4 事务

Spring框架中的事务:
1)管理事务的对象: 事务管理器(接口, 接口有很多的实现类)
例如:使用Jdbc或mybatis访问数据库,使用的事务管理器:DataSourceTransactionManager

2)声明式事务: 在xml配置文件或者使用注解说明事务控制的内容
控制事务: 隔离级别,传播行为, 超时时间

3)事务处理方式:
​ 1.Spring框架中的@Transactional
​ 2.aspectj框架可以在xml配置文件中,声明事务控制的内容

SpringBoot中使用事务: 上面的两种方式都可以,底层依然采用的是 Spring 本身提供的事务管理。
➢ 在入口类中使用注解 @EnableTransactionManagement 开启事务支持
➢ 在访问数据库的 Service 方法上添加注解 @Transactional 即可

1.4.1 SpringBoot 实现事务

1)pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.1</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-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <!--加入 resource 插件-->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
    </build>

2)配置 application.properties

server.port=9001
server.servlet.context-path=/orm

#连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456

#指定mapper文件位置
mybatis.mapper-locations=classpath:mapper/*.xml
#mybatis日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

3)创建 Student 实体类

package com.suyv.model;

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

4)创建 StudentDao 接口与 mapper 文件

StudentDao.java

package com.suyv.dao;

import com.suyv.model.Student;

public interface StudentDao {
    int addStudent(Student student);
}

StudentDao.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">
<mapper namespace="com.suyv.dao/StudentDao">
    <insert id="addStudent">
        insert into student(name,age) value (#{name},#{age})
    </insert>
</mapper>

5)创建 service 接口及实现类

StudentService.java

package com.suyv.service;

import com.suyv.model.Student;

public interface StudentService {
    int addStudent(Student student);
}

StudentServiceImpl.java

package com.suyv.service.impl;

import com.suyv.dao.StudentDao;
import com.suyv.model.Student;
import com.suyv.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentDao studentDao;

    @Transactional
    @Override
    public int addStudent(Student student) {
        System.out.println("业务方法addStudent");
        int rows = studentDao.addStudent(student);
        // 抛出运行时异常
        int m = 10/0;
        System.out.println("执行sql语句");
        return rows;
    }
}

6)创建 Controller

package com.suyv.controller;

import com.suyv.model.Student;
import com.suyv.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;

@Controller
public class StudentController {

    @Resource
    private StudentService studentService;

    @RequestMapping("/addStudent")
    @ResponseBody
    public String addStudent(String name,Integer age){
        Student student = new Student();
        student.setName(name);
        student.setAge(age);
        int rows = studentService.addStudent(student);
        return "添加学生:" + rows;
    }
}

7)修改主启动类

package com.suyv;

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

@EnableTransactionManagement
@SpringBootApplication
@MapperScan(basePackages = "com.suyv.dao")
public class Application {

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

憨憨浩浩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值