Springboot+Mybaits+Mysql数据库增删改查操作新手上路

最近在老师的建议下,参加了一个学习小组,主要了解Spring Cloud微服务架构的应用开发,在初次搭建好环境后,这一次使用Spring boot+Mybatis完成对数据库的一些简单操作,作为新手,下面就是我整个做的过程,查阅了许多网上的资料,这里面很多都是学习别人的东西,自己说的也可能不专业,权当自己记录复习。

1.任务要求

image.png
image.png

2.工程创建

springboot工程建立就不说了,这里主要说一下pom.xml文件添加的依赖,如下:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!--pagehelper-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

还有就是application.yml文件的数据库配置:

spring:
  application:
    name: mysql-service
  datasource:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/spring-c?useUnicode=true&characterEncoding=UTF-8
      username: root
      password: hui19970201

3.应用文件创建及说明

新建一个应用,目录结构如下:


image.png

entity层

(1)根据要求在entity层创建User实体类,内容如下:

@Getter
@Setter
public class User {
    private String userId;

    private String userCode;

    @Max(value = 100, message = "年龄不能大于100岁")
    @Min(value = 18, message = "必须年满18岁!")
    private int age;

    @Pattern(regexp = "[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,4}", message = "邮件格式错误")
    private String mail;

    @Length(min = 11, max = 11, message = "手机号长度必须为11位")
    private String phone;

    private int groupId;
    private Date createTime;
    private String createBy;
    private Date modifiedTime;
    private String modifiedBy;
}

(2)根据要求在entity层创建JsonResult实体类,内容如下:

@Data
public class JsonResult {

    private Long total;
    private String message;
    private boolean status;
    private Object data;

    public JsonResult(String message, boolean status) {

        this.message = message;
        this.status = status;
    }

    public JsonResult(Long total, String message, boolean status) {
        this.total = total;
        this.message = message;
        this.status = status;
    }

    public JsonResult(String message, boolean status, Object data) {
        this.message = message;
        this.status = status;
        this.data = data;
    }

    public JsonResult(Long total, String message, boolean status, Object data) {
        this.total = total;
        this.message = message;
        this.status = status;
        this.data = data;
    }
}

(3)一些解释
首先是用来lombok的注解@Data,@Getter,@Setter减少了代码了,就不用那么多的get和set方法了,当然你也可以使用IDE的generate来生成,随自己喜好就行,如果使用的是IDEA,这里注意引入依赖之后还需要下载lombok的插件,重启就能生效了;然后就是用Validator,主要是校验用户提交的数据的合理性,这里大家可以百度一下具体的用法,下面是一些常见的注解及实际用法(复制别人的):

@null           验证对象是否为空
@notnull     验证对象是否为非空
@asserttrue       验证 boolean 对象是否为 true
@assertfalse      验证 boolean 对象是否为 false
@min           验证 number 和 string 对象是否大等于指定的值
@max           验证 number 和 string 对象是否小等于指定的值
@decimalmin    验证 number 和 string 对象是否大等于指定的值,小数存在精度
@decimalmax    验证 number 和 string 对象是否小等于指定的值,小数存在精度
@size           验证对象(array,collection,map,string)长度是否在给定的范围之内
@digits       验证 number 和 string 的构成是否合法
@past           验证 date 和 calendar 对象是否在当前时间之前
@future       验证 date 和 calendar 对象是否在当前时间之后
@pattern     验证 string 对象是否符合正则表达式的规则
@Email     验证邮箱

