美文网首页
springboot简单demo实践(IDEA+springBo

springboot简单demo实践(IDEA+springBo

作者: 花椒胡椒小辣椒 | 来源:发表于2019-08-01 15:13 被阅读0次

    参考链接
    因为参考上面的博文发现有几个问题,解决问题之后把自己的完整步骤整理如下,在搭建项目时遇到的问题也整理出来。我用的springboot的版本是2.1,参考博文应该是1.5,版本不一样有些api就不一样了,遇到问题可以看看参考。

    springboot项目搭建(更新中)

    环境:mac系统
    所需工具:IDEA(jdk1.8)+mysql+postman
    下载地址:ideamysqlmysql workbenchpostman

    1. 创建项目
      在idea界面通过file—>new—>projects,选择Spring Initializr(是Spring 官方提供的一个用来初始化一个Spring boot 项目的工具),选择已有的jdk,next,输入Group & Artifact(Group和Artifact等的含义),dependencies选择所需的依赖包,基本的如图所示,注意图片最右侧一栏(如果建好项目了才发现少添加了包,在pom.xml配置文件中添加即可;这些包具体的作用请自行百度)。
      选择依赖包
      一路next直至finish,项目结构如图所示:
      项目结构
    1. 修改配置文件application.properties
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demoTest?characterEncoding=UTF-8&&useSSL=false&useUnicode=true
    spring.datasource.username=root
    spring.datasource.password=password
    
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.jpa.hibernate.ddl-auto=update
    
    • demoTest对应你建立的数据库,root和password分别对应你自己的用户名、密码
    • spring.datasource.driver-class-name的值要注意,要与springboot的版本相对应,1.5版本写com.mysql.jdbc.Driver,2.0以上版本写com.mysql.cj.jdbc.Driver。(参考:com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的区别
    • ddl-auto:update (介绍:ddl-auto的配置)表示该数据库中如果没有表,会自动创建,但是如果里面有数据,不会清空数据。
    到mysql workbench中新建一个数据库,命名为demoTest,表不需要创建,会通过注解自动创建。此时启动项目,会在控制台中看到启动成功。 启动成功
    1. 新建User类
      在DemoApplication的父文件夹下分别新建entity、controller、dao包,在entity包下新建user类(注意这里DemoApplication和各个包的位置是有讲究的,具体原因可以自行百度,我也不是特别清楚原理,等我搞懂再来更新这个吧。还有为了代码规范,各个包具体用来放什么功能的代码,还是需要更进一步学习(涉及到mvc模式等等))
    package com.fn.example.entity;
    
    import lombok.Data;
    import javax.persistence.*;
    import java.io.Serializable;
    
    @Entity
    @Table(name = "user")
    @Data
    public class User implements Serializable {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;
    
        private String name;
        private Integer age;
    
        public User(){
        }
    
        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;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    }
    

    各个注解的作用可百度springboot data jpa注解,详细学习(待更新)。
    数据库的表的名称和代码中@Table注解name的值对应。
    重新启动项目,可以看到在本地数据库中自动生成了数据库的表user


    数据库user表
    1. 新建UserRepository接口
      在dao包下面新建UserRepository接口
      (idea新建interface:new-Java Class-在kind下拉框选择interface)
    package com.jianshu.demo.dao;
    
    import com.jianshu.demo.entity.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UserRepository extends JpaRepository<User,Integer> {
    }
    
    1. 新建UserController类
      在controller包下新建UserController类
    package com.jianshu.demo.controller;
    
    import com.jianshu.demo.dao.UserRepository;
    import com.jianshu.demo.entity.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    import java.util.List;
    
    @RestController
    public class UserController {
    
        @Autowired
        private UserRepository userRepository;
    
         /*
         select all data
          */
        @GetMapping(value = "/all")
        public List<User> getUserList(){
            return userRepository.findAll();
        }
    
        /*
        add a user
         */
        @PostMapping(value = "/add")
        public User addUser(@RequestParam("name") String name,@RequestParam("age") Integer age){
            User user = new User();
            user.setName(name);
            user.setAge(age);
    
            return userRepository.save(user);
        }
    
        /*
        select a user based on id
         */
        @GetMapping(value = "all/{id}")
        public User getUser(@PathVariable("id") Integer id){
            return userRepository.findById(id).orElse(null);
        }
    
        /*
        delete a user based on id
         */
        @DeleteMapping(value = "del/{id}")
        public void deleteUser(@PathVariable("id") Integer id){
            userRepository.deleteById(id);
        }
    }
    
    1. 测试
      get方法可以直接用浏览器输入,这里我们都用postman来模拟网页请求。
    • 获取数据库中的所有用户信息:
      输入网址:http://localhost:8080/all,选择get请求方式,点击send。可以看到结果如图所示,因为此时数据库中还没有数据。
      getAllUser
    • 向数据库中添加数据:
      输入网址:http://localhost:8080/add,选择post方式,在Body中选择form-data,输入对应的key-value值,key列输入表的列name和age,点击send,可以看到有json格式的数据返回,也可以在数据库中看到数据已经插入。
      (因为主键id使用注解@GeneratedValue设置了自增,所以不必输入id)
    add a user
    数据库更新
    此时再查看http://localhost:8080/all,可以看到数据已返回。
    all
    • 查看id=1的用户
      输入网址:http://localhost:8080/all/1,选择get方式,点击send,结果如图所示:

      id select
    • 删除id=1的用户
      输入网址:http://localhost:8080/del/1,选择delete方式,点击send,到数据库查看,可以看到数据库已更新。

      以id delete
      ⚠️问题总结:
    • 确认在application.properties中,spring.datasource.driver-class-name的值要与springboot的版本对应,以及api操作和springboot版本的对应。否则会出现报错 Inferred type 'S' for type parameter 'S' is not within its bound;should extend ‘com.mysql.cj.jdbc.Driver’。
      如:

    return girlRepository.findOne(id);

    要改成:

    return userRepository.findById(id).orElse(null);

    • 用postman时,链接url地址注意要写正确,我把http写成了https造成了错误。
      (参考http和https的区别问题(待更新))
    • 用postman模拟请求时,发现get方法返回正确数据,post方法出现错误,查看报错信息,有一句是:Field ‘id’ doesn't have a default value,而且还在数据库中多了一个hibernate.sequence的表。当时是按照参考博文的代码来写的,如果完全按照我的上述代码写应该不会出现此问题。查询之后发现是主键的自增策略问题,需要设置@GeneratedValue(strategy = GenerationType.IDENTITY),而不能单单写@GeneratedValue(参考@GeneratedValue注解(待更新))
    • 在出现上述错误之后,我改了代码,重新启动项目发现还是报错,思考了一下,应该是spring.jpa.hibernate.ddl-auto=update的原因,使得之前的修改并没有生效,解决方法1:删除原数据库中的表,重新启动项目;解决方法2:将update改为create,重新启动项目。建议选择方法1。(参考spring.jpa.hibernate.ddl-auto问题(待更新))
      ⚠️疑问:为什么在UserController类中,向数据库中添加一条数据时要new一个user,我记得springboot的优点之一就是在于注入依赖,不需要new对象啊。请求大家帮我解答一下,百度了之后也还是没有完全理解。

    相关文章

      网友评论

          本文标题:springboot简单demo实践(IDEA+springBo

          本文链接:https://www.haomeiwen.com/subject/jjwtdctx.html