springboot+mybatis+mysql

6 篇文章 0 订阅
4 篇文章 0 订阅

pom文件

<?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.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-boot-test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-test</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!-- web模块 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
	<!-- 日志 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <!-- mybatis模块 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!-- mysql的java连接依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- lombok依赖 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- spring boot 单元测试模块 -->
        <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>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.yml文件

server:
  port: 8080

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
  config-location: classpath:mybatis-config.xml
logging:
  level:
    com.example.springboot.mapper: debug

mybatis-config.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<!-- mybatis的主配置文件 -->
<configuration>

    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer"/>
        <typeAlias alias="Long" type="java.lang.Long"/>
        <typeAlias alias="HashMap" type="java.util.HashMap"/>
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/>
        <typeAlias alias="ArrayList" type="java.util.ArrayList"/>
        <typeAlias alias="LinkedList" type="java.util.LinkedList"/>
    </typeAliases>

</configuration>

modul

package com.example.springboot.modul;

import lombok.*;

@ToString
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Data
public class Student {

    private Integer id;
    private String name;
    private Integer age;
    private String email;
    private String password;
    private String classNum;

}

mapper

package com.example.springboot.mapper;

import com.example.springboot.modul.Student;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 
 * @Description:
 * @data: 2020/8/20 15:50 PM
 */

@Mapper
public interface StudentMapper {
    /**
     * @param student
     * @return 插入的条数
     * 单条插入
     * private Integer id;
     * private String name;
     * private Integer age;
     * private String email;
     * private String password;
     * private String classNum;
     */
    @Insert("insert into student(name, age, email, password, class_num) " +
            " values(#{name}, #{age}, #{email}, #{password}, #{classNum})")
    // 该注解会返回插入新插入数据的自增主键
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int addStudent(Student student);


    /**
     * @param students
     * @return 插入的条数
     * 批量插入
     */
    @Insert({
            "<script> ",
            "insert into student(name, age, email, password, class_num) ",
            "values ",
            "<foreach collection='students' item='item' index='index' separator=','> ",
            "(#{item.name}, #{item.age}, #{item.email}, #{item.password}, #{item.classNum}) ",
            "</foreach> ",
            "</script>"

    })
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int addStudents(@Param(value = "students") List<Student> students);


    /**
     * @return 查询出的数据
     * 查询sql
     */
    @Select({
            "<script> ",
            "select * from student ",
            "<where> 1=1 ",
            "<if test='ids != null'> ",
            "and id in ",
            "<foreach collection='ids' item='item' index='index' open='(' close=')' separator=','> ",
            "#{item}",
            "</foreach> ",
            "</if> ",
            "</where> ",
            "</script>"
    })
    // 表字段和实体字段不一致时做映射
    @Results({
            @Result(property = "classNum", column = "class_num")
    })
    List<Student> selectStudents(@Param(value = "ids") List<Integer> ids);

    /**
    * @return 删除条数
    * 根据id批量删除
    */
    @Delete({
            "<script> ",
            "delete from student where id in ",
            "<foreach collection='ids' item='item' index='index' open='(' close=')' separator=','> ",
            "#{item} ",
            "</foreach>",
            "</script>"
    })
    int deleteStudents(@Param(value = "ids") List<Integer> ids);

}

service

package com.example.springboot.service;

import com.example.springboot.modul.Student;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 
 * @Description:
 * @data: 2020/8/20 16:03 PM
 */
public interface StudentService {

    int saveStudent(Student student);

    int saveStudents(List<Student> students);

    List<Student> showStudents(List<Integer> ids);

    int removeStudents(List<Integer> ids);

}

serviceimpl

package com.example.springboot.service.impl;

import com.example.springboot.mapper.StudentMapper;
import com.example.springboot.modul.Student;
import com.example.springboot.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * Created with IntelliJ IDEA.
 *
 * @author: 
 * @Description:
 * @data: 2020/8/20 16:10 PM
 */

@Service
public class StudentServiceImpl implements StudentService {

    private static final Logger LOG = LoggerFactory.getLogger(StudentService.class);

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public int saveStudent(Student student) {
        int i = studentMapper.addStudent(student);
        LOG.info("插入的数据为" + student.toString());
        return i;
    }

    /**
     * @param students
     * @return 插入的条数
     * 批量插入
     */
    @Override
    public int saveStudents(List<Student> students) {

        if (students.size() == 0 || students.isEmpty()) {
            LOG.info("没有需要插入的数据");
            return 0;
        }

        int i = studentMapper.addStudents(students);
        LOG.info("插入的数据为" + students.toString());
        return i;
    }

    @Override
    public List<Student> showStudents(List<Integer> ids) {
        List<Student> students = studentMapper.selectStudents(ids);
        return students;
    }

    /**
     * @param ids
     * @return 删除条数
     */
    @Override
    public int removeStudents(List<Integer> ids) {
        if (ids.isEmpty() || ids.size() == 0) {
            LOG.info("没有选中需要删除的数据");
            return 0;
        }
        int i = studentMapper.deleteStudents(ids);
        LOG.info("删除了" + i + "条数据");
        return i;
    }
}

controller

package com.example.springboot.controller;

import com.example.springboot.modul.Student;
import com.example.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class ControllerTest {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/info")
    public String info() {
        return "hello world";
    }


    /**
     * @return 单个插入
     */
    @RequestMapping("/save")
    public Student savaStudent() {
        Student student = new Student();

        student.setName("ww");
        student.setAge(18);
        student.setEmail("24@qq.com");
        student.setPassword("123456");
        student.setClassNum("1903");

        int i = studentService.saveStudent(student);

        System.out.println("插入了 " + i + " 条数据");
        return student;
    }


    /**
     * @return 查询所有
     */
    @RequestMapping("/show")
    public List<Student> showStudent() {

        ArrayList<Integer> ids = new ArrayList<>();

        ids.add(5);
        ids.add(6);
        ids.add(10);

        List<Student> students = studentService.showStudents(ids);
        return students;
    }

    /**
     * @return 批量插入
     */
    @RequestMapping("/saves")
    public List<Student> saveStudents() {
        ArrayList<Student> students = new ArrayList<>();
        Student student = new Student();

        student.setName("阿斯蒂芬");
        student.setAge(18);
        student.setEmail("24@qq.com");
        student.setPassword("123456");
        student.setClassNum("1903");

//        students.add(student);

        int i = studentService.saveStudents(students);
        System.out.println("插入了 " + i + " 条数据");
        return students;
    }

    @RequestMapping("/remove")
    public List<Student> removeStudents() {
        ArrayList<Integer> ids = new ArrayList<>();

        ids.add(12);
        ids.add(13);
        ids.add(14);

        List<Student> students = studentService.showStudents(ids);

        studentService.removeStudents(ids);

        return students;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值