SpringBoot系列:SpringBoot整合mybatis

Springboot整合mybatis

  整理Springboot学习过程第一个阶段,整合mybatis,学习使我快乐。
  在学习过程中,没有资源的小伙伴可以去B站找狂神、雷神(尚硅谷)的springboot学习视频,雷神的视频有点害怕,都是源码解析,狂神的就简单明了些,但是雷神的你能听下去,你收获绝对满满,开冲!




 1、新建工程

   点击下一步:
在这里插入图片描述


命名注意:
在这里插入图片描述

选择依赖,然后下一步就点击完成可以了。
在这里插入图片描述

 2、在pom.xml文件下添加依赖

lombok:省掉实体类的有参无参构造方法,自动注入set、get方法,重写toString()方法等

        <!--        lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        
        <!--        引入thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
        
         <!-- Spring-Mybatis   非官方整合,官方是spring开头的-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <!--        导入阿里的数据库连接池技术-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.17</version>
        </dependency>

        <!--引入Mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>


        <!--mapper依赖-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>RELEASE</version>
        </dependency>

 3、在数据库中保证有Student表

在这里插入图片描述


 4、在entities包中添加Student实体类

@Data :自动注入set、get方法,重写equals、toString、hashCode方法
@AllArgsConstructor //有参构造
@NoArgsConstructor //无参构造

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
    private Integer id;
    private String sname;
    private Integer sage;
    private String password;
}

 5、在mapper包中添加StudentMapper接口

  实现操作数据库的方法就在该接口中在这里,个人故意设置了 List findAllStudents();方法不用注解方式,在下一步中用mapper.xml文件来进行配置
  @Mapper //开启扫描包之后,启动类中就不用注释了
  @Repository //使用Repository就可以给StudentMapper这个类添加@Autowreid注解不爆红

@Mapper      //开启扫描包之后这里就不用注释了
@Repository  //使用Repository就可以给StudentMapper这个类添加@Autowreid注解不爆红
public interface StudentMapper {
    /**
     * 查询所有学生
     * @return
     */
    //@Select("select * from student")
    List<Student> findAllStudents();

    @Select("select * from student where id=#{id}")
    Student findStudentById(Integer id);

    @Select("select * from student where sname=#{sname}")
    Student findStudentByName(String sname);


    @Insert("insert into student(sname,sage) values(#{sname},#{sage})")
    int insertStudent(Student student);


    @Delete("delete from student where id=#{id}")
    int deleteStudent(Integer id);


    @Update("update student set sname=#{sname},sage=#{sage} where id=#{id}")
    int updateStudent(Student student);

    /**
     * 登录方法
     * @param sname
     * @param password
     * @return
     */
    Student login(@Param("sname") String sname,@Param("password") String password);
}


 6、mapper映射文件

  在resources文件下新建mybatis文件夹mapper映射文件,存放,同时,新建StudentMapper.xml文件,该文件中实现查询所有学生List findAllStudents()方法

<?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="top.weidaboy.mapper.StudentMapper">

    <!--    查询所有学生-->
    <select id="findAllStudents" resultType="Student" >
            select *from student;
    </select>
</mapper>


 7、student.html

  templates中新建student.html,在student文件中添加关于学生操作模板的网页

<head>
    <meta charset="UTF-8">
    <title>全部学生列表</title>
</head>
<body>
	<a th:href="@{/student/addStudent}">添加学生信息</a>
	<br>
	<a th:href="@{/student/updateStudent}">更新学生信息</a>
	<hr />
	<div>
	    <table>
	        <tr th:each="stu:${allStudents}">
	            <td  th:text="${stu.id}"></td>
	            <td  th:text="${stu.sname}"></td>
	            <td  th:text="${stu.sage}"></td>
	        </tr>
	    </table>
</div>

 8、StudentController

  在controller文件中添加StudentController,在类中添加测试所有学生的查询方法。

    /**
     * 登录判断
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(Model model,String sname,String password){
            System.out.println(sname+"   "+ password);
            List<Student> allStudents = studentService.findAllStudents();
            model.addAttribute("allStudents",allStudents);
            return "allStudent";
    }

 9、application.yml文件配置

#设置端口
server:
  port: 8081
  #可以自动添加项目文件路径

spring:
  datasource:
    username: 账号
    password: 密码
    url: jdbc:mysql://IP地址:3306/数据库名?useUnicode=true&characterEncoding=utf8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #   数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    #导入国际化配置文件
  messages:
    basename: i18n.login
    #关闭模板缓存
  thymeleaf:
    cache: false
    
  #mybatis配置
mybatis:
  type-aliases-package: top.weidaboy.entities   #实体类所在包名
  mapper-locations: mybatis/*.xml   #配置文件


 10、启动程序

在这里插入图片描述
记得关闭浏览器缓存
在这里插入图片描述


  别的方法也是这样子的,奥力给就完事了~ 先写那么多,相关代码已经更新,具体使用可以参考readme.md,不足之处欢迎交流!!!
  ---------------------------------------------------------------------Vinda的Github代码

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值