内容详情 您现在的位置是: 首页> 其他随笔

spring boot 整合MyBatis

发布时间:2022-04-21 19:05 已围观:2186

摘要spring boot 整合MyBatis

在学习java spring boot的时候使用MyBatis时一直出现问题, 现将详细demo代码记录如下:

1.sql

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 80015
 Source Host           : localhost:3306
 Source Schema         : test

 Target Server Type    : MySQL
 Target Server Version : 80015
 File Encoding         : 65001

 Date: 20/12/2021 11:24:17
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user`  (
  `id` int(11) NOT NULL,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES (1, 'laowang', '112233');
INSERT INTO `tb_user` VALUES (2, 'laoli', '123456');

SET FOREIGN_KEY_CHECKS = 1;

2. pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhg.demo</groupId>
    <artifactId>mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--web核心依赖-->
        <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>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
        <!--Thymeleaf 启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

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

</project>

3.src/main/resources/application.yml

server:
  port: 8182
spring:
  thymeleaf:
    mode: HTML
    encoding: UTF-8
    content-type: text/html
    cache: false
    prefix: classpath:/templates
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test
    username: root
    password: 123456
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.zhg.demo.entity
  configuration:
    map-underscore-to-camel-case: true

4. src/main/resources/mapper/UserMapper.xml

<?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.zhg.demo.mapper.UserMapper">
    <select id="findAll" resultType="com.zhg.demo.entity.User">
        SELECT * FROM tb_user
    </select>
    <select id="findById" resultType="com.zhg.demo.entity.User">
        SELECT * FROM tb_user WHERE id = #{id}
    </select>
</mapper>

5.com.zhg.demo.entity.User

package com.zhg.demo.entity;

public class User {
    private Integer id;
    private String username;
    private String password;

    public User() {

    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

6.com.zhg.demo.mapper.UserMapper

package com.zhg.demo.mapper;

import com.zhg.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper//指定这是一个操作数据库的mapper
public interface UserMapper {
    List<User> findAll();
    User findById(Integer id);
}

7.com.zhg.demo.service.UserService

package com.zhg.demo.service;

import com.zhg.demo.entity.User;

import java.util.List;

public interface UserService {
    List<User> findAll();
    User findById(Integer id);
}

8.com.zhg.demo.service.impl.UserServiceImpl

package com.zhg.demo.service.impl;

import com.zhg.demo.entity.User;
import com.zhg.demo.mapper.UserMapper;
import com.zhg.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }
}

9.com.zhg.demo.controller.UserController

package com.zhg.demo.controller;

import com.zhg.demo.entity.User;
import com.zhg.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findAll")
    public List<User> findAll() {
        return userService.findAll();
    }

    @ResponseBody
    @RequestMapping("/abc")
    public ModelAndView abc(HttpServletRequest request) {
        String paramName = request.getParameter("name");/*get/post参数*/
        request.getSession().setAttribute("login",1);
        Object session = request.getSession().getAttribute("login");

        /*查询表中的多条数据*/
        List<User> users = userService.findAll();
        String userName = users.get(0).getUsername();

        /*条件查询*/
        User userOne = userService.findById(1);
        String password = userOne.getPassword();

        ModelAndView mv = new ModelAndView();
        mv.addObject("name", session);
        mv.setViewName("/abc.html");
        return mv;
    }
}

10.src/main/resources/templates/abc.html

<!DOCTYPE html>
<!--导入thymeleaf的名称空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text 为 Thymeleaf 属性,用于获取指定属性的值-->
<h1 th:text="'欢迎来到'+${name}"></h1>
<table>
    <tr th:each="m:${users}">
        <td th:text="${m.getUserName()}"></td>
    </tr>
</table>
</body>
</html>

 11.目录结构图如下

 

 注意: application.yml 的配置内容严格控制缩进, 由于缩进问题影响时间大概为2天。

声明:本文内容摘自网络,版权归原作者所有。如有侵权,请联系处理,谢谢~
转发:龍飛鳯舞--https://www.cnblogs.com/longfeiPHP/p/15710196.html

赞一个 (290)