SpringBoot 集成Mybatis 连接Mysql数据库

Stella981
• 阅读 782
记录SpringBoot 集成Mybatis 连接数据库 防止后面忘记
1.添加Mybatis和Mysql依赖

   
    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    1.1.1
  

  
    mysql
    mysql-connector-java
  

2.创建pojo,mapper,service,controller

此时项目结构

SpringBoot 集成Mybatis 连接Mysql数据库

3.配置application配置文件

SpringBoot 集成Mybatis 连接Mysql数据库

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


server.port=8080
server.tomcat.uri-encoding=UTF-8

#mybatis.config= classpath:mybatis-config.xml
mybatis.typeAliasesPackage=com.zld.student.bean
mybatis.mapperLocations=classpath:mappers/*Mapper.xml
4.添加接口

package com.zld.student.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zld.student.pojo.Student;
import com.zld.student.service.StudentService;

@RestController
@RequestMapping("student")
public class StudentController {

@Autowired
StudentService studentService;

@RequestMapping(value = "/add", method = { RequestMethod.GET, RequestMethod.POST })
public String add(Student student) {
return studentService.add(student);

}

@RequestMapping(value = "/delete", method = { RequestMethod.GET, RequestMethod.POST })
public String delete(
@RequestParam(value = "ids", required = false) String[] ids) {
if (ids != null && ids.length <= 0) {
return "Ids不能为空";
}
return studentService.delete(ids);
}

@RequestMapping(value = "/update", method = { RequestMethod.GET, RequestMethod.POST })
public String update(Student student) {
return studentService.update(student);
}

@RequestMapping(value = "/findList", method = { RequestMethod.GET, RequestMethod.POST })
public Map<String, Object> findEqList(
) {
Map<String, Object> data = new HashMap<String, Object>();
List list=studentService.findEqList();
if (list.isEmpty()) {
data.put("msg", "无数据");
return data;
}
data.put("list", list);
return data;
}

@RequestMapping(value = "/findById", method = { RequestMethod.GET, RequestMethod.POST })
public Student findByIds(
@RequestParam(value = "id", required = false) Integer id) {
return studentService.findById(id);
}

}

SpringBoot 集成Mybatis 连接Mysql数据库 SpringBoot 集成Mybatis 连接Mysql数据库

package com.zld.student.service;

import java.util.List;

import com.zld.student.pojo.Student;

public interface StudentService {

    String add(Student student);

    String delete(String[] ids);

    String update(Student student);

    List<Student> findEqList();

    Student findById(Integer id);

}

StudentService

SpringBoot 集成Mybatis 连接Mysql数据库 SpringBoot 集成Mybatis 连接Mysql数据库

package com.zld.student.service.impl;

import java.util.List;

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

import com.zld.student.mapper.StudentMapper;
import com.zld.student.pojo.Student;
import com.zld.student.service.StudentService;

@Service
public class StudentServiceImpl implements  StudentService{
    
    @Autowired 
    private StudentMapper studentMapper;
    
    @Override
    public String add(Student student) {
        try {
            int addCount = studentMapper.insertSelective(student);
            if(addCount>0){
                return "添加成功";
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("数据添加失败");
        }
        return "添加失败";
    }

    @Override
    public String delete(String[] ids) {
        try {
            int deleteCount = studentMapper.deleteAll(ids);
            if(deleteCount>0){
                return "删除成功";
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("数据删除失败");
        }
        return "删除失败";
    }

    @Override
    public String update(Student student) {
        try {
            int updateCount = studentMapper.updateByPrimaryKeySelective(student);
            if(updateCount>0){
                return "修改成功";
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("数据修改失败");
        }
        return "数据失败";
    }

    @Override
    public List<Student> findEqList() {
        List<Student> data=null;
        try {
            data= studentMapper.findList();
            return data;
        } catch (Exception e) {
            System.err.println("数据修改失败");
            e.printStackTrace();
            return data;
        }
        
    }
    @Override
    public Student findById(Integer id) {
        // TODO Auto-generated method stub
        return id==null ? new Student(): studentMapper.selectByPrimaryKey(id);
    }

}

StudentServiceImpl

SpringBoot 集成Mybatis 连接Mysql数据库 SpringBoot 集成Mybatis 连接Mysql数据库

package com.zld.student.mapper;

import java.util.List;

import com.zld.student.pojo.Student;

public interface StudentMapper {
    int deleteByPrimaryKey(Integer sno);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer sno);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);

    int deleteAll(String[] ids);

    List<Student> findList();
}

StudentMapper.java

SpringBoot 集成Mybatis 连接Mysql数据库 SpringBoot 集成Mybatis 连接Mysql数据库

<?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.zld.student.mapper.StudentMapper" >
  <resultMap id="BaseResultMap" type="com.zld.student.pojo.Student" >
    <id column="sno" property="sno" jdbcType="INTEGER" />
    <result column="sname" property="sname" jdbcType="VARCHAR" />
    <result column="sage" property="sage" jdbcType="TIMESTAMP" />
    <result column="ssex" property="ssex" jdbcType="CHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    sno, sname, sage, ssex
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from student
    where sno = #{sno,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from student
    where sno = #{sno,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.zld.student.pojo.Student" >
    insert into student (sno, sname, sage, 
      ssex)
    values (#{sno,jdbcType=INTEGER}, #{sname,jdbcType=VARCHAR}, #{sage,jdbcType=TIMESTAMP}, 
      #{ssex,jdbcType=CHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.zld.student.pojo.Student" >
    insert into student
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="sno != null" >
        sno,
      </if>
      <if test="sname != null" >
        sname,
      </if>
      <if test="sage != null" >
        sage,
      </if>
      <if test="ssex != null" >
        ssex,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="sno != null" >
        #{sno,jdbcType=INTEGER},
      </if>
      <if test="sname != null" >
        #{sname,jdbcType=VARCHAR},
      </if>
      <if test="sage != null" >
        #{sage,jdbcType=TIMESTAMP},
      </if>
      <if test="ssex != null" >
        #{ssex,jdbcType=CHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.zld.student.pojo.Student" >
    update student
    <set >
      <if test="sname != null" >
        sname = #{sname,jdbcType=VARCHAR},
      </if>
      <if test="sage != null" >
        sage = #{sage,jdbcType=TIMESTAMP},
      </if>
      <if test="ssex != null" >
        ssex = #{ssex,jdbcType=CHAR},
      </if>
    </set>
    where sno = #{sno,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.zld.student.pojo.Student" >
    update student
    set sname = #{sname,jdbcType=VARCHAR},
      sage = #{sage,jdbcType=TIMESTAMP},
      ssex = #{ssex,jdbcType=CHAR}
    where sno = #{sno,jdbcType=INTEGER}
  </update>
  
   <delete id="deleteAll" parameterType="java.lang.String" >
    delete from student
    where sno in <foreach item="id" collection="array" open="(" separator=","
            close=")">
            #{id}
        </foreach>
  </delete>
  
    <select id="findList" resultMap="BaseResultMap" >
    select 
    <include refid="Base_Column_List" />
    from student
  </select>
</mapper>

StudentMapper.xml

SpringBoot 集成Mybatis 连接Mysql数据库 SpringBoot 集成Mybatis 连接Mysql数据库

package com.zld.student.pojo;

import java.util.Date;

public class Student {
    private Integer sno;

    private String sname;

    private Date sage;

    private String ssex;

    public Integer getSno() {
        return sno;
    }

    public void setSno(Integer sno) {
        this.sno = sno;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname == null ? null : sname.trim();
    }

    public Date getSage() {
        return sage;
    }

    public void setSage(Date sage) {
        this.sage = sage;
    }

    public String getSsex() {
        return ssex;
    }

    public void setSsex(String ssex) {
        this.ssex = ssex == null ? null : ssex.trim();
    }
}

Student

SpringBoot 集成Mybatis 连接Mysql数据库 SpringBoot 集成Mybatis 连接Mysql数据库

package com.zld.student;

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

@SpringBootApplication
@MapperScan(basePackages = {"com.zld.student.mapper"})
public class DemoApplication {

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

DemoApplication

最后项目结构

SpringBoot 集成Mybatis 连接Mysql数据库

最近一直忙于前端写篇文章记录下来,免得以后捡起来的时候需要重新翻资料

-----只有用尽全力,才能看起来毫不费劲

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这