• SpringBoot 集成Mybatis 连接Mysql数据库


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

       <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.1.1</version>
      </dependency>
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
      </dependency>

    2.创建pojo,mapper,service,controller

    此时项目结构

    3.配置application配置文件

    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<Student> 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);
    }

    }

    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
    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
    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
    <?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
    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
    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

    最后项目结构

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

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

  • 相关阅读:
    Vue Scroller:Vue 下拉刷新及无限加载组件
    vue引用公用的头部和尾部文件。
    Java后期拓展(三)Nginx ——高性能的HTTP和反向代理服务器
    JAVA后期拓展(二)ZooKeeper——分布式应用程序协调服务系统
    Java高级部分
    Java后期拓展(一)非关系型数据库Redis
    LoadRunner(四)——深度了解LR相关功能
    LoadRunner(三)——LR相关概念&组成部分
    LoadRunner(二)——性能测试过程概述
    LoadRunner(一)——性能测试基础及性能指标概述
  • 原文地址:https://www.cnblogs.com/shaoniandream/p/9682385.html
Copyright © 2020-2023  润新知