springboot如何对本地数据库增删改查_Spring Boot整合Mybatis实现对数据库的增删改查...

写在开始:

今天学习了一下springboot,从网上找各种资料,视频,系统的学习了springboot入门,springboot controller,springboot过滤器,监听器,springboot JDBC连接数据库,JPA连接数据库,MyBatis连接数据库等相关知识,通过网上的资料自己动手敲了一遍,慢慢从helloworld到成功实现对数据库的增删改查,但我觉得还是mybatis用的比较多一些,springboot连接mybatis真的是纯注解式开发,个人觉得很简单方便有效。这里主要记录springboot整合mybatis实现对数据库的增删改查。

正文:

首先用maven构建springboot项目:

2.选择构建工具Maven Project、Spring Boot版本1.5.8以及一些工程基本信息,点击“Switch to the full version.”java版本选择1.8,可参考下图所示:

3.点击Generate Project下载项目压缩包,解压之后导入你得开发工具中即可。

运行截图:

4.运行成功之后,首选需要在SpringBoot的启动类里面增加用来扫描Mapper接口的注解,用来扫描Mapper包下面的接口。

5.在application.properties配置文件中添加数据库的支持.

6.pom.xml文件中添加相应的jar包,主要是添加mybatis的相关jar

7.准备工作完成之后就可以写代码了:

实体类代码如下:

package com.joy.entity;

import java.util.Date;

