Springboot整合mybatis试连接数据库

Web02成功案例分析

Springboot整合mybatis从而使用数据库试验,为员工管理系统配置数据库做准备,狂神B站有教程

2021-10-27

IDEA2021.2
java 8
mysql 8

项目步骤

这波是自己回来看都看不懂,先看一遍流程,然后照做

一、建立一个空的springboot项目,依赖不选也无所谓

二、闭着眼睛导依赖,pom.xml文件中dependencies标签包括的东西拿来把自己的替换掉

三、添加数据库,写配置文件application.properties,建表不急

四、往test目录下的Test类加代码,代码简陋有爆红应该无所谓,强迫症可自行加上(try,catch)的环绕,主要是测试能否与数据库建立连接,若连接成功会执行那两个打印的操作,慢慢来很难出错吧

如果报错就是没连上,根据报错检查配置文件,这步测试通不过就不用往后做了

五、正式开始写代码,看看项目结构(没有按照正常的mvc开发),照贴代码ing
六、启动,测试,结束

代码结构

Springboot整合mybatis试连接数据库_第1张图片

数据库结构

Springboot整合mybatis试连接数据库_第2张图片

测试连接

Web02ApplicationTests.java

package com.xie;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class Web02ApplicationTests {

    //DI注入数据源
    @Autowired
    DataSource dataSource;

    @Test
    public void contextLoads() throws SQLException {
        //看一下默认数据源
        System.out.println(dataSource.getClass());
        //获得连接
        Connection connection =   dataSource.getConnection();
        System.out.println(connection);
        //关闭连接
        connection.close();
    }
}

Test强迫症版本

void contextLoads() {
        System.out.println(dataSource.getClass());
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(connection);
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

测试结果

输出默认数据源,且获得连接,顺便打印该连接

Springboot整合mybatis试连接数据库_第3张图片

CURD测试

一般springboot启动成功后,访问localhost:8080看到404就是可以继续了

localhost:8080/queryUserList

Springboot整合mybatis试连接数据库_第4张图片

localhost:8080/addUser  #以下操作均返回“ok”

Springboot整合mybatis试连接数据库_第5张图片

localhost:8080/updateUser

Springboot整合mybatis试连接数据库_第6张图片

localhost:8080/deleteUser

Springboot整合mybatis试连接数据库_第7张图片

依赖文件

pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.6.7version>
        <relativePath/> 
    parent>
    <groupId>comgroupId>
    <artifactId>vote01artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>vote01name>
    <description>vote01description>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>

        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.1version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

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

project>

配置文件

application.properties
(个人配置文件)

spring.datasource.username=root
spring.datasource.password=111111
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package=com.xie.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

代码详情

User.java

package com.xie.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

UserMapper.java

package com.xie.mapper;

import com.xie.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserMapper {
    List<User> queryUserList();
    int addUser (User user);
    int updateUser(User user);
    int deleteUser(int id);
}

UserController.java

package com.xie.controller;

import com.xie.mapper.UserMapper;
import com.xie.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @GetMapping("/queryUserList")
    public List<User> queryUserList(){
        List<User> userList = userMapper.queryUserList();
        for (User user : userList){
            System.out.println(user);
        }
        return userList;
    }
    @GetMapping("addUser")
    public String addUser(){
        userMapper.addUser(new User(106,"amao","123456"));
        return "ok";
    }
    @GetMapping("updateUser")
    public String updateUser(){
        userMapper.updateUser(new User(106,"amao","000456"));
        return "ok";
    }
    @GetMapping("deleteUser")
    public String deleteUser(){
        userMapper.deleteUser(106);
        return "ok";
    }
}

Web02Application.java

保持默认,不可更改

UserMapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.xie.mapper.UserMapper">


    <select id="queryUserList" resultType="com.xie.pojo.User">
        select * from user ;
    select>
    <insert id="addUser" parameterType="com.xie.pojo.User">
        insert into user (id,name ,pwd) values (#{id},#{name},#{pwd})
    insert>
    <update id="updateUser" parameterType="com.xie.pojo.User">
        update user set name = #{name},pwd=#{pwd} where id = #{id}
    update>
    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    delete>
mapper>

mapper文件之间的相互对应,应该是因为namespace联系上的
Springboot整合mybatis试连接数据库_第8张图片

数据库

use testdb;
create table user
(
    id   int         not null
        primary key,
    name varchar(30) null,
    pwd  varchar(30) null
);

INSERT INTO exp_4.user (id, name, pwd) VALUES (102, 'b', '123456');
INSERT INTO exp_4.user (id, name, pwd) VALUES (103, 'b', '3456');
INSERT INTO exp_4.user (id, name, pwd) VALUES (104, 'c', '1256');
INSERT INTO exp_4.user (id, name, pwd) VALUES (105, 's', '123456');
INSERT INTO exp_4.user (id, name, pwd) VALUES (106, 'r', '1256');
INSERT INTO exp_4.user (id, name, pwd) VALUES (107, 'y', '123456');

你可能感兴趣的:(spring,boot,java,intellij-idea)