springBoot整合mybatis

功能

  • 配置mybatis
  • 调用数据库

创建springBoot项目

编辑器: idea

Create New Project -> Spring Initializr ->next-> 添加项目信息

14

添加依赖 web mysql mybatis

15

安装配置数据库

  • 安装数据库,或者直接通过docker 安装mysql
docker pull mysql:8.0

docker run -p 3306:3306 --name mymysql -e MYSQL_ROOT_PASSWORD=123456 -d mysql:8.0
  • -p 3306:3306:将容器的 3306 端口映射到主机的 3306 端口。
  • **-e MYSQL_ROOT_PASSWORD=123456:**初始化 root 用户的密码。
//设置远程访问,如果在本地不需要设置
docker exec -it mymysql bash
mysql -uroot -p123456	
//授权
GRANT ALL ON *.* TO 'root'@'%';
//刷新权限
flush privileges;

//此时,还不能远程访问,因为Navicat只支持旧版本的加密,需要更改mysql的加密规则
//更改加密规则
ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
//更新root用户密码
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '123456';
//刷新权限
flush privileges;

新建数据库

新建一个数据库xzw

创建数据表

CREATE TABLE `user` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `passWord` varchar(50) NOT NULL,
  `number` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

配置application.properties

spring.datasource.url = jdbc:mysql://192.168.99.100:3306/xzw
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
mybatis.mapper-locations= classpath:mapper/*.xml

这时候运行项目mybatis就不会报错

数据库调用

entity层

别名: model层 ,domain层
用途: 实体层,用于存放我们的实体类,与数据库中的属性值基本保持一致,实现set和get的方法。

创建entity目录在这个目录下创建实体类User

package indi.xzw.mybatis_basic.entity;

public class User {
    private int id;
    private String name;
    private String password;
    private String number;
    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
    
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", password=" + password + ", number=" + number + "]";
    }
}

mapper层

别名: dao层
用途: 对数据库进行数据持久化操作,他的方法语句是直接针对数据库操作的,主要实现一些增删改查操作,在mybatis中方法主要与与xxx.xml内相互一一映射。

创建mapper文件夹并在下面新建UserMapper类

package indi.xzw.mybatis_basic.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import indi.xzw.mybatis_basic.entity.User;

@Mapper
public interface UserMapper {
    List<User> findUserByName(String name);

    public List<User> ListUser();

    public int insertUser(User user);

    public int delete(int id);

    public int Update(User user);
}

创建映射文件

在src/main/resources/下新建mapper文件夹,在src/main/resources/mapper下写UserMapper的映射文件UserMapper.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE mapper PUBLIC
        "-//mybatis.org//DTD com.example.Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="indi.xzw.mybatis_basic.mapper.UserMapper">
    <resultMap id="result" type="indi.xzw.mybatis_basic.entity.User">
        <result property="name" column="name" />
        <result property="password" column="password" />
        <result property="number" column="number"/>

    </resultMap>

    <select id="ListUser" resultMap="result">
		SELECT * FROM user
	</select>

    <select id="findUserByName" resultMap="result">
		SELECT * FROM user where name=#{name}
	</select>

    <insert id="insertUser" parameterType="indi.xzw.mybatis_basic.entity.User"
            keyProperty="id" useGeneratedKeys="true">
		INSERT INTO user
		(
		id,name,password,number
		)
		VALUES (
		#{id},
		#{name, jdbcType=VARCHAR},
		#{password, jdbcType=VARCHAR},
		#{number}
		)
	</insert>

    <delete id="delete" parameterType="int">
		delete from user where id=#{id}
	</delete>

    <update id="Update" parameterType="indi.xzw.mybatis_basic.entity.User">
	update user set user.name=#{name},user.password=#{password},user.number=#{number} where user.id=#{id}
	</update>
</mapper>

service 层

用途:业务service层,给controller层的类提供接口进行调用。一般就是自己写的方法封装起来,就是声明一下,具体实现在serviceImpl中。

新建service 目录,在该目录下新建实体类UserService

package indi.xzw.mybatis_basic.service;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import indi.xzw.mybatis_basic.entity.User;
import indi.xzw.mybatis_basic.mapper.UserMapper;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User> findByName(String name) {
        return userMapper.findUserByName(name);
    }

    public User insertUser(User user) {
        userMapper.insertUser(user);
        return user;
    }
    public List<User> ListUser(){
        return	userMapper.ListUser();
    }


    public int Update(User user){
        return userMapper.Update(user);
    }

    public int delete(int id){
        return userMapper.delete(id);
    }
}

controller层

别名:web 层
用途: 控制层,负责具体模块的业务流程控制,需要调用service逻辑设计层的接口来控制业务流程。因为service中的方法是我们使用到的,controller通过接收前端H5或者App传过来的参数进行业务操作,再将处理结果返回到前端。

package indi.xzw.mybatis_basic.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import indi.xzw.mybatis_basic.entity.User;
import indi.xzw.mybatis_basic.service.UserService;


@RestController
@RequestMapping(value = "/CRUD", method = { RequestMethod.GET, RequestMethod.POST })
public class CRUD {
    @Autowired
    private UserService userservice;

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(int id) {
        int result = userservice.delete(id);
        if (result >= 1) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(User user) {
        int result = userservice.Update(user);
        if (result >= 1) {
            return "修改成功";
        } else {
            return "修改失败";
        }

    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public User insert(User user) {
        return userservice.insertUser(user);
    }

    @RequestMapping("/ListUser")
    @ResponseBody
    public List<User> ListUser(){
        return userservice.ListUser();
    }

    @RequestMapping("/ListUserByname")
    @ResponseBody
    public List<User> ListUserByname(String name){
        return userservice.findByName(name);
    }
}

测试

insert

http://localhost:8080/CRUD/insert?name=夏中伟&password=123456&number=123

16

ListUser

测试查询所有的信息

http://localhost:8080/CRUD/ListUser

17

ListUserByname

http://localhost:8080/CRUD/ListUserByname?name=夏中伟

update

localhost:8080/CRUD/update?id=3&name=夏中伟&password=9999999&number=5555

delete

根据Id删除数据:

http://localhost:8080/CRUD/delete?id=3

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×