SpringBoot整合mybatis

软件版本:
mysql:8.0.20
springboot:2.1.16
关于springboot整合jsp的方法可以参考
https://blog.csdn.net/u014520586/article/details/108350576

maven依赖:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--        引入jsp依赖-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <!--  <scope>provided</scope>-->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jsp-api</artifactId>
        </dependency>
        <!--        引入jsp依赖 结束-->
        <!--        引入lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
<!--引入bootstrap-->

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

yml文件配置
application.yml

spring:
    mvc:
        view:
            prefix: /
            suffix: .jsp

    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/ems?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&characterEncoding=UTF8
        username: root
        password:



#mybatis:
#    mapper-locations: classpath:com/lzh/emp/dao/*.xml
#    type-aliases-package: com.lzh.emp.entity


server:
    servlet:
        context-path: /emps
        jsp:
            init-parameters:
                development: true #开启jsp热部署
    port: 80

sql语句

-- --------------------------------------------------------
-- 主机:                           127.0.0.1
-- 服务器版本:                        8.0.20 - MySQL Community Server - GPL
-- 服务器操作系统:                      Win64
-- HeidiSQL 版本:                  11.0.0.5919
-- --------------------------------------------------------

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;


-- 导出 ems 的数据库结构
CREATE DATABASE IF NOT EXISTS `ems` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `ems`;

-- 导出  表 ems.t_emp 结构
CREATE TABLE IF NOT EXISTS `t_emp` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(40) DEFAULT NULL,
  `salary` double(7,2) DEFAULT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

-- 正在导出表  ems.t_emp 的数据:~4 rows (大约)
/*!40000 ALTER TABLE `t_emp` DISABLE KEYS */;
INSERT INTO `t_emp` (`id`, `name`, `salary`, `age`) VALUES
	(2, '2', 2.00, 23),
	(3, 'test2', 2100.00, 25),
	(4, 'test2', 2100.00, 25),
	(5, 'test2', 2100.00, 25);
/*!40000 ALTER TABLE `t_emp` ENABLE KEYS */;

/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;

实体类:

public class Emp {
    private Integer id;
    private String name;
    private Double salary;
    private Integer age;

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

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public Integer getAge() {
        return age;
    }

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

dao
代码说明:dao层属于数据访问层,与mybatis 的xml文件相互映射,实现SQL语句的功能。

注解说明:在dao层的类需要加上 @Mapper的注解,这个注解是mybatis提供的,标识这个类是一个数据访问层的bean,并交给spring容器管理。并且可以省去之前的xml映射文件。在编译的时候,添加了这个类也会相应的生成这个类的实现类。

@Repository
@Mapper
public interface EmpDao {
    @Select("select * from t_emp")
    public List<Emp> findAll();

    @Insert("insert into t_emp (name, salary, age) values (#{name}, #{salary}, #{age})")
    void save(Emp emp);

    @Delete("delete from t_emp where id = #{id}")
    void delete(Integer id);

    @Select("select * from t_emp where id = #{id}")
    Emp findById(Integer id);

    @Update("update t_emp set name = #{name}, salary = #{salary}, age = #{age} where id = #{id}")
    void update(Emp emp);
}

service

import com.lzh.demo01.entity.Emp;

import java.util.List;

public interface EmpService {

    List<Emp> findAll();

    void save(Emp emp);

    void delete(Integer id);

    Emp findById(Integer id);

    void update(Emp emp);
}

serviceImpl

import com.lzh.demo01.dao.EmpDao;
import com.lzh.demo01.entity.Emp;
import com.lzh.demo01.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    EmpDao empDao;

    @Override
    public List<Emp> findAll() {
        return empDao.findAll();
    }

    @Override
    public void save(Emp emp) {
        empDao.save(emp);
    }

    @Override
    public void delete(Integer id) {
        empDao.delete(id);
    }

    @Override
    public Emp findById(Integer id) {
        return empDao.findById(id);
    }