public class UserEntity {

private long userId;

private String userCode;

private String userName;

private String nickName;

private String userPwd;

private Date createDate;

private Date updateDate;

public long getUserId() {

return userId;

}

public void setUserId(long userId) {

this.userId = userId;

}

public String getUserCode() {

return userCode;

}

public void setUserCode(String userCode) {

this.userCode = userCode;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getNickName() {

return nickName;

}

public void setNickName(String nickName) {

this.nickName = nickName;

}

public String getUserPwd() {

return userPwd;

}

public void setUserPwd(String userPwd) {

this.userPwd = userPwd;

}

public Date getCreateDate() {

return createDate;

}

public void setCreateDate(Date createDate) {

this.createDate = createDate;

}

public Date getUpdateDate() {

return updateDate;

}

public void setUpdateDate(Date updateDate) {

this.updateDate = updateDate;

}

}

数据库sql命令:SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------

-- Table structure for user

-- ----------------------------

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (

`user_id` int(10) NOT NULL AUTO_INCREMENT,

`user_code` varchar(20) DEFAULT NULL,

`user_name` varchar(20) DEFAULT NULL,

`nick_name` varchar(20) DEFAULT NULL,

`user_pwd` varchar(20) DEFAULT NULL,

`create_date` datetime DEFAULT NULL,

`update_date` datetime DEFAULT NULL,

PRIMARY KEY (`user_id`)

) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------

-- Records of user

-- ----------------------------

INSERT INTO `user` VALUES ('1', '10001', 'user10001', 'no1', '123456', '2017-10-22 15:23:32', '2017-11-07 15:23:35');

INSERT INTO `user` VALUES ('2', '10002', 'user10002', 'no2', '123456', '2017-10-22 15:23:32', '2017-11-07 15:23:35');

接下来就是最重要的编写Mapper接口,我们这里采用通过注解来实现数据库的增删改查功能。package com.joy.dao;

import java.util.List;

import java.util.Map;

import org.apache.ibatis.annotations.*;

import com.joy.entity.UserEntity;

public interface UserMapper {

@Select("select * from user ")

@Results({

@Result(property = "userId", column = "user_id"),

@Result(property = "nickName", column = "nick_name"),

@Result(property = "userCode", column = "user_code"),

@Result(property = "userName", column = "user_name"),

@Result(property = "userPwd", column = "user_pwd"),

@Result(property = "createDate", column = "create_date"),

@Result(property = "updateDate", column = "update_date") })

public List queryList();

@Select("SELECT * FROM USER WHERE user_id = #{userId}")

@Results({

@Result(property = "userId", column = "user_id"),

@Result(property = "nickName", column = "nick_name"),

@Result(property = "userCode", column = "user_code"),

@Result(property = "userName", column = "user_name"),

@Result(property = "userPwd", column = "user_pwd"),

@Result(property = "createDate", column = "create_date"),

@Result(property = "updateDate", column = "update_date") })

UserEntity findById(long userId);

@Insert("INSERT INTO USER(nick_name, user_code) VALUES(#{nickName}, #{userCode})")

int insertParam(@Param("nickName") String nickName, @Param("userCode") String userCode);

@Insert("INSERT INTO USER(nick_name, user_code) VALUES(#{nickName,jdbcType=VARCHAR}, #{userCode,jdbcType=INTEGER})")

int insertByMap(Map map);

@Insert("insert into user(nick_name,user_code,user_name,user_pwd,create_date,update_date) values(#{nickName},#{userCode},#{userName},#{userPwd},#{createDate},#{updateDate})")

public int insertEntity(UserEntity entity);

@Update("UPDATE user SET nick_name=#{nickName} WHERE user_id=#{userId}")

int updateEntity(UserEntity user);

@Delete("DELETE FROM user WHERE user_id =#{userId}")

int delete(Long userId);

@Delete("DELETE FROM user WHERE user_id =#{userId}")

int deleteEntity(UserEntity entity);

}

service层代码:package com.joy.service;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

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

import org.springframework.stereotype.Service;

import com.joy.dao.UserMapper;

import com.joy.entity.UserEntity;

@Service

public class UserService {

@Autowired(required = false)

private UserMapper mapper;

public List queryList(){

List userList=mapper.queryList();

return userList;

}

public UserEntity findById(long userId){

System.out.println("userId:"+userId);

return mapper.findById(userId);

}

public int insertEntity() {

UserEntity entity=new UserEntity();

entity.setUserName("lisi");

entity.setUserCode("lisi"+new Date());

entity.setNickName("郭靖");

entity.setUserPwd("123");

entity.setCreateDate(new Date());

entity.setUpdateDate(new Date());

return mapper.insertEntity(entity);

}

public int insertParam() {

return mapper.insertParam("linzhiqiang","lzq");

}

public int insertByMap() {

Map map=new HashMap();

map.put("nickName","zhaotong");

map.put("userCode","zt");

return mapper.insertByMap(map);

}

public int updateEntity() {

UserEntity entity=new UserEntity();

entity.setUserId(1);

entity.setNickName("郭靖");

return mapper.updateEntity(entity);

}

public int deleteEntity() {

UserEntity entity=new UserEntity();

entity.setUserId(11);

return mapper.deleteEntity(entity);

}

}

controller层代码:package com.joy.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.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;

import com.joy.entity.UserEntity;

import com.joy.service.UserService;

@RestController

public class UserController {

@Autowired

private UserService userService;

@RequestMapping("/userlist")

public List queryList(){

PageHelper.startPage(1, 2);

return userService.queryList();

}

@RequestMapping(value="/queryUser/{userId}",method=RequestMethod.GET)

public UserEntity queryUserEntity(@PathVariable long userId){

UserEntity userEntity=userService.findById(userId);

return userEntity;

}

@RequestMapping("/insert")

public int insertEntity() {

return userService.insertEntity();

}

@RequestMapping("/insertParam")

public int insertParam() {

return userService.insertParam();

}

@RequestMapping("/insertByMap")

public int insertByMap() {

return userService.insertByMap();

}

@RequestMapping("/updateEntity")

public int updateEntity() {

return userService.updateEntity();

}

@RequestMapping("/deleteEntity")

public int deleteEntity() {

return userService.deleteEntity();

}

}

8.执行结果:

分页查询结果:

带参数查询结果:

写在最后:通过今天的学习,简单的了解了springboot的实用性,感觉真的很简洁,继续学习springboot,积累点滴。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当前课程中博客项目的实战源码是我在 GitHub上开源项目 My-Blog,目前已有 3000 多个 star:本课程是一个 Spring Boot 技术栈的实战类课程,课程共分为 3 大部分,前面两个部分为基础环境准备和相关概念介绍,第三个部分是 Spring Boot 个人博客项目功能的讲解,通过本课程的学习,不仅仅让你掌握基本的 Spring Boot 开发能力以及 Spring Boot 项目的大部分开发使用场景,同时帮你提前甄别和处理掉将要遇到的技术难点,认真学完这个课程后,你将会对 Spring Boot 有更加深入而全面的了解,同时你也会得到一个大家都在使用的博客系统源码,你可以根据自己的需求和想法进行改造,也可以直接使用它来作为自己的个人网站,这个课程一定会给你带来巨大的收获。作者寄语本课程录制于 2020 年,代码基于 Spring Boot 2.x 版本。到目前为止,Spring Boot 技术栈也有一些版本升级,比如 Spring Boot 2.7 发版、Spring Boot 3.x 版本发布正式版本。对于这些情况,笔者会在本课程实战项目的开源仓库中创建不同的代码分支,保持实战项目的源码更新,保证读者朋友们不会学习过气的知识点。课程特色 课程内容紧贴 Spring Boot 技术栈,涵盖大部分 Spring Boot 使用场景。开发教程详细完整、文档资源齐全、实验过程循序渐进简单明了。实践项目页面美观且实用,交互效果完美。包含从零搭建项目、以及完整的后台管理系统和博客展示系统两个系统的功能开发流程。技术栈新颖且知识点丰富,学习后可以提升大家对于知识的理解和掌握,对于提升你的市场竞争力有一定的帮助。实战项目预览    

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值