• SpringBoot:MyBatis访问数据库(动力)


     


    目录:

    (1)MyBatis访问数据库 

    (2)@Mapper注解

    (3)@MapperScan注解

    (4)Dao接口和Mapper文件的分开


    ORM:O:Object R:Relation M:Mapping 指:Java对象和数据库表的数据的映射关系

    用Java对象来表示表中的数据的

    通过ORM来简化对数据的操作,我们用MyBatis框架来操作表中的数据,MyBatis就是ORM中的一种,SpringBoot集成MyBatis去操作数据

     

     

     创建新的Model,选择依赖:

    (1)MyBatis访问数据库 

     pom.xml:就加入了依赖:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0</modelVersion>
    5. <parent>
    6. <groupId>org.springframework.boot</groupId>
    7. <artifactId>spring-boot-starter-parent</artifactId>
    8. <version>2.7.1</version>
    9. <relativePath/> <!-- lookup parent from repository -->
    10. </parent>
    11. <groupId>com.bjpowernode</groupId>
    12. <artifactId>017-springboot-mapper</artifactId>
    13. <version>1.0.0</version>
    14. <properties>
    15. <java.version>1.8</java.version>
    16. </properties>
    17. <dependencies>
    18. <!--web的起步依赖-->
    19. <dependency>
    20. <groupId>org.springframework.boot</groupId>
    21. <artifactId>spring-boot-starter-web</artifactId>
    22. </dependency>
    23. <!--mybatis的起步依赖-->
    24. <dependency>
    25. <groupId>org.mybatis.spring.boot</groupId>
    26. <artifactId>mybatis-spring-boot-starter</artifactId>
    27. <version>2.2.2</version>
    28. </dependency>
    29. <!--mysql的驱动-->
    30. <dependency>
    31. <groupId>mysql</groupId>
    32. <artifactId>mysql-connector-java</artifactId>
    33. <scope>runtime</scope>
    34. </dependency>
    35. <!--测试-->
    36. <dependency>
    37. <groupId>org.springframework.boot</groupId>
    38. <artifactId>spring-boot-starter-test</artifactId>
    39. <scope>test</scope>
    40. </dependency>
    41. </dependencies>
    42. <build>
    43. <!--resources插件把xml的文件方到 target-class文件下-->
    44. <resources>
    45. <resource>
    46. <directory>src/main/java</directory>
    47. <includes>
    48. <include>**/*.xml</include>
    49. </includes>
    50. </resource>
    51. </resources>
    52. <plugins>
    53. <plugin>
    54. <groupId>org.springframework.boot</groupId>
    55. <artifactId>spring-boot-maven-plugin</artifactId>
    56. </plugin>
    57. </plugins>
    58. </build>
    59. </project>

     

     

     创建实体类:Student:

    1. package com.bjpowernode.model;
    2. public class Student {
    3. private Integer id;
    4. private String name;
    5. private Integer age;
    6. public Integer getId() {
    7. return id;
    8. }
    9. public void setId(Integer id) {
    10. this.id = id;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public Integer getAge() {
    19. return age;
    20. }
    21. public void setAge(Integer age) {
    22. this.age = age;
    23. }
    24. @Override
    25. public String toString() {
    26. return "Student{" +
    27. "id=" + id +
    28. ", name='" + name + '\'' +
    29. ", age=" + age +
    30. '}';
    31. }
    32. }

    创建Dao接口:StudentDao:

    1. package com.bjpowernode.dao;
    2. import com.bjpowernode.model.Student;
    3. import org.apache.ibatis.annotations.Mapper;
    4. import org.apache.ibatis.annotations.Param;
    5. //在springboot框架中想用这个接口需要加@Mapper注解
    6. /*@Mapper:告诉MyBatis这是dao接口,创建此接口的代理对象
    7. * 位置:在类的上面
    8. * 通过这个Mapper注解可以找到StudentDao接口和StudentDao.xml文件
    9. * */
    10. @Mapper
    11. public interface StudentDao {
    12. //@Param 注解给参数命名
    13. Student selectById(@Param("stuId") Integer id);
    14. }

    写接口所对应的Mapper文件,创建Mapper文件

    StudentDao.xml:

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.bjpowernode.dao.StudentDao">
    6. <!--使用insert,update,delete,select标签来写sql语句
    7. resultType="com.kuang.pojo.User11":返回数据的类型
    8. -->
    9. <select id="selectById" resultType="com.bjpowernode.model.Student">
    10. select id,name,age from student where id=#{stuId}
    11. </select>
    12. </mapper>

    创建业务层对象:

    StudentService接口:

    1. package com.bjpowernode.service;
    2. import com.bjpowernode.model.Student;
    3. public interface StudentService {
    4. Student queryStudent(Integer id);
    5. }

    接口的实现类StudentServiceImpl:

    1. package com.bjpowernode.service.impl;
    2. import com.bjpowernode.dao.StudentDao;
    3. import com.bjpowernode.model.Student;
    4. import com.bjpowernode.service.StudentService;
    5. import org.springframework.stereotype.Service;
    6. import javax.annotation.Resource;
    7. @Service //注解创建Service对象
    8. public class StudentServiceImpl implements StudentService {
    9. //用到Dao,声明Dao的属性
    10. @Resource //注解自动注入
    11. private StudentDao studentDao;
    12. @Override
    13. public Student queryStudent(Integer id) {
    14. Student student = studentDao.selectById(id);
    15. return student;
    16. }
    17. }

    创建Controller:StudentController:

    1. package com.bjpowernode.controller;
    2. import com.bjpowernode.model.Student;
    3. import com.bjpowernode.service.StudentService;
    4. import org.springframework.stereotype.Controller;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.ResponseBody;
    7. import javax.annotation.Resource;
    8. @Controller
    9. public class StudentController {
    10. //需要Service,声明属性,进行注入
    11. @Resource
    12. private StudentService studentService;
    13. @RequestMapping("/student/query")
    14. @ResponseBody
    15. public String queryStudent(Integer id){
    16. Student student = studentService.queryStudent(id);
    17. return student.toString();
    18. }
    19. }

    声明插件:作用把java目录下的子目录中的以xml结尾的文件,输出到target  Class目录文件中,这样你就可以在类路径当中找到.xml文件了

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

     连接数据库,用到application.properties配置文件:进行连接数据的配置:

    1. server.port=9001
    2. server.servlet.context-path=/orm
    3. #设置连接数据库 mysql驱动新版的驱动类
    4. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    5. #连接数据库的url ?后是连接数据库提供的参数 useUnicode:表示用的是useUnicode编码 characterEncoding:表示字符集 serverTimezone:表示时区 GMT:标准时区 8:表示加8小时,我们的时区跟标准时区差8小时
    6. spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    7. #数据库连接名字
    8. spring.datasource.username=root
    9. #数据库连接密码
    10. spring.datasource.password=123456

    数据库中的表:

     

     

    测试MyBatis访问数据库:传递id=1

     传递id=2

     (2)@Mapper注解

    通过这个注解@Mapper:可以找到Dao接口和Mapper.xml文件

     当接口少时,用注解@Mapper还比较方便

    如果项目中有多个Dao接口,那么每个接口都需要加@Mapper注解,那就不怎么方便了,这是可以通过第二种方式:

    (3)@MapperScan注解

     

     

     

    当项目中有多个Dao接口,就可以使用@MapperScan注解,只需要加载主启动类的上面:

    1. package com.bjpowernode;
    2. import org.mybatis.spring.annotation.MapperScan;
    3. import org.springframework.boot.SpringApplication;
    4. import org.springframework.boot.autoconfigure.SpringBootApplication;
    5. /*@MapperScan:找到Dao接口和Mapper文件
    6. * basePackages:Dao接口所在的包名
    7. * */
    8. @SpringBootApplication
    9. @MapperScan(basePackages = "com.bjpowernode.dao") //根据这个注解会找到所有的Dao接口和Mapper文件
    10. //@MapperScan(basePackages = {"com.bjpowernode.dao","com.bjpowernode.mapper"}) //这个注解可以指定多个值,可以扫描多个包
    11. public class Application {
    12. public static void main(String[] args) {
    13. SpringApplication.run(Application.class, args);
    14. }
    15. }

    结果跟上方的一样。

     

    (4)Dao接口和Mapper文件的分开

     Dao接口和Mapper是放在一起的,正常理解下Java目录下只能是java文件,最理想的情况是Dao接口和Mapper给它分开存储,怎么分开存储呢?我们可以把.xml文件放在resources目录下,新建一个mapper文件夹专门来存放.xml文件:

     

    这样存放后,MyBatis能找到的是Dao接口,找不高Mapper文件了,因为mapper文件夹是自定义的,所以需要告诉框架去哪里找Dao接口对应的Mapper文件

    需要在配置文件中声明mapper文件的位置:application.properties:

    1. server.port=9001
    2. server.servlet.context-path=/orm
    3. #设置连接数据库 mysql驱动新版的驱动类
    4. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    5. #连接数据库的url ?后是连接数据库提供的参数 useUnicode:表示用的是useUnicode编码 characterEncoding:表示字符集 serverTimezone:表示时区 GMT:标准时区 8:表示加8小时,我们的时区跟标准时区差8小时
    6. spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    7. #数据库连接名字
    8. spring.datasource.username=root
    9. #数据库连接密码
    10. spring.datasource.password=123456
    11. #指定mapper文件的位置
    12. mybatis.mapper-locations=classpath:mapper/*.xml

    跟换下pom.xml中的插件信息:

    <!--resources插件 把resources下的任意的处理文件放到target class目标目录下-->
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>

    配置日志信息:

    1. server.port=9001
    2. server.servlet.context-path=/orm
    3. #设置连接数据库 mysql驱动新版的驱动类
    4. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    5. #连接数据库的url ?后是连接数据库提供的参数 useUnicode:表示用的是useUnicode编码 characterEncoding:表示字符集 serverTimezone:表示时区 GMT:标准时区 8:表示加8小时,我们的时区跟标准时区差8小时
    6. spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    7. #数据库连接名字
    8. spring.datasource.username=root
    9. #数据库连接密码
    10. spring.datasource.password=123456
    11. #指定mapper文件的位置
    12. mybatis.mapper-locations=classpath:mapper/*.xml
    13. #指定mybatis的日志 将这个日志输出到控制台上
    14. mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

     

    在控制台可以显示配置的日志:

     

     

  • 相关阅读:
    [每日两题系列]刷算法题咯~~
    C#的托盘窗体显示与隐藏效果 - 开源研究系列文章
    VMware ESXi 8.0U2c macOS Unlocker & OEM BIOS ConnectX-3 网卡定制版 (集成驱动版)
    [datawhale202208]计算之魂共读:算法规范化,大数和数量级的概念
    推荐五款装机必备的常用软件
    MHA高可用
    Accelerate 0.24.0文档 四:Megatron-LM
    react 路由权限
    【linux C】绑定任务到特定CPU(CPU亲和性)
    js中的instance,isPrototype和getPrototypeOf的使用,来判断类的关系
  • 原文地址:https://blog.csdn.net/dengfengling999/article/details/125545988