踩了几百个坑总结出来的springboot整合MyBatis---能掉的坑都掉了

我人麻了

本来就是很简单的整合 和我脑袋里面想到的整合的方式基本上重合 但就是由于太多太多太多小细节 才让我搞了好几天都没成功 最后还是按着狂神老哥一步一步的写出来吧。
细节之多真的就把我整麻了

导包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>springboottest1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboottest1</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
*这里一定记得给我搞高版本的 吗的 就是这里 版本太低连jdbc的驱动都不支持*
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
    还有这个包 是MyBatis开发出来的 spring没有这个 所以直接去他们官网拷贝过来再导进去
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
        这个是jdbc的启动器starter就是能把所有需要的配置都调出来
        比如我想要用springboot启动datasource 那我就必须依赖data的start
        这样我在yaml里面配置的时候就能成功
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.23</version>
        </dependency>
     
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>

这个一定要记得加上 就是能扫描的 具体作用我也不太清楚 
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.json</include>
                    <include>**/*.ftl</include>
                </includes>
            </resource>
        </resources>

    </build>


</project>

实体类pojo
经典狗哥

package com.liujiacheng.pojo;

import org.springframework.stereotype.Component;

public class Dog {
    String name;
    String age;

    public Dog() {
    }

    public Dog(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

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

配置文件一定一定要配置好

spring:
  datasource:
    username: sa
    password: 123456
    url: jdbc:mysql://localhost:3306/mysql?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    这里就是上面说的那个pom高版本的那个cj了 要记得
    driver-class-name: com.mysql.cj.jdbc.Driver



server:
  port: 8080

mybatis:
  mapper-locations:
    - classpath:com/liujiacheng/DAO/*.xml
    下面这个就是配置实体类的别名  Mapper要是找类的话就会去这里找
  type-aliases-package: com.liujiacheng.pojo


然后就是Mapper接口了这上面的两个注解 一个是用来辩识的 告诉springboot这里是一个Mapper
下面是表示dao层的专属注解

package com.liujiacheng.DAO;

import com.liujiacheng.pojo.Dog;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.Mapping;

import java.util.Map;

@Mapper
@Repository
public interface DogMapper {

    void addOneDog(Map<String,Object> map);

    void delOneDog(String name);

    Dog selectOneDog(String name);

}

然后就是Mapper的配置文件 详细讲解一下

<?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.liujiacheng.DAO.DogMapper">
		然后就是这个result 表示的是实体类 在application里面配置好了别名的话
		这里就能直接写dog也能识别到pojo层
    <select id="selectOneDog" resultType="Dog" parameterType="String">
        select * from dog where name=#{name};
    </select>
    <delete id="delOneDog"  parameterType="String">
        delete * from dog where name = #{name};
    </delete>
    <insert id="addOneDog" parameterType="Map" >
        insert into dog(name, age) VALUES (#{name},#{age})
    </insert>
</mapper>

最后就是调用 我们写一个controller

package com.liujiacheng.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.liujiacheng.DAO.DogMapper;
import com.liujiacheng.pojo.Dog;
import com.liujiacheng.service.DogService;
    import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import sun.misc.Request;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

/**
 * @author Michelle
 */
@RestController

public class DogController {


    @Autowired
     JdbcTemplate jdbcTemplate;
    @Autowired
    DogMapper dogMapper;
    @Autowired
    DogService dogService;

    @Autowired
    DataSource dataSource;

    @RequestMapping("/helloSql")
    public String selectAll(){
        String sql="select * from dog ";
        System.out.println(jdbcTemplate.getClass());
        System.out.println(jdbcTemplate.queryForList(sql));
        return "index";
    }
    @RequestMapping("/addOneDogByJDBC")
    public String addOneDog(){
        String sql="insert into dog(name,age) values ('xiaobaigou','666')";
        jdbcTemplate.execute(sql);

        return "index";
    }

    @RequestMapping("/selectOneDog")
    String selectOneDog(@RequestParam("name") String userName, @RequestParam("password") String password, HttpSession session,Model model){

        System.out.println(userName);
        System.out.println(password);
        session.setAttribute("user",userName);
        System.out.println(session);

        System.out.println(session);
        String myPassword="123456";
        String myUserName="hello";
       if (userName.equals(myUserName)&&password.equals(myPassword)){
           session.setAttribute("hello","my");
           return "redirect:/auth_login.html" ;
       }else {
           model.addAttribute("msg","账号密码错误");
           return "index";
       }
    }

    @RequestMapping("/selectNoDog")
    String selectNoDog( Model model){
        return "redirect:/main.html" ;

    }

    @RequestMapping("/test")
    String test() throws Exception{
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        System.out.println(druidDataSource.getMaxActive()+druidDataSource.getMaxCreateTaskCount());
        return "index";
    }

    @RequestMapping("/addOneDogByMybatis")
    String addOneDogByMybatis() {
        Dog dog = dogService.selectOneDog("xiaobai");
        System.out.println(dog.toString());
        return "index";
    }
}

只看最下面这个 你去前端请求的时候就会执行 然后就能查到这个小白的信息了

注意点

1、sql语句可能会报错 但是没关系的直接上就完事了
2、可能就算你配置了别名 在那个xml文件里面还是显示不能找到那个实体类没事的上就完事了。
3、配置文件的路径一定要写对!!!!!
4、这里省略了一个server层没写 可以加上 就是一个接口加一个实现类就好了 记得加注解@Server

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值