springboot2.2和mybatis2.1的增删改查

Easter79
• 阅读 479

直接结构图

springboot2.2和mybatis2.1的增删改查

数据表

CREATE TABLE `user` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`user_name` varchar(32) NOT NULL,
`pass_word` varchar(50) NOT NULL,
`real_name` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `t_userinfo` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`UserName` varchar(50) DEFAULT NULL,
`PassWord` varchar(50) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB  AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

pom.xm文件内容

<?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.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com</groupId>
    <artifactId>example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>LinMyBatis</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-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <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>

配置数据库

src/main/resources/application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=

mybatis.mapper-locations=classpath:mapping/*Mapper.xml
mybatis.type-aliases-package=com.example.entity

1.编写实体代码

       src/main/java/com/example/entity/User.java

package com.example.entity;


public class User
{
    private Integer id;
    private String userName;
    private String passWord;
    private String realName;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public String getRealName() {
        return realName;
    }
    public void setRealName(String realName) {
        this.realName = realName;
    }
    
    public String toString()
    {
        return "User:{id="+id+",userName="+userName+",passWord="+passWord+",realName="+realName+"}";
    }
}

  2.编写请求的控制器名

src/main/java/com/example/controller/UserController.java

package com.example.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.entity.User;
import com.example.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController
{
    @Autowired
    private UserService userService;
    /**
     * 查找单一记录
     * @param id
     * @return
     */
    @RequestMapping("findOne/{id}")
    public String findOne(@PathVariable int id)
    {
        return userService.findOne(id).toString();
    }
    
    @RequestMapping("getDataMultiTable/{id}")
    public List<Object> getDataMultiTable(@PathVariable int id)
    {
        return userService.getDataMultiTable(id);
    }
    
    /**
     * 查找所有
     * @return
     */
    @RequestMapping("findAll")
    public List<User> findAll()
    {
        return userService.findAll();
    }
    
    /**
     * 增加数据
     * @param args
     * @return
     */
    @RequestMapping(value="addData",method = RequestMethod.POST)
    public int addData(@RequestBody User args)
    {
        User user = new User();
        user.setUserName(args.getUserName());
        user.setPassWord(args.getPassWord());
        user.setRealName(args.getRealName());
        System.out.println(args);
        return userService.addData(user);
    }
    
    /**
     * 删除指定记录
     * @param id
     * @return
     */
    @RequestMapping("deleteUser/{id}")
    public int deleteUser(@PathVariable int id)
    {
        return userService.deleteData(id);
    }
    
    /**
     * 更新数据
     * @param args
     * @return
     */
    @RequestMapping(value="updateData",method=RequestMethod.POST)
    public int updateData(@RequestBody User args)
    {
        User user = new User();
        user.setId(args.getId());
        user.setRealName(args.getRealName());
        return userService.updateData(user);
    }
    
    
}

  3.编写请求的服务

package com.example.service;

import java.util.List;

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

import com.example.entity.User;
import com.example.mapper.UserMapper;

@Service
public class UserService
{
    @Autowired
    UserMapper userMapper;
    public User findOne(int id)
    {
        return userMapper.findOne(id);
    }
    
    public List<User> findAll()
    {
        return userMapper.findAll();
    }
    
    public int deleteData(int id)
    {
        return userMapper.deleteData(id);
    }
    
    public int addData(User user)
    {
        return userMapper.addData(user);
    }
    
    public int updateData(User user)
    {
        return userMapper.updateData(user);
    }
    
    public List<Object> getDataMultiTable(int id)
    {
        return userMapper.getDataMultiTable(id);
    }
}

  4.服务映射

src/main/java/com/example/mapper/UserMapper.java

package com.example.mapper;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.example.entity.User;

@Repository
public interface UserMapper
{
    User findOne(int id);
    
    List<User> findAll();
    
    int deleteData(int id);
    
    int addData(User user);
    
    int updateData(User user);
    
    List<Object> getDataMultiTable(int id);
}

  5.编写增删改查

src/main/resources/mapping/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.example.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="com.example.entity.User">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="user_name" jdbcType="VARCHAR" property="userName" />
        <result column="pass_word" jdbcType="VARCHAR" property="passWord" />
        <result column="real_name" jdbcType="VARCHAR" property="realName" />
    </resultMap>
    
    <select id="findOne" resultType="com.example.entity.User">
        select * from user where id = #{id}
    </select>
    
    <select id="findAll" resultType="hashmap">
    select * from user
    </select>    
    

    <select id="getDataMultiTable" resultType="hashmap">
    select u.*,tu.id as tu_id,tu.UserName as tu_username 
    from user as u join t_userinfo as tu on u.id = tu.id 
    where u.id > #{id} limit 1
    </select>
    
    <insert id="addData" keyColumn="id" useGeneratedKeys="true" keyProperty="id"  parameterType="User">
     insert into user (user_name,pass_word,real_name) values (#{userName},#{passWord},#{realName})
    </insert>
    
    <delete id="deleteData">
    delete from user where id = #{id}
    </delete>
    
    <update id="updateData" keyColumn="id" useGeneratedKeys="true" keyProperty="id"  parameterType="User">
    update user set real_name=#{realName} where id = #{id}
    </update> 
</mapper>

  请求结果如下

1.获取所有数据

springboot2.2和mybatis2.1的增删改查

删除指定数据

springboot2.2和mybatis2.1的增删改查

修改指定的数据

springboot2.2和mybatis2.1的增删改查

新增数据

springboot2.2和mybatis2.1的增删改查

参考文档与代码

https://www.w3cschool.cn/mybatis/f4uw1ilx.html

https://blog.csdn.net/iku5200/article/details/82856621

https://blog.mybatis.org/

点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
Wesley13 Wesley13
2年前
mysql的自增id 用完了怎么办?
mysql的自增id用完了怎么办?createtabletest\_auto\_increment\_id(idintUNSIGNEDauto\_incrementPRIMARYKEY,nameVARCHAR(255));执行sql语句!(https://oscimg.oschina.net/oscnet/updfcee9
Stella981 Stella981
2年前
Git使用总结
生成密钥1.打开GitBash,运行  \_sshkeygen  \_2.密钥生成空间\_~/.ssh/id\_rsa  \_(C:/User/.ssh)3.输入密码(不输入增直接回车跳过)4._~/.ssh/id\_rsa.pub_ (公钥), _id\_rsa_ (私钥)下载代码到本地
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年前
Mysql 分区表
DROPTABLEIFEXISTS\frank\_test\;CREATETABLE\frank\_test\(\id\bigint(20)NOTNULLAUTO\_INCREMENTCOMMENT'主键id',\gid\bigint(20)DEFAULT'0'COMMENT'基础表id'
Wesley13 Wesley13
2年前
oracle游标的例子
declare    cursor ca is select id_no, name from user where ym201401;begin    for cb in ca loop        update path set enamecb.name where id_nocb.id
Wesley13 Wesley13
2年前
mysql select将多个字段横向合拼到一个字段
表模式:CREATE TABLE tbl_user (  id int(11) NOT NULL AUTO_INCREMENT,  name varchar(255) DEFAULT NULL,  age int(11) DEFAULT NULL,  PRIMARY KEY (id)
Wesley13 Wesley13
2年前
Java将List中的实体按照某个字段进行分组的算法
publicvoidtest(){List<UserlistnewArrayList<();//User实体测试用Stringid,name;//当前测试以id来分组,具体请按开发场景修改list.add(newUse
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究
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k