Spring Boot 使用Mybatis操作数据库

新建一个Spring boot 项目。

1.引入依赖

<!-- 需要去仓库搜索添加 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- 实体类这注解简写工具 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
    <scope>provided</scope>
</dependency>
  1. 配置数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 这里使用的是MySql 8.0.15 数据库,需要加时区,保证自己的数据库db_jdbc 存在。
spring.datasource.url=jdbc:mysql://localhost:3306/db_mybatis?\
  useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=666666

# 整合Mybatis
# 检查mybatis 配置文件是否存在
mybatis.check-config-location=true
# 配置别名
mybatis.type-aliases-package=com.zdy.springboot.pojo
# 配置文件位置
# mybatis.config-location=classpath:mybatis/mybatis-config.xml
#配置mybatis 映射文件位置
mybatis.mapper-locations=classpath:mybatis/mapper/*Mapper.xml

数据库sql

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        `user_name` varchar(255) NOT NULL,
                        `user_password` varchar(255) NOT NULL,
                        PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '322');
INSERT INTO `user` VALUES ('2', 'lisi', '353534');

测试数据库配置

@SpringBootTest
class Springboot03MybatisApplicationTests {
    @Autowired
    private DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {

        System.out.println(dataSource.getClass());
        System.out.println(dataSource.getConnection());


    }

}
  1. 创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String user_name;
    private String user_password;
}
  1. 创建Usermapper接口
package com.zdy.springboot.mapper;

import com.zdy.springboot.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author deyou
 * @create 2020-03-29 10:29 AM
 */
//这个注解表示了这是一个mybatis 的注解类
@Mapper
@Repository
public interface UserMapper {
    User findUserByname(String username);
    //参数绑定问题参数名要和map
    void updateUserByName( String user_name, String user_password);
    void deleteUserByName(String username);
    void saveUser(User user);
    List<User> getUserList();

    /*基于注解的2个方法*/
    //查询所用用户信息
    @Select("select * from user")
    List<User> findAllUser();
    @Select("select * from user where id=#{myId}")
    User findUserById(@Param("myId") int id);

}
  1. 创建映射文件UserMapper.xml
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zdy.springboot.mapper.UserMapper">
    <select id="findUserByname" resultType="User">
        select * from user where user_name = #{username}
    </select>
<!--springboot 里配置了-->
    <select id="getUserList" resultType="User" >
        select * from user
    </select>
    <!--名字要和user_password和user_name要和User类属性名一致,接口也是-->
    <update id="updateUserByName" parameterType="User">
        update user set user_password=#{user_password} where user_name=#{user_name}
    </update>
    <insert id="saveUser" parameterType="User">
        insert into user (user_name,user_password) values (#{user_name},#{user_password})
    </insert>
    <delete id="deleteUserByName" parameterType="String">
        delete from user where user_name=#{1}
    </delete>
</mapper>
  1. 创建Usercontroller类
package com.zdy.springboot.controller;

import com.zdy.springboot.pojo.User;
import com.zdy.springboot.mapper.UserMapper;
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;

/**
 * @author deyou
 * @create 2020-03-29 10:45 AM
 */
@RestController
public class UserController {
    /**
     *
     */
    @Autowired
    private UserMapper userMapper;
    //也可是使用restful 风格,这里就不使用了
    //查询所有用户
    //http://localhost:8080/findAllUserList
    @GetMapping("findAllUserList")
    public List<User> findAllUserList(){
        List<User> userList = userMapper.getUserList();
        //控制台数据
        userList.forEach(user -> System.out.println(user));
        return userList;
    }
    //通过名字查询用户
    //http://localhost:8080/findUserByName?username=zhangsan
    @GetMapping("findUserByName")
    public User findUserByName(String username){
        User user = userMapper.findUserByname(username);
        return user;
    }
    //通过名字修改用户密码
    //http://localhost:8080/updateUserByName?username=zhangsan&password=56666
    @GetMapping("updateUserByName")
    public String updateUserByName(String username,String password){
        System.out.println(username);
        System.out.println(password);
        userMapper.updateUserByName(username,password);
        return "update method success";
    }
    //添加用户
    //http://localhost:8080/addUser?username=zhangsan&password=56666
    @GetMapping("addUser")
    public String addUser(String username,String password){
        User user = new User(username, password);
        System.out.println(username);
        System.out.println(password);
        userMapper.saveUser(user);
        return "update method success";
    }
    //通过名字删除用户
    //http://localhost:8080/deleteUserByName?username=zhangsan&password=56666
    @GetMapping("deleteUserByName")
    public String deleteUserByName(String username){
        userMapper.deleteUserByName(username);
        return "delete method success";
    }

    //http://localhost:8080/findAllUser
    @GetMapping("findAllUser")
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }

    //http://localhost:8080/findUserById?id=2
    @GetMapping("findUserById")
    public User findUserById(int id) {
        return userMapper.findUserById(id);
    }

}

最后: 启动项目,在浏览器中输出Controller 方法上对应网址检测结果。

项目目录:

在这里插入图片描述

发布了88 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_21344887/article/details/105178836