springboot增删改查案例

github地址

https://github.com/daily11/springboot

1 目录结构

springboot增删改查案例_第1张图片

2 依赖

2.1 POM依赖


    org.springframework.boot
    spring-boot-starter-web



    mysql
    mysql-connector-java
    runtime



    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    2.0.1



    com.alibaba
    druid-spring-boot-starter
    1.1.9


    org.apache.httpcomponents
    httpclient
    4.3.1


    com.alibaba
    fastjson
    1.1.41

2.2 数据库配置类

package com.swust.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = MybatisDB.PACKAGE, sqlSessionFactoryRef = "localSqlSessionFactory")
public class MybatisDB {
    // 精确到 local 目录,以便跟其他数据源隔离
    static final String PACKAGE = "com.swust.springboot.dao";
    static final String MAPPER_LOCATION = "classpath:mapper/*.xml";

    @Value("${local.datasource.url}")
    private String url;

    @Value("${local.datasource.username}")
    private String user;

    @Value("${local.datasource.password}")
    private String password;

    @Value("${local.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "localDataSource")
    public DataSource localDataSource() {
        DruidDataSource localSource = new DruidDataSource();
        localSource.setDriverClassName(driverClass);
        localSource.setUrl(url);
        localSource.setUsername(user);
        localSource.setPassword(password);
        return localSource;
    }

    @Bean(name = "localTransactionManager")
    public DataSourceTransactionManager localTransactionManager() {
        return new DataSourceTransactionManager(localDataSource());
    }

    @Bean(name = "localSqlSessionFactory")
    public SqlSessionFactory localSqlSessionFactory(@Qualifier("localDataSource") DataSource localDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(localDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MybatisDB.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

2.3 配置文件

# 应用端口号
server.port=8080

# bdgisbase 数据库地址
local.datasource.url=jdbc:mysql://localhost:3306/permission?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
local.datasource.driverClassName=com.mysql.cj.jdbc.Driver
local.datasource.username=root
local.datasource.password=root

3 controller

package com.swust.springboot.controller;

import com.swust.springboot.aop.DemoAnnotationService;
import com.swust.springboot.entity.BookDO;
import com.swust.springboot.service.BookService;
import com.swust.springboot.utils.CODE;
import com.swust.springboot.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private DemoAnnotationService demoAnnotationService;

    @RequestMapping(value = "/selectByIdReturnMap", method = RequestMethod.POST)
    private Result selectByIdReturnMap() {
        List list = bookService.selectByIdReturnMap();
        System.out.println(list.toString());
        return new Result(CODE.SUCCESS, list, "success");
    }


    /**
     * 查询书记录
     *
     * @param name 书名
     * @return
     */
    @RequestMapping(value = "/selectByName", method = RequestMethod.POST)
    private Result selectByName(String name) {
        try {
            BookDO book = bookService.selectByName(name);
            demoAnnotationService.add();
            return new Result(CODE.SUCCESS, book, "查询成功!");
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Result(CODE.ERROR, null, "查询失败!");
        }
    }

    /**
     * 查询书记录
     *
     * @param id 书ID
     * @return
     */
    @RequestMapping(value = "/selectById", method = RequestMethod.POST)
    private Result selectById(long id) {
        try {
            BookDO book = bookService.selectById(id);
            return new Result(CODE.SUCCESS, book, "查询成功!");
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Result(CODE.ERROR, null, "查询失败!");
        }
    }

    /**
     * 删除书记录
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    private Result deleteById(long id) {
        try {
            Integer num = bookService.deleteById(id);
            return new Result(CODE.SUCCESS, num, "查询成功!");
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Result(CODE.ERROR, null, "查询失败!");
        }
    }

    /**
     * 插入书记录
     *
     * @param bookDO 书对象
     * @return
     */
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    private Result insert(BookDO bookDO) {
        try {
            Integer num = bookService.insert(bookDO);
            return new Result(CODE.SUCCESS, num, "查询成功!");
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Result(CODE.ERROR, null, "查询失败!");
        }
    }

    /**
     * 更新书记录
     *
     * @param bookDO 书对象
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    private Result update(BookDO bookDO) {
        try {
            System.out.println("客户端上传--->" + bookDO.toString());
            Integer num = bookService.update(bookDO);
            return new Result(CODE.SUCCESS, num, "查询成功!");
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Result(CODE.ERROR, null, "查询失败!");
        }
    }
}

4 service

package com.swust.springboot.service.impl;

import com.swust.springboot.dao.BookDao;
import com.swust.springboot.entity.BookDO;
import com.swust.springboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    @Override
    public List selectByIdReturnMap() {
        return bookDao.selectByIdReturnMap();
    }

    /**
     * 查询书记录
     *
     * @param name 书名
     * @return
     */
    @Override
    public BookDO selectByName(String name) {
        return bookDao.selectByName(name);
    }

    /**
     * 查询书记录
     *
     * @param id 书ID
     * @return
     */
    @Override
    public BookDO selectById(Long id) {
        return bookDao.selectById(id);
    }

    /**
     * 删除书记录
     *
     * @param id
     * @return
     */
    @Override
    public Integer deleteById(Long id) {
        return bookDao.deleteById(id);
    }

    /**
     * 插入书记录
     *
     * @param book 书对象
     * @return
     */
    @Override
    public Integer insert(BookDO book) {
        return bookDao.insert(book);
    }

    /**
     * 更新书记录
     *
     * @param book 书对象
     * @return
     */
    @Override
    public Integer update(BookDO book) {
        return bookDao.update(book);
    }
}

5 dao

package com.swust.springboot.dao;


import com.swust.springboot.entity.BookDO;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

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

@Repository
public interface BookDao {

    /**
     * 查询书记录
     *
     * @param name 书名
     * @return
     */
    BookDO selectByName(@Param("bookName") String name);

    /**
     * 查询书记录
     * 以map形式返回
     *
     * @return
     */
    List selectByIdReturnMap();

    /**
     * 查询书记录
     *
     * @param id 书ID
     * @return
     */
    BookDO selectById(@Param("bookId") Long id);

    /**
     * 删除书记录
     *
     * @param id
     * @return
     */
    Integer deleteById(@Param("bookId") Long id);

    /**
     * 插入书记录
     *
     * @param book 书对象
     * @return
     */
    Integer insert(BookDO book);

    /**
     * 更新书记录
     *
     * @param book 书对象
     * @return
     */
    Integer update(BookDO book);

}

6 entity

package com.swust.springboot.entity;

import java.util.Date;

public class BookDO {
    private Long id;
    private String name;
    private Date gmtCreate;
    private Date gmtModified;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Date getGmtCreate() {
        return gmtCreate;
    }

    public void setGmtCreate(Date gmtCreate) {
        this.gmtCreate = gmtCreate;
    }

    public Date getGmtModified() {
        return gmtModified;
    }

    public void setGmtModified(Date gmtModified) {
        this.gmtModified = gmtModified;
    }

    @Override
    public String toString() {
        return "BookDO{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gmtCreate=" + gmtCreate +
                ", gmtModified=" + gmtModified +
                '}';
    }
}

7 mapper






    
        
        
        
        
    

    
        id,name,gmt_create,gmt_modified
    

    
    

    
    

    
    
    
    
    
    
    
    
    

    
    
        delete from book where id = #{bookId}
    

    
    
        INSERT INTO book
        
            
                gmt_create,
            
            
                gmt_modified,
            
            
                name,
            
        
        
            
                #{gmtCreate},
            
            
                #{gmtModified},
            
            
                #{name},
            
        
    

    
    
        update book
        
            
                name=#{name},
            
            gmt_modified = sysdate()
        
        
        
            
                and id = #{id}
            
        
    

    
    
        
            
                and id = #{id}
            
            
                and name = #{name}
            
            
                and gmt_create = #{gmtCreate}
            
            
                and gmt_modified = #{gmtModified}
            
        
    

8 工具类

package com.swust.springboot.utils;


public class CODE {
    //前端访问请求成功
    public static final int SUCCESS = 200;
    //前端访问请求失败
    public static final int ERROR = 500;

    //账号状态 禁用
    public static final int ACCOUT_LOCK = 0;
    //账号状态 正常
    public static final int ACCOUT_UNLOCK = 1;

}
package com.swust.springboot.utils;


public class Result {

    private int code;
    private Object data;
    private String msg;

    public Result(int code, Object data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

9 数据库SQL文件

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 50549
 Source Host           : localhost:3306
 Source Schema         : springboot

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

 Date: 02/09/2019 14:18:24
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `gmt_create` timestamp NULL DEFAULT NULL,
  `gmt_modified` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (2, 'cyx', '2019-09-02 13:59:04', '2019-09-02 14:03:58');
INSERT INTO `book` VALUES (3, 'zou', '2019-09-02 14:12:14', '2019-09-02 14:12:14');

SET FOREIGN_KEY_CHECKS = 1;

 

你可能感兴趣的:(spring)