1. 程式人生 > >springboot常用註解的使用

springboot常用註解的使用

Controller:

@Controller:處理http請求

@RestController :返回json格式的資料。相當於@[email protected]

@RequestMapping:配置URL對映

@PathVariable:獲取URL中的資料

//簡潔請求方式:127.0.0.1:8080/hello/say/111

@RestController
@RequestMapping("/hello")

public class TestController{

    @RequestMapping(value="/say/{id}",method = RequestMethod.GET)
    public String say(@PathVariable("id") Integer myId){
        return "id:" + myId ;
    }
}

@RequestParam:獲取請求引數的值

//傳統請求方式:127.0.0.1:8080/hello/say?id=111

@RestController:
@RequestMapping("/hello")

public class TestController{

    @RequestMapping(value="/say",method = RequestMethod.GET)
   // @GetMapping(value="/say")
   // public String say(@RequestParam(value="id") Integer myId){
    public String say(@RequestParam(value="id",required=false,defaultValue="0") Integer myId){   //required =false 標示非必傳引數
        return "id:" + myId ;
    }
}

@GetMapping:查詢

@PostMapping 新增

@PutMapping 更新

@DeleteMapping 刪除

Dao

//實體類可以自動生成表

spring:
    profiles:
        active: dev
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/xxx
        username: root
        password: 123456
    jpa:
        hibernate:
            ddl-auto: create    //注意這個create每次啟動都會刪除表後新建表。如果是update也會新建表,原來有相同的表裡面有資料,會保留資料建立表。create-drop表示應用停下來的時候會自動刪除表。none什麼都不做。validate 會驗證類的屬性和表的欄位是否一致,不一致會報錯
        show-sql: true

@Entity 實體類對映表

@Id

@GeneratedValue            與@Id一起加到id屬性上,id自增