实际例子:
@size (min=3, max=20, message="用户名长度只能在3-20之间")
@size (min=6, max=20, message="密码长度只能在6-20之间")
@pattern (regexp="[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,4}", message="邮件格式错误")
@Length(min = 5, max = 20, message = "用户名长度必须位于5到20之间")  
@Email(message = "比如输入正确的邮箱")  
@NotNull(message = "用户名称不能为空") 
@Max(value = 100, message = "年龄不能大于100岁") 
@Min(value= 18 ,message= "必须年满18岁!" )  
@AssertTrue(message = "bln4 must is true")
@AssertFalse(message = "blnf must is falase")
@DecimalMax(value="100",message="decim最大值是100")
DecimalMin(value="100",message="decim最小值是100")
@NotNull(message = "身份证不能为空") 
@Pattern(regexp="^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message="身份证格式错误")

dao层

代码如下:

@Mapper//这里的Mapper是Mybatis自己定义的注解。
public interface UserDao {
    //插入数据
    @Insert("insert into user(userId,userCode,age,mail,phone,groupId," +
            "createTime,createBy,modifiedTime,modifiedBy)" +
            "values (#{userId,jdbcType=VARCHAR}, #{userCode,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}," +
            "#{mail,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{groupId,jdbcType=INTEGER}," +
            "#{createTime,jdbcType=TIMESTAMP}, #{createBy,jdbcType=VARCHAR}, #{modifiedTime,jdbcType=TIMESTAMP}," +
            "#{modifiedBy,jdbcType=VARCHAR})")
    void insertUser(User user);
    //更新数据
    @Update("update user set userId=#{userId,jdbcType=VARCHAR}," +
            "            userCode=#{userCode,jdbcType=VARCHAR}," +
            "            age=#{age,jdbcType=INTEGER}," +
            "            mail=#{mail,jdbcType=VARCHAR}," +
            "            phone=#{phone,jdbcType=VARCHAR}," +
            "            groupId=#{groupId,jdbcType=INTEGER}," +
            "            createTime=#{createTime,jdbcType=TIMESTAMP}," +
            "            createBy=#{createBy,jdbcType=VARCHAR}," +
            "            modifiedTime=#{modifiedTime,jdbcType=TIMESTAMP}," +
            "            modifiedBy=#{modifiedBy,jdbcType=VARCHAR} where userId=#{userId,jdbcType=VARCHAR}")
    void updateUser(User  user);

    //根据userId删除一个用户的数据
    @Delete("delete from user where useId = #{useId,jdbcType=VARCHAR}")
    void deletdUserById(String userId);
    //根据userCode删除一个用户的数据
    @Delete("delete from user where userCode = #{userCode,jdbcType=VARCHAR}")
    void deletdUserByCode(String userCode);
    //根据userCode取出一个用户的数据

    @Select("select * from user WHERE userCode = #{userCode,jdbcType=VARCHAR}")
    User getUserByCode(String userCode);
    //根据userId取出一个用户的数据
    @Select("select * from user WHERE userId = #{userId,jdbcType=VARCHAR}")
    User getUserById(String userId);
    @Select("select userCode,age,phone,modifiedTime from user ORDER BY modifiedTime DESC")
    List<User> getUserList();

}

这里使用mybatis注解的方式@Insert、@Update、@Delete、@Select来进行数据库的数据库操作,当然也可使用Mapper映射文件,我个人觉得简单的sql操作使用注解,麻烦的还是使用Mapper文件比较好。这里推荐几篇文章。
MyBatis 3(中文版) 第四章 使用注解配置SQL映射器
Mybatis中Mapper映射文件详解

service层

代码如下:

@Service
public class UserServices {
   @Autowired
   private UserDao userDao;

   public JsonResult add(User user){
       User User= userDao.getUserByCode(user.getUserCode());
       if(User!=null){
           return new JsonResult("userCode已存在",false);
       }
       user.setUserId(UUID.randomUUID().toString());
       user.setCreateTime(new Date());
       user.setModifiedTime(new Date());
       userDao.insertUser(user);
       return new JsonResult("success",true);
   }

   public JsonResult delete(String userId,String userCode){
       User User=null;
       if(userId==null&&userCode==null){
           return new JsonResult("缺少参数userId或userCode",false);
       }else if(userId==null){
           User= userDao.getUserByCode(userCode);
           if(User==null){
               return new JsonResult("userCode不存在,无法删除",false);
           }
           userDao.deletdUserByCode(userCode);
       }else {
           User= userDao.getUserById(userId);
           if(User==null){
               return new JsonResult("userId不存在,无法删除",false);
           }
           userDao.deletdUserById(userId);
       }

       return new JsonResult("success",true);
   }

   public JsonResult update(User  user){
       User User= userDao.getUserById(user.getUserId());
       if(User==null){
           return new JsonResult("没有此userId",false);
       }

       user.setModifiedTime(new Date());
       userDao.updateUser(user);
       return  new JsonResult("success",true);
   }

   public JsonResult detail(String userId, String userCode){
       User User=null;
       if(userId==null){
           User= userDao.getUserByCode(userCode);
       }else if(userCode==null){
           User= userDao.getUserById(userId);
       }
       System.out.println(User);
       return  new JsonResult("success",true,User);
   }

   public JsonResult list(int pageNum,int pageSize){
       PageHelper.startPage(pageNum, pageSize);
       List<User> list= userDao.getUserList();
       //把list包装成PageInfo对象才能序列化,该插件也默认实现了一个PageInfo
       PageInfo<User> pageInfo = new PageInfo<User>(list);
       //得到总的数据条数
       Long total=pageInfo.getTotal();
       return  new JsonResult(total,"success",true,list);
   }
}

这里主要看一下list()方法,这里采用了pagehelper插件,pageNum为页面页数,pageSize为一页数据的数量,需要把把list包装成PageInfo对象才能序列化,使用getTotal()方法得到数据的条数。pagehelper插件的的依赖引入如下,一直遇到报空错误,更新一下版本就好了。
Spring Boot+Mybatis+Pagehelper分页

controller层

代码如下:

@RestController //使用这个方法代表rest风格的控制器
public class UserController {

    @Autowired
    private UserServices userServices; //注入服务方法;

    @RequestMapping(value = "/add", method= RequestMethod.POST)
    public Object add(@Valid @RequestBody User user, BindingResult result){
        if(result.hasErrors()){
            String msg="";
            List<FieldError> fieldErrors=result.getFieldErrors();
            for (FieldError fieldError:fieldErrors){
                msg+=fieldError.getDefaultMessage()+",";
            }
            return new JsonResult(msg.substring(0,msg.length()-1),false);
        }
        return userServices.add(user);
    }

    @RequestMapping(value = "/delete",method= RequestMethod.POST)
    public Object delete(String userId,String userCode){
        return userServices.delete(userId,userCode);
    }

    @RequestMapping(value = "/update",method= RequestMethod.POST)
    public Object update(@RequestBody User  user){
        return userServices.update(user);
    }

    @RequestMapping(value = "/detail",method= RequestMethod.GET)
    public Object detail(String userId,String userCode){
        return  userServices.detail(userId,userCode);
    }

    @RequestMapping(value = "/list",method= RequestMethod.GET)
    public Object list(){
        int pageNum=1;
        int pageSize=5;
        return userServices.list(pageNum,pageSize);
    }
}

这里的@RequestBody代表参数的传入得是json格式,Validator注解@Valid说明需要检查的对象,如果有错误,错误结果都会传入BindingResult,里面就是具体的用法了。
59. Spring Boot Validator校验【从零开始学Spring Boot】

程序入口

@SpringBootApplication()
public class mysqlApplication {
    public static void main(String[] args){
        SpringApplication.run(mysqlApplication.class,args);
    }
}

4.测试

测试采用google浏览器的postman插件来发送get/post请求,部分结果如下:

add

add_failed
add_success

detail

detail_get

detail_result

list

list
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,806评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,652评论 18 139
  • Spring 技术笔记Day 1 预热知识一、 基本术语Blob类型,二进制对象Object Graph:对象图...
    OchardBird阅读 973评论 0 2
  • 现在大家都不读书,阅读都靠微博微信和知乎...过度的娱乐和社交使人麻木和空虚...甚至觉得是会扼杀一部分想象力(这...
    dd7901360167阅读 229评论 1 1
  • 【梦想成为主妇的她】她,从小的愿望是成为一个“家庭主妇”,像妈妈一样,全心全意地服务家人。以家人的乐为乐,以家庭的...
    丛阑阅读 986评论 0 0