    @Override
    public void update(Emp emp) {
        empDao.update(emp);
    }
}

controller

import com.lzh.demo01.entity.Emp;
import com.lzh.demo01.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmpController {
    @Autowired
    EmpService empService;

    @GetMapping("/findAll")
    public String findAll2(Model model) {
//        System.out.println("controller start");
        List<Emp> emps = empService.findAll();
//        System.out.println(emps);

        model.addAttribute("empList", emps);
        return "/emp/emplist";
    }


    @PostMapping("/save")
    public String save(Emp emp){
        empService.save(emp);
        return "redirect:/emp/findAll";
    }

    @GetMapping("/delete")
    public String delete(Integer id) {
        empService.delete(id);
        return "redirect:/emp/findAll";
    }

    @GetMapping("/findOne")
    public String findOne(Integer id, Model model) {
        Emp emp = empService.findById(id);
        model.addAttribute("emp", emp);
        return "/emp/updateEmp";
    }

    @PostMapping("/update")
    public String update(Emp emp) {
        empService.update(emp);
        return "redirect:/emp/findAll";
    }
}

入口类

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.xxx.demo01.dao")
//你的dao类所在的包
public class Demo01Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo01Application.class, args);
    }

}

jsp文件
/emp/emplist.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<html>
<head>
    <title>所有员工</title>
</head>
<body>
<table>


    <c:forEach items="${empList}" var="emp">
        <tr>${emp.name}</tr>
        <tr>${emp.id}</tr>
    </c:forEach>
</table>

<h1>empslist.jsp</h1>
<table>
    <tr>
        <th>id</th>
        <th>name</th>
        <th>salary</th>
        <th>age</th>
        <th>operation</th>
    </tr>
    <c:forEach items="${empList}" var="emp">
    <tr>
        <td>${emp.id}</td>
        <td>${emp.name}</td>
        <td><fmt:formatNumber type="number" value="${emp.salary}" pattern="#.00"/></td>
        <td>${emp.age}</td>
        <td><a href="${pageContext.request.contextPath}/emp/delete?id=${emp.id}">delete</a> &nbsp; <a href="${pageContext.request.contextPath}/emp/findOne?id=${emp.id}">modify</a></td>

    </tr>
    </c:forEach>

</body>
</html>

浏览器访问 localhost/emps/emp/findAll

注意@MapperScan注解

@MapperScan与@Mapper:
@MapperScan 只会扫描包里面的接口,@MapperScan 是可以简化@Mapper 注解,@Mapper 注解需要对每一个接口都加上这个注解,但是@MapperScan是可以扫描这个包下面的所有的接口,对实体类,service等没用。然后一般来说,我们开发的时候都会接口和实体类分开

基于xml的开发需要在yml文件中加上配置, (如果使用注解开发就不要加以下配置)
并且删除dao类中各方法上的@Select/@Insert/@Update等注解

mybatis:
  mapper-locations: com/lzh/emp/dao/*.xml # xml映射文件的文件夹
  type-aliases-package: com.lzh.emp.entity # 实体类所在的包

然后编写相应的xml类
EmpDaoMapper.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.lzh.emp.dao.EmpDao">

    <select id="findAll" resultType="Emp">
        select * from t_emp
    </select>

    <insert id="save">
        insert into t_emp(name, salary, age) values(#{name}, #{salary}, #{age});
    </insert>

    <delete id="delete" parameterType="Integer">
        delete from t_emp where id = #{id};
    </delete>

    <select id="findById" parameterType="Integer" resultType="Emp">
        select * from t_emp where id = #{id};
    </select>

    <update id="update" parameterType="Emp">
        update t_emp set name = #{name}, salary = #{salary}, age = #{age} where id = #{id};
    </update>
</mapper>

整体目录结构
在这里插入图片描述

xml开发
https://blog.csdn.net/iku5200/article/details/82856621

mybatis各种注解详解
https://blog.csdn.net/qq_36027670/article/details/79606402

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值