精华内容
下载资源
问答
  • springboot增删改查

    2020-06-19 21:13:54
    使用SpringBoot实现增删改查 这个代码真的写的很棒
  • SpringBoot增删改查

    2019-04-04 09:15:42
    SpringBoot增删改查 开发工具基于IDEA + Maven + Navicat for MySQL 环境配置 配置Maven ​ 下载Maven后配置环境变量 MAVEN_HOME=upath %JAVA_HOME%\bin %MAVEN_HOME%\bin ​ 创建Maven本地仓库,并在%MAVEN_...

    SpringBoot增删改查

    开发工具基于IDEA + Maven + Navicat for MySQL

    环境配置

    配置Maven

    ​ 下载Maven后配置环境变量

    	MAVEN_HOME=upath
    	%JAVA_HOME%\bin
    	%MAVEN_HOME%\bin
    

    ​ 创建Maven本地仓库,并在%MAVEN_HOME%\conf\setting.xml路径下修改<LocalRepository>的路径为本地仓库路径

    IDEA配置Maven

    文件-设置-构建-构建工具-Maven

    • Maven home directory :Maven路径
    • User settings file :%MAVEN_HOME%\conf\setting.xml
    • Local repository :本地仓库路径

    项目制作

    创建项目

    1. 创建Spring Initializr项目
    2. Dependecies选择
      • Web选项勾选Web
      • Template Engines选项勾选Thymeleaf
      • SQL选项勾选MySQL+JDBC+Mybatis
    3. 完成创建后的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 http://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.1.3.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.pratice.persondemo</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>demo</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</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.0.0</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.45</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    

    创建数据库

    ​ 使用Navicat for MySQL创建数据库springdemo并使用该数据库创建persons

    use springdemo;
    create table persons(
        id int(3) primary key not null auto_increment,
        name varchar(50),
        gender varchar(10),
        age int(3)
    );
    

    创建JavaBean

    ​ 完成数据库创建后,在我们的项目中创建对应的JavaBean对象

    src-main-java-uProjectName在该目录下创建一个名为pojo的package

    ​ 创建完成后在pojo包下创建一个名为Person的java类

    public class Person {
        private int id;
        private String name;
        private String gender;
        private int age;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getGender() {
            return gender;
        }
    
        public void setGender(String gender) {
            this.gender = gender;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    

    三层架构

    mapper数据访问层

    1. 在properties文件中配置数据库驱动
    spring.datasource.url=uUrl
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.username=root
    spring.datasource.password=uPwd
    
    1. 数据访问层实现 接口+配置

      使用注释语句实现数据库数据操作

    @Mapper
    public interface PersonMapper {
        @Select("select * from persons")
        List<Person> getAllPersons();
    
        @Select("select * from persons where id=#{id}")
        Person getPersonByID(int id);
    
        @Insert("insert into persons(name,gender,age) values(#{name},#{gender},#{age})")
        int addPerson(Person person);
    
        @Update("update persons set name=#{name},gender=#{gender},age=#{age} where id=#{id}")
        int updatePerson(Person person);
    
        @Delete("delete from persons where id=#{id}")
        int deletePersonByID(int id);
    }
    

    service业务逻辑层

    1. Service接口
    public interface PersonService {
        List<Person> getAllPersons();
    
        Person getPersonByID(int id);
    
        int addPerson(Person person);
    
        int updatePerson(Person person);
    
        int deletePersonByID(int id);
    }
    
    1. Service接口实现类

      Autowired注解使用控制反转,由Spring自动按类型注入bean对象

      在Service层使用数据访问层mapper中的基本数据库操作组合实现业务逻辑操作。

    @Service
    public class PersonServiceImpl implements PersonService {
        @Autowired
        private PersonMapper personMapper;
        @Override
        public List<Person> getAllPersons() {
            return personMapper.getAllPersons();
        }
    
        @Override
        public Person getPersonByID(int id) {
            return personMapper.getPersonByID(id);
        }
    
        @Override
        public int addPerson(Person person) {
            return personMapper.addPerson(person);
        }
    
        @Override
        public int updatePerson(Person person) {
            return personMapper.updatePerson(person);
        }
    
        @Override
        public int deletePersonByID(int id) {
            return personMapper.deletePersonByID(id);
        }
    }
    

    controller + 页面 表示层

    • RequestMapping(“url”) 指定路径
    • Map<String,Object> 键值对形式,对页面传参
    • return “url” 返回template中的路径
    • 页面代码中使用过<html lang="en" xmlns:th="http://www.thymeleaf.org">加载模板引擎
    1. 查找所有记录

      controller方法实现

          @RequestMapping("/list")
          public String getAllPersons(Map<String,Object> map){
              List<Person> list=personService.getAllPersons();
              map.put("persons", list);
              return "person/list";
          }
      

      页面实现

      <!DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
          <meta charset="UTF-8">
          <title>人员信息表</title>
      </head>
      <body>
          <a th:href="@{/add}">添加记录</a>
          <table border="1px">
              <tr>
                  <td colspan="6" align="center">人员信息表</td>
              </tr>
              <tr>
                  <td>ID</td>
                  <td>姓名</td>
                  <td>性别</td>
                  <td>年龄</td>
              </tr>
              <tr th:each="person:${persons}">
                  <td th:text="${person.id}">ID</td>
                  <td th:text="${person.name}">姓名</td>
                  <td th:text="${person.gender}">性别</td>
                  <td th:text="${person.age}">年龄</td>
              </tr>
          </table>
      </body>
      </html>
      
    2. 添加记录

      controller方法实现

          @GetMapping("/add")
          public String addPerson(){
              return "person/add";
          }
      
          @PostMapping("/add")
          public String addPerson(Person person){
              personService.addPerson(person);
              return "redirect:/list";
          }
      

      页面实现

      <!DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
          <meta charset="UTF-8">
          <title>添加记录</title>
      </head>
      <body>
          <form th:action="@{/add}" th:method="post">
              <table border="1px">
                  <tr>
                      <td colspan="2" align="center">添加记录</td>
                  </tr>
                  <tr>
                      <td>姓名</td>
                      <td>
                          <input type="text" name="name"/>
                      </td>
                  </tr>
                  <tr>
                      <td>性别</td>
                      <td>
                          <select name="gender">
                              <option>请选择</option>
                              <option value=""></option>
                              <option value=""></option>
                          </select>
                      </td>
                  </tr>
                  <tr>
                      <td>年龄</td>
                      <td>
                          <input type="text" name="age"/>
                      </td>
                  </tr>
                  <tr>
                      <td colspan="2" align="center">
                          <input type="submit" value="添加"/>
                      </td>
                  </tr>
              </table>
          </form>
      </body>
      </html>
      
    3. 修改记录

      controller方法实现

          @GetMapping("/update/{id}")
          public String updatePerson(@PathVariable("id") int id,Map<String,Person> map){
              Person person = personService.getPersonByID(id);
              map.put("person", person);
              return "person/update";
          }
      
          @PostMapping("/update")
          public String updatePerson(Person person){
              personService.updatePerson(person);
              return "redirect:/list";
          }
      

      页面实现

      <!DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
          <meta charset="UTF-8">
          <title>修改记录</title>
      </head>
      <body>
          <form th:action="@{/update}" th:method="post">
              <input type="hidden" name="id" th:value="${person.id}"/>
              <table border="1px">
                  <tr>
                      <td colspan="2" align="center">修改记录</td>
                  </tr>
                  <tr>
                      <td>ID</td>
                      <td th:text="${person.id}"></td>
                  </tr>
                  <tr>
                      <td>姓名</td>
                      <td>
                          <input type="text" name="name" th:value="${person.name}"/>
                      </td>
                  </tr>
                  <tr>
                      <td>性别</td>
                      <td>
                          <select name="gender">
                              <option value="" th:selected="${person.gender}==''"></option>
                              <option value="" th:selected="${person.gender}==''"></option>
                          </select>
                      </td>
                  </tr>
                  <tr>
                      <td>年龄</td>
                      <td>
                          <input type="text" name="age" th:value="${person.age}"/>
                      </td>
                  </tr>
                  <tr>
                      <td colspan="2" align="center">
                          <input type="submit" value="修改"/>
                      </td>
                  </tr>
              </table>
          </form>
      </body>
      </html>
      
    4. 删除记录

      controller方法实现

          @GetMapping("/delete/{id}")
          public String deletePerson(@PathVariable("id") int id){
              personService.deletePersonByID(id);
              return "redirect:/list";
          }
      
    5. 完整controller类代码

    @Controller
    public class PersonController {
        @Autowired
        private PersonService personService;
        @RequestMapping("/list")
        public String getAllPersons(Map<String,Object> map){
            List<Person> list=personService.getAllPersons();
            map.put("persons", list);
            return "person/list";
        }
    
        @GetMapping("/add")
        public String addPerson(){
            return "person/add";
        }
    
        @PostMapping("/add")
        public String addPerson(Person person){
            personService.addPerson(person);
            return "redirect:/list";
        }
    
        @GetMapping("/update/{id}")
        public String updatePerson(@PathVariable("id") int id,Map<String,Person> map){
            Person person = personService.getPersonByID(id);
            map.put("person", person);
            return "person/update";
        }
    
        @PostMapping("/update")
        public String updatePerson(Person person){
            personService.updatePerson(person);
            return "redirect:/list";
        }
    
        @GetMapping("/delete/{id}")
        public String deletePerson(@PathVariable("id") int id){
            personService.deletePersonByID(id);
            return "redirect:/list";
        }
    }
    
    1. 完整list页面代码
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>人员信息表</title>
    </head>
    <body>
        <a th:href="@{/add}">添加记录</a>
        <table border="1px">
            <tr>
                <td colspan="6" align="center">人员信息表</td>
            </tr>
            <tr>
                <td>ID</td>
                <td>姓名</td>
                <td>性别</td>
                <td>年龄</td>
                <td>修改</td>
                <td>删除</td>
            </tr>
            <tr th:each="person:${persons}">
                <td th:text="${person.id}">ID</td>
                <td th:text="${person.name}">姓名</td>
                <td th:text="${person.gender}">性别</td>
                <td th:text="${person.age}">年龄</td>
                <td><a th:href="@{/update/}+${person.id}">修改</a></td>
                <td><a th:href="@{/delete/}+${person.id}" onclick="return confirm('确定要删除该记录吗?')">删除</a></td>
            </tr>
        </table>
    </body>
    </html>
    

    打包项目

    • 项目右侧选择Maven Projects
    • 选择Lifecycle-package
    • 右键选择Run Maven Build
    • 在项目的target包中便可以找到打包后项目的jar包
    • 在命令行中运行java -jar xxx.jar便可以实现脱离开发环境运行
    展开全文
  • SpringBoot:SpringBoot增删改查补充发布下载
  • springboot 增删改查

    2020-04-13 09:03:17
    配置springboot server: port: 8080 # jdbc 的配置 spring: datasource: url: jdbc:mysql://localhost:3306/db_gm?userSSL=true&characterEncoding=utf-8&&serverTimezone=UTC username: root ...

    配置springboot

    server:
      port: 8080
    
    #  jdbc 的配置
    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/db_gm?userSSL=true&characterEncoding=utf-8&&serverTimezone=UTC
        username: root
        password: 123456
    
    #  视图解析器
      mvc:
        view:
          prefix: /
          suffix: .html
    
    # Mybatis
      mybatis:
        type-aliases-package: it.gm.springboot.pojo
    
    

    dao层

    package it.gm.springboot.dao;
    
    import it.gm.springboot.pojo.UserInfor;
    import org.apache.ibatis.annotations.Delete;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Select;
    import org.apache.ibatis.annotations.Update;
    
    import java.util.List;
    
    public interface UserInforDao {
    //    添加
    @Insert("insert into tb_user(username,password) values(#{username},#{password})")
        int addUser(UserInfor userInfor);
    //      删除
        @Delete("delete from tb_user where id =#{id}")
        int delUser(int id);
    //    修改
        @Update("update tb_user set username=#{username},password = #{password} where id = #{id}")
        int updUser(UserInfor userInfor);
    //    查询所有
        @Select("select * from tb_user")
        List<UserInfor> findAllUser();
    //    查询单个
        @Select("select * from tb_user where id =#{id}")
        UserInfor findUserById(int id);
    }
    
    

    service层

    package it.gm.springboot.service;
    import it.gm.springboot.pojo.UserInfor;
    
    import java.util.List;
    
    public interface UserInforService {
    //    添加用户
        int addUser(UserInfor userInfor);
    
    //    删除用户
        int delUser(int id);
    
    //    修改用户
        int updUser(UserInfor userInfor);
    
    //    查询所有
        List<UserInfor> findAllUser();
    
    //    查询单个用户
        UserInfor findUserById(int id);
    }
    
    

    实现类

    package it.gm.springboot.service.Impl;
    
    import it.gm.springboot.dao.UserInforDao;
    import it.gm.springboot.pojo.UserInfor;
    import it.gm.springboot.service.UserInforService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class UserInforServiceDaoImpl implements UserInforService {
        @Autowired
        private UserInforDao userInforDao;
        @Override
        public int addUser(UserInfor userInfor) {
            return userInforDao.addUser(userInfor);
        }
    
        @Override
        public int delUser(int id) {
            return userInforDao.delUser(id);
        }
    
        @Override
        public int updUser(UserInfor userInfor) {
            return userInforDao.updUser(userInfor);
        }
    
        @Override
        public List<UserInfor> findAllUser() {
            return userInforDao.findAllUser();
        }
    
        @Override
        public UserInfor findUserById(int id) {
            return userInforDao.findUserById(id);
        }
    }
    
    

    controller层

    package it.gm.springboot.controller;
    
    import it.gm.springboot.pojo.UserInfor;
    import it.gm.springboot.service.UserInforService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.List;
    
    @Controller
    @RequestMapping("/userInforController")
    public class UserInforController {
        @Autowired
        private UserInforService userInforService;
    
        @RequestMapping("/addUser")
        public String addUser(UserInfor userInfor){
            int i = userInforService.addUser(userInfor);
            if (i>0){
                System.out.println("添加成功");
            }
            else {
                System.out.println("添加失败");
            }
            return "index";
        }
        @RequestMapping("/delUser")
        public String delUser(int id){
            int i = userInforService.delUser(id);
            if (i>0){
                System.out.println("删除成功");
            }
            else {
                System.out.println("删除失败");
            }
            return "index";
        }
        @RequestMapping("/updUser")
        public String updUser(UserInfor userInfor){
            int i = userInforService.updUser(userInfor);
            if (i>0){
                System.out.println("修改成功");
            }
            else {
                System.out.println("修改失败");
            }
            return "index";
        }
        @RequestMapping("/findAllUser")
        public String findAllUser(){
            List<UserInfor> allUser = userInforService.findAllUser();
            for (UserInfor userInfor:allUser){
                System.out.println(userInfor);
                System.out.println();
            }
            return "index";
        }
        @RequestMapping("/findUserById")
        public String findUserById(int id){
            UserInfor userInfor = userInforService.findUserById(id);
            System.out.println(userInfor);
            return "index";
        }
    }
    
    

    html成功页面

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>成功页面</title>
    </head>
    <body>
    成功了
    </body>
    </html>
    

    填写dao层扫描路径,配置自动打开默认页面

    package it.gm.springboot;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.context.event.ApplicationReadyEvent;
    import org.springframework.context.event.EventListener;
    
    import java.io.IOException;
    
    @MapperScan("it.gm.springboot.dao")
    @SpringBootApplication
    public class SpringbootApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringbootApplication.class, args);
        }
        @EventListener({ApplicationReadyEvent.class})
        public void applicationReadyEvent() {
            System.out.println("应用已经准备就绪 ... 启动浏览器");
            String url = "http://localhost:8080";
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }
    
    
    展开全文
  • springboot增删改查模板

    2021-04-02 14:14:05
    springboot增删改查项目模板,适合新手练习,由swagger展示功能,localhost:8888/docs.html
  • springboot增删改查.7z

    2020-12-30 16:03:28
    springboot实现增删改查的功能+界面
  • springboot增删改查 IDEA

    千次阅读 2017-11-28 16:00:12
    springboot增删改查 IDEA版本:2017.1.5 运行方式:部署到tomcat中运行 数据库使用的mysql 程序中使用了mybatis,sql语句是写在xml中的 改项目是个maven项目

    IDEA版本:2017.1.5
    运行方式:部署到tomcat中运行
    数据库使用的mysql
    程序中使用了mybatis,sql语句是写在xml中的
    改项目是个maven项目

    1.项目结构

    这里写图片描述

    2.pom.xml文件

    <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.user</groupId>
        <artifactId>user-crud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
    
        <name>user-crud</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.8.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <!-- mybatis -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.1.1</version>
            </dependency>
            <!-- mysql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
            </dependency>
            <!-- tomcat -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <fork>true</fork>
                    </configuration>
                </plugin>
            </plugins>
        </build>

    3.application.properties文件

    mybatis.config-locations=classpath:mybatis/mybatis-config.xml
    mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
    mybatis.type-aliases-package=com.user.pojo
    
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    spring.datasource.url = jdbc:mysql://数据库ip:3306/数据库名?useUnicode=true&characterEncoding=utf-8
    spring.datasource.username = 用户名
    spring.datasource.password = 密码

    4.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">
    <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>

    5.UserMapper.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.user.dao.UserDao" >
    
      <resultMap id="BaseResultMap" type="com.user.pojo.UserPO" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
        <result column="phone" property="phone" jdbcType="VARCHAR" />
      </resultMap>
    
      <sql id="Base_Column_List" >
        id, name, password, age, phone
      </sql>
    
      <!-- 得到所有的用户信息 -->
      <select id="getAll" resultMap="BaseResultMap" >
        select
        <include refid="Base_Column_List" />
        from user
      </select>
    
      <!-- 根据id查找某个用户信息 -->
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from user
        where id = #{id,jdbcType=INTEGER}
      </select>
    
      <!-- 根据id删除某个用户信息 -->
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from user
        where id = #{id,jdbcType=INTEGER}
      </delete>
    
      <!-- 插入一条用户信息 -->
      <insert id="insertSelective" parameterType="com.user.pojo.UserPO" >
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            id,
          </if>
          <if test="name != null" >
            name,
          </if>
          <if test="password != null" >
            password,
          </if>
          <if test="age != null" >
            age,
          </if>
          <if test="phone != null" >
            phone,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            #{id,jdbcType=INTEGER},
          </if>
          <if test="name != null" >
            #{name,jdbcType=VARCHAR},
          </if>
          <if test="password != null" >
            #{password,jdbcType=VARCHAR},
          </if>
          <if test="age != null" >
            #{age,jdbcType=INTEGER},
          </if>
          <if test="phone != null" >
            #{phone,jdbcType=VARCHAR},
          </if>
        </trim>
      </insert>
    
      <!-- 根据id更新一条用户信息 -->
      <update id="updateByPrimaryKeySelective" parameterType="com.user.pojo.UserPO" >
        update user
        <set >
          <if test="name != null" >
            name = #{name,jdbcType=VARCHAR},
          </if>
          <if test="password != null" >
            password = #{password,jdbcType=VARCHAR},
          </if>
          <if test="age != null" >
            age = #{age,jdbcType=INTEGER},
          </if>
          <if test="phone != null" >
            phone = #{phone,jdbcType=VARCHAR},
          </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
      </update>
    
    </mapper>

    6.UserPO.java

    package com.user.pojo;
    
    public class UserPO {
        private Integer id;
        private String name; // 用户名
        private String password; // 密码
        private Integer age; // 年龄
        private String phone; // 电话号码
    
        public UserPO() {
            super();
        }
    
        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 == null ? null : name.trim();
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password == null ? null : password.trim();
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public String getPhone() {
            return phone;
        }
    
        public void setPhone(String phone) {
            this.phone = phone == null ? null : phone.trim();
        }
    
        @Override
        public String toString() {
            return "UserPO{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", password='" + password + '\'' +
                    ", age=" + age +
                    ", phone='" + phone + '\'' +
                    '}';
        }
    }

    7.UserDao.java

    package com.user.dao;
    
    import com.user.pojo.UserPO;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    @Repository
    public interface UserDao {
    
        /**
         * 得到所有的用户信息
         * @return List<UserPO>
         */
        List<UserPO> getAll();
    
        /**
         * 根据id删除某个用户信息
         * @param id
         * @return
         */
        int deleteByPrimaryKey(Integer id);
    
        /**
         * 插入一条用户信息
         * @param record
         * @return
         */
        int insertSelective(UserPO record);
    
        /**
         * 根据id查找某个用户信息
         * @param id
         * @return UserPO
         */
        UserPO selectByPrimaryKey(Integer id);
    
        /**
         * 根据id更新一条用户信息
         * @param record
         * @return
         */
        int updateByPrimaryKeySelective(UserPO record);
    }

    8.UserService.java

    package com.user.service;
    
    import com.user.dao.UserDao;
    import com.user.pojo.UserPO;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * @Author: yf
     * @Date: 2017/11/27.
     */
    @Service
    public class UserService {
    
        @Autowired
        private UserDao userDao;
    
        public List<UserPO> getUsers() {
            List<UserPO> users = userDao.getAll();
            return users;
        }
    
        public int addUser(UserPO user) {
            return userDao.insertSelective(user);
        }
    
        public int deleteUser(Integer id) {
            return userDao.deleteByPrimaryKey(id);
        }
    
        public int updateUser(UserPO user) {
            return userDao.updateByPrimaryKeySelective(user);
        }
    
        public UserPO getUser(Integer id) {
            return userDao.selectByPrimaryKey(id);
        }
    }

    9.UserController.java

    package com.user.controller;
    
    import com.user.pojo.UserPO;
    import com.user.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    /**
     * @Author: yf
     * @Date: 2017/11/27.
     */
    @RestController
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @GetMapping("/getUsers")
        public List<UserPO> getUsers() {
            return userService.getUsers();
        }
    
        @PostMapping("/add")
        public int add(@ModelAttribute UserPO user) {
            return userService.addUser(user);
        }
    
        @GetMapping("/delete/{id}")
        public int delete(@PathVariable("id") Integer id) {
            return userService.deleteUser(id);
        }
    
        @PostMapping("/update")
        public int update(@ModelAttribute UserPO user) {
            return userService.updateUser(user);
        }
    
        @GetMapping("/get/{id}")
        public UserPO getOne(@PathVariable("id") Integer id) {
            return  userService.getUser(id);
        }
    }

    10.ServletInitializer.java

    package com.user;
    
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.boot.web.support.SpringBootServletInitializer;
    
    /**
     * @Author: yf
     * @Date: 2017/11/27.
     */
    public class ServletInitializer extends SpringBootServletInitializer {
    
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            return builder.sources(UserCrudApplication.class);
        }
    }

    11.UserCrudApplication.java

    package com.user;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan("com.user.dao")
    public class UserCrudApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(UserCrudApplication.class, args);
        }
    }

    12.数据库
    建表语句:

    CREATE TABLE `user` (
      `id` int(8) NOT NULL AUTO_INCREMENT COMMENT '主键',
      `name` varchar(32) NOT NULL COMMENT '用户名',
      `password` varchar(255) NOT NULL COMMENT '密码',
      `age` int(8) NOT NULL COMMENT '年龄',
      `phone` varchar(32) NOT NULL COMMENT '电话号码',
      PRIMARY KEY (`id`),
      UNIQUE KEY `user_name_uindex` (`name`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4

    这里写图片描述

    展开全文
  • springboot增删改查Demo

    2018-07-23 10:22:33
    spring boot + jpa + bootstrap + thymeleaf 简单的增删改查Demo,对springboot和bootstrap初学者来说是一个不错Demo github代码下载地址:https://github.com/wjup/springBoot_Jpa

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 5,735
精华内容 2,294
关键字:

springboot增删改查

spring 订阅