SpringBoot从陌生到熟悉(一)

一、开发工具IAEA的简单使用和项目的创建

  1. file-->new-->Project -->Spring Initializr 如下图:


    截屏2020-07-20 下午3.51.49.png

    2.然后一路next,到下面界面,选择配置如下:
    Spring Web MyBaits Framework MySql Driver 基本可以开发web界面和连接数据库写页面


    截屏2020-07-20 下午3.55.08.png

    3.设置字体和代码自动联想
    字体:Preferences-->Editor-->Font-->Size

    联想:Preferences-->Editor-->General-->Code Completion 选中First letter only 去掉Match case
    二、application.yml的简单配置和简单的mybaits使用
    1.配置application.yml,新创建的项目是application.property,我们可以删除,在同样的位置创建application.yml文件
    配置文件的内容如下:

    #自定义属性配置
    author:
      name: eden
      age: 18
      desc: 个人立志不掉发
    #关于端口的配置
    server:
      port: 8080
      address: localhost
    #关于spring的配置
    spring:
    # 数据库连接配置
      datasource:
        name: test
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/rms?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
        username: root
        password: root
    # 设置放入静态资源可直接访问权限
      resources:
        static-locations: classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/, classpath:/templates/
      # 热部署
      devtools:
        restart:
           enabled: true  #热部署生效
           exclude: /templates/ #设置需要重启的目录
           additional-paths: src/main/java #该目录下的文件不需要重启  #  热部署配置
    #mybaits配置
    mybatis:
      mapper-locations: classpath*:mybatis/mapper/*.xml
      type-aliases-package: com.example.demo.entity
    

2.项目常见构成目录如下图:


截屏2020-07-20 下午5.35.38.png

3.controller简单使用

@Controller //说明此类是控制器
@RequestMapping(value = "/user") //第一层路径
public class UserController {
   //返回内容,用@ResponseBody注解
  @RequestMapping(value = "/content")
  @ResponseBody
  public String getUser(){
     return "2345678";
  }
 // 返回json字符串
   @RequestMapping(value = "/json",method = RequestMethod.GET)
   @ResponseBody
   public User getJson(){
      User user = new User();
      user.setName("eden");
      user.setAge("18");
      user.setDesc("个人立志不掉发");
     return user;
   }
    // 返回json字符串
   @GetMapping("/json1")
   @ResponseBody
   public User getJson1(){
      User user = new User();
      user.setName("eden");
      user.setAge("18");
      user.setDesc("个人立志不掉发");
      return user;
   }
   //重定向页面
   @GetMapping(value = "/page")
   public String page(){
       return "test";
    }
   //重定向页面传参
   @GetMapping(value = "/page1")
   public String page1(ModelMap map){
       map.addAttribute("name","孙见伟");
      return "test";
    }
}

templates/test.html获取传入的参数如下:

<!DOCTYPE html>
  //模版的链接
  <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
   <head>
     <meta charset="UTF-8">
    <title>Title</title>
  </head>
 <body>
     我是测试页面
     <h1 th:text="${name}">Hello World</h1>
  </body>
</html>

⚠️:定向页面需要导入模版依赖库,否则报错,依赖库如下:

<!--页面重定向模版-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

4.两种种方法获取配置属性
第一种:

@Value("${author.name}")
private String name;
//单个属性获取
@GetMapping(value = "/property")
@ResponseBody
public String property(){
  return this.name;
}

第二种:

@Autowired
private User user;
//一个类的属性获取
@GetMapping(value = "/author")
@ResponseBody
public String authorProperty(){
    return user.getName() + " : " + user.getAge() + " : " + user.getDesc();
}

对应实体代码如下:

@Component //表明当前类是一个java bean
@ConfigurationProperties(prefix = "author") //表示获取前缀为anthor的配置信息
public class User {
    private String name;
    private String age;
    private String desc;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getAge() { return age;}
    public void setAge(String age) { this.age = age; }
    public String getDesc() { return desc; }
    public void setDesc(String desc) { this.desc = desc; }
}

⚠️:请求返回页面不能用注解@ResponseBody
请求返回内容必须用注解@ResponseBody
5.文件上传和下载

  1. 手写dao文件
    CommentController.java

    @RestController
    @RequestMapping(value = "/comment")
    public class CommentController {
    
         @Autowired
         CommentMapper commentMapper;
         @Autowired
         HotelMapper hotelMapper;
    
         //list
         @RequestMapping(value = "/list",method = RequestMethod.GET)
         public ResultEntity getData(@RequestParam(value = "hotel_id") int hotel_id){
             ResultEntity result = new ResultEntity();
             List<CommentEntity> datas = commentMapper.selectAll(hotel_id);
             result.setCode(0);
             result.setData(datas);
             return  result;
         }
    
    
         //add
         @RequestMapping(value = "/add",method = RequestMethod.POST)
         public ResultEntity addComment(int hotel_id,int user_id,String comment,String grade) throws Exception{
              ResultEntity result = new ResultEntity();
              CommentEntity commentEntity = new CommentEntity();
              commentEntity.setHotel_id(hotel_id);
              commentEntity.setUser_id(user_id);
              commentEntity.setContent(comment);
              commentEntity.setGrade(Float.valueOf(grade));
              commentEntity.setAddtime(new Date());
              int addId = commentMapper.insert(commentEntity);
    
              //grade
              Integer avgGrade = commentMapper.avgGrade(hotel_id);
              HotelEntity hotelEntity = new HotelEntity();
              hotelEntity.setGrade(avgGrade + "");
              hotelEntity.setHotel_id(hotel_id);
              hotelMapper.updateByPrimaryKey(hotelEntity);
              result.setCode(0);
              result.setMsg("add comment success!");
              return  result;
           }
    }
    

CommentMapper.java

   public interface CommentMapper {

        int deleteByPrimaryKey(Integer id);

        int insert(CommentEntity record);

        CommentEntity selectByPrimaryKey(Integer id);

        List<CommentEntity> selectAll(Integer hotel_id);

        Integer avgGrade(Integer hotel_id);

   }
 CommentMapper.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.demo.mapper.CommentMapper">
   <resultMap id="BaseResultMap" type="com.example.demo.entity.CommentEntity">
      <id column="comment_id" jdbcType="INTEGER" property="comment_id" />
      <id column="hotel_id" jdbcType="INTEGER" property="hotel_id" />
      <id column="user_id" jdbcType="INTEGER" property="user_id" />
      <result column="content" jdbcType="VARCHAR" property="content" />
      <result column="addtime" jdbcType="TIMESTAMP" property="addtime" />
      <result column="grade" jdbcType="INTEGER" property="grade" />
      <result column="name" jdbcType="VARCHAR" property="name" />
      <result column="account" jdbcType="VARCHAR" property="account" />
      <result column="img" jdbcType="VARCHAR" property="userImg" />
   </resultMap>

    <!-- 增 -->
    <insert id="insert" parameterType="com.example.demo.entity.CommentEntity">
   
      <selectKey keyProperty="comment_id" order="AFTER" resultType="java.lang.Integer">
        SELECT LAST_INSERT_ID()
      </selectKey>
      insert into comment (hotel_id, user_id, `content`, `addtime`,
    grade)
    values (#{hotel_id,jdbcType=INTEGER}, #{user_id,jdbcType=INTEGER}, #{content,jdbcType=VARCHAR},
    #{addtime,jdbcType=TIMESTAMP},#{grade,jdbcType=INTEGER})
   </insert>

   <!-- 删 -->
   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
      delete from comment
      where comment_id = #{comment_id,jdbcType=INTEGER}
   </delete>

   <!-- 改 -->
   <update id="updateByPrimaryKey" parameterType="com.example.demo.entity.UserEntity">
     update user set
     <if test="name!= null" >
           name = #{name,jdbcType=VARCHAR},
     </if>
     <if test="img!= null" >
           img = #{img,jdbcType=VARCHAR},
     </if>
     <if test="gender!= null" >
            gender = #{gender,jdbcType=VARCHAR}
     </if>
     where account = #{account,jdbcType=VARCHAR}
   </update>
   <!-- 查 -->
   <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
      select * from comment
      where comment_id = #{comment_id,jdbcType=INTEGER}
   </select>
   <select id="selectAll" parameterType="java.lang.Integer" resultMap="BaseResultMap" useCache="true">
      select * from comment, user
      where  comment.hotel_id = #{hotel_id,jdbcType=INTEGER} and comment.user_id = user.account  order by addtime desc
   </select>

   <!-- 求平均 -->
   <select id="avgGrade" parameterType="java.lang.Integer" resultType="java.lang.Integer" useCache="true">
      select AVG(grade) AS grade from comment
      where  comment.hotel_id = #{hotel_id,jdbcType=INTEGER}
   </select>
   </mapper>

7.遇到注解的解释

   @SpringBootApplication  //表明是SpringBoot项目
   @MapperScan("com.example.demo.mapper") //与dao层的@Mapper二选
   @Value("${author.name}") //自动获取配置属性
   @Component  //表明当前类是一个java bean
   @ConfigurationProperties(prefix = "author") //表示获取前缀为anthor的配置信息
   @Controller //表明该类是控制器
   @RestController //是@Controller和@ResponseBody之和
   @Resource //自动创建一个对象
   @Autowired //自动创建一个对象
   @RequestMapping(value = "/event") //一个请求
   @RequestMapping(value = "/json",method = RequestMethod.GET) //一个get请求
   @PostMapping(value = "insert")   //一个post请求
   @GetMapping(value = "/one")    //一个get请求
   @ResponseBody  //返回数据,非页面
   @Param("name") String name //输入的参数

三、自动生成dao文件的配置和使用
自动生成dao文件
1.依赖库的引入,在pom.xml添加热部署依赖库如下:

 <!-- mysql自动生成实体类-->
<dependency>
  <groupId>org.mybatis.generator</groupId>
  <artifactId>mybatis-generator-core</artifactId>
  <version>1.3.5</version>
</dependency>

2.在resources文件夹创建mybatis-generator.xml,目录如下图


截屏2020-07-20 下午3.07.14.png

内容如下(在里面配置好自己的实体类,map.xml,数据库,表)等相关信息:

 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE generatorConfiguration   PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 <generatorConfiguration>
   <context id="DB2Tables" targetRuntime="MyBatis3Simple">
      <commentGenerator>
         <property name="suppressDate" value="true"/>
         <!-- 是否去除自动生成的注释 true:是 : false:否 -->
         <!-- 这个注释是generator的注释。不是建表时手输的,没什么卵用-->
         <property name="suppressAllComments" value="true"/>
      </commentGenerator>
     <!--数据库链接URL,用户名、密码 -->
     <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/rms?characterEncoding=utf-8"
                userId="root" password="2012715Aa">
     </jdbcConnection>
     <javaTypeResolver>
        <property name="forceBigDecimals" value="false"/>
     </javaTypeResolver>
     <!-- 设置Java类生成的位置 -->
    <javaModelGenerator targetPackage="com.example.demo.entity"
                    targetProject="./src/main/java">
        <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
         <property name="enableSubPackages" value="true"/>
          <!-- 是否对model添加 构造函数 -->
         <property name="constructorBased" value="true"/>
         <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
         <property name="trimStrings" value="true"/>
         <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
         <property name="immutable" value="false"/>
    </javaModelGenerator>
    <!-- 生成映射文件的包名和位置 ***mapper.xml-->
    <sqlMapGenerator targetPackage="/mybatis/mapper"
                 targetProject="./src/main/resources">
       <property name="enableSubPackages" value="true"/>
    </sqlMapGenerator>
    <!-- 生成DAO的包名和位置 ***mapper.java-->
    <javaClientGenerator type="XMLMAPPER"
                     targetPackage="com.example.demo.mapper"
                     targetProject="./src/main/java">
        <property name="enableSubPackages" value="true"/>      
     </javaClientGenerator>
     <!-- 所有要生成的表名 -->
     <table tableName="event"></table>
   </context>
</generatorConfiguration>

3.在test文件夹下新建java类,目录如下图


截屏2020-07-20 下午3.00.32.png

代码如下:

 package com.example.demo;
 import org.mybatis.generator.api.ShellRunner;
 public class GetAutoEntityAndDao {
   // 该配置文件放在src\\main\\resources\\该路径下即可
   public static void main(String[] args) {
      //路径一定要配置正确
     args = new String[] { "-configfile", "src//main//resources//mybatis-generator.xml", "-overwrite" };
     ShellRunner.main(args);
 }}

四、热部署的配置和使用
使用场景:修改项目下的静态文件(html,css,js,img)等需要重新运行项目才可以访问,这个时候采用热加载,可以不用重新运行项目也可以访问,达到在开发中节省时间的作用。
1.依赖库的引入,在pom.xml添加热部署依赖库如下:

  <!--热部署依赖库-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
  <optional>true</optional>
</dependency>

2.application.yml配置热加载路径代码如下:

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