Spring/SpringBoot常用注解總結(jié)

轉(zhuǎn)自:【Guide哥】

0.前言

可以毫不夸張地說(shuō)谴麦,這篇文章介紹的 Spring/SpringBoot 常用注解基本已經(jīng)涵蓋你工作中遇到的大部分常用的場(chǎng)景夺荒。對(duì)于每一個(gè)注解我都說(shuō)了具體用法呜呐,掌握搞懂跷车,使用 SpringBoot 來(lái)開(kāi)發(fā)項(xiàng)目基本沒(méi)啥大問(wèn)題了担映!

為什么要寫(xiě)這篇文章嘱蛋?

最近看到網(wǎng)上有一篇關(guān)于 SpringBoot 常用注解的文章被轉(zhuǎn)載的比較多双饥,我看了文章內(nèi)容之后屬實(shí)覺(jué)得質(zhì)量有點(diǎn)低厚骗,并且有點(diǎn)會(huì)誤導(dǎo)沒(méi)有太多實(shí)際使用經(jīng)驗(yàn)的人(這些人又占據(jù)了大多數(shù))。所以兢哭,自己索性花了大概 兩天時(shí)間簡(jiǎn)單總結(jié)一下了。

1. @SpringBootApplication

這里先單獨(dú)拎出@SpringBootApplication 注解說(shuō)一下夫嗓,雖然我們一般不會(huì)主動(dòng)去使用它迟螺。

這個(gè)注解是 Spring Boot 項(xiàng)目的基石,創(chuàng)建 SpringBoot 項(xiàng)目之后會(huì)默認(rèn)在主類(lèi)加上舍咖。

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

我們可以把 @SpringBootApplication看作是 @Configuration矩父、@EnableAutoConfiguration@ComponentScan 注解的集合排霉。

package org.springframework.boot.autoconfigure;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
   ......
}

package org.springframework.boot;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {

}

根據(jù) SpringBoot 官網(wǎng)窍株,這三個(gè)注解的作用分別是:

  • @EnableAutoConfiguration:?jiǎn)⒂?SpringBoot 的自動(dòng)配置機(jī)制
  • @ComponentScan: 掃描被@Component (@Service,@Controller)注解的 bean,注解默認(rèn)會(huì)掃描該類(lèi)所在的包下所有的類(lèi)攻柠。
  • @Configuration:允許在 Spring 上下文中注冊(cè)額外的 bean 或?qū)肫渌渲妙?lèi)

2. Spring Bean 相關(guān)

2.1. @Autowired

自動(dòng)導(dǎo)入對(duì)象到類(lèi)中球订,被注入進(jìn)的類(lèi)同樣要被 Spring 容器管理比如:Service 類(lèi)注入到 Controller 類(lèi)中。

@Service
public class UserService {
  ......
}

@RestController
@RequestMapping("/users")
public class UserController {
   @Autowired
   private UserService userService;
   ......
}

2.2. Component,@Repository,@Service, @Controller

我們一般使用 @Autowired 注解讓 Spring 容器幫我們自動(dòng)裝配 bean瑰钮。要想把類(lèi)標(biāo)識(shí)成可用于 @Autowired 注解自動(dòng)裝配的 bean 的類(lèi),可以采用以下注解實(shí)現(xiàn):

  • @Component :通用的注解冒滩,可標(biāo)注任意類(lèi)為 Spring 組件。如果一個(gè) Bean 不知道屬于哪個(gè)層浪谴,可以使用@Component 注解標(biāo)注开睡。
  • @Repository : 對(duì)應(yīng)持久層即 Dao 層,主要用于數(shù)據(jù)庫(kù)相關(guān)操作苟耻。
  • @Service : 對(duì)應(yīng)服務(wù)層篇恒,主要涉及一些復(fù)雜的邏輯,需要用到 Dao 層凶杖。
  • @Controller : 對(duì)應(yīng) Spring MVC 控制層胁艰,主要用戶接受用戶請(qǐng)求并調(diào)用 Service 層返回?cái)?shù)據(jù)給前端頁(yè)面。

2.3. @RestController

@RestController注解是@Controller和@ResponseBody的合集,表示這是個(gè)控制器 bean,并且是將函數(shù)的返回值直 接填入 HTTP 響應(yīng)體中,是 REST 風(fēng)格的控制器智蝠。

Guide 哥:現(xiàn)在都是前后端分離蝗茁,說(shuō)實(shí)話我已經(jīng)很久沒(méi)有用過(guò)@Controller。如果你的項(xiàng)目太老了的話寻咒,就當(dāng)我沒(méi)說(shuō)哮翘。

單獨(dú)使用 @Controller 不加 @ResponseBody的話一般使用在要返回一個(gè)視圖的情況,這種情況屬于比較傳統(tǒng)的 Spring MVC 的應(yīng)用毛秘,對(duì)應(yīng)于前后端不分離的情況饭寺。@Controller +@ResponseBody 返回 JSON 或 XML 形式數(shù)據(jù)

關(guān)于@RestController@Controller的對(duì)比阻课,請(qǐng)看這篇文章:@RestController vs @Controller

2.4. @Scope

聲明 Spring Bean 的作用域艰匙,使用方法:

@Bean
@Scope("singleton")
public Person personSingleton() {
    return new Person();
}

四種常見(jiàn)的 Spring Bean 的作用域:

  • singleton : 唯一 bean 實(shí)例限煞,Spring 中的 bean 默認(rèn)都是單例的。
  • prototype : 每次請(qǐng)求都會(huì)創(chuàng)建一個(gè)新的 bean 實(shí)例员凝。
  • request : 每一次 HTTP 請(qǐng)求都會(huì)產(chǎn)生一個(gè)新的 bean署驻,該 bean 僅在當(dāng)前 HTTP request 內(nèi)有效。
  • session : 每一次 HTTP 請(qǐng)求都會(huì)產(chǎn)生一個(gè)新的 bean健霹,該 bean 僅在當(dāng)前 HTTP session 內(nèi)有效旺上。

2.5. Configuration

一般用來(lái)聲明配置類(lèi),可以使用 @Component注解替代糖埋,不過(guò)使用Configuration注解聲明配置類(lèi)更加語(yǔ)義化宣吱。

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }

}

3. 處理常見(jiàn)的 HTTP 請(qǐng)求類(lèi)型

5 種常見(jiàn)的請(qǐng)求類(lèi)型:

  • GET :請(qǐng)求從服務(wù)器獲取特定資源。舉個(gè)例子:GET /users(獲取所有學(xué)生)
  • POST :在服務(wù)器上創(chuàng)建一個(gè)新的資源瞳别。舉個(gè)例子:POST /users(創(chuàng)建學(xué)生)
  • PUT :更新服務(wù)器上的資源(客戶端提供更新后的整個(gè)資源)征候。舉個(gè)例子:PUT /users/12(更新編號(hào)為 12 的學(xué)生)
  • DELETE :從服務(wù)器刪除特定的資源。舉個(gè)例子:DELETE /users/12(刪除編號(hào)為 12 的學(xué)生)
  • PATCH :更新服務(wù)器上的資源(客戶端提供更改的屬性祟敛,可以看做作是部分更新)疤坝,使用的比較少,這里就不舉例子了馆铁。

3.1. GET 請(qǐng)求

@GetMapping("users") 等價(jià)于@RequestMapping(value="/users",method=RequestMethod.GET)

@GetMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {
 return userRepository.findAll();
}

3.2. POST 請(qǐng)求

@PostMapping("users") 等價(jià)于@RequestMapping(value="/users",method=RequestMethod.POST)

關(guān)于@RequestBody注解的使用卒煞,在下面的“前后端傳值”這塊會(huì)講到。

@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) {
 return userRespository.save(user);
}

3.3. PUT 請(qǐng)求

@PutMapping("/users/{userId}") 等價(jià)于@RequestMapping(value="/users/{userId}",method=RequestMethod.PUT)

@PutMapping("/users/{userId}")
public ResponseEntity<User> updateUser(@PathVariable(value = "userId") Long userId,
  @Valid @RequestBody UserUpdateRequest userUpdateRequest) {
  ......
}

3.4. DELETE 請(qǐng)求

@DeleteMapping("/users/{userId}")等價(jià)于@RequestMapping(value="/users/{userId}",method=RequestMethod.DELETE)

@DeleteMapping("/users/{userId}")
public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){
  ......
}

3.5. PATCH 請(qǐng)求

一般實(shí)際項(xiàng)目中叼架,我們都是 PUT 不夠用了之后才用 PATCH 請(qǐng)求去更新數(shù)據(jù)畔裕。

  @PatchMapping("/profile")
  public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) {
        studentRepository.updateDetail(studentUpdateRequest);
        return ResponseEntity.ok().build();
    }

4. 前后端傳值

掌握前后端傳值的正確姿勢(shì),是你開(kāi)始 CRUD 的第一步乖订!

4.1. @PathVariable@RequestParam

@PathVariable用于獲取路徑參數(shù)扮饶,@RequestParam用于獲取查詢參數(shù)。

舉個(gè)簡(jiǎn)單的例子:

@GetMapping("/klasses/{klassId}/teachers")
public List<Teacher> getKlassRelatedTeachers(
         @PathVariable("klassId") Long klassId,
         @RequestParam(value = "type", required = false) String type ) {
...
}

如果我們請(qǐng)求的 url 是:/klasses/{123456}/teachers?type=web

那么我們服務(wù)獲取到的數(shù)據(jù)就是:klassId=123456,type=web乍构。

4.2. @RequestBody

用于讀取 Request 請(qǐng)求(可能是 POST,PUT,DELETE,GET 請(qǐng)求)的 body 部分并且Content-Type 為 application/json 格式的數(shù)據(jù)甜无,接收到數(shù)據(jù)之后會(huì)自動(dòng)將數(shù)據(jù)綁定到 Java 對(duì)象上去。系統(tǒng)會(huì)使用HttpMessageConverter或者自定義的HttpMessageConverter將請(qǐng)求的 body 中的 json 字符串轉(zhuǎn)換為 java 對(duì)象哥遮。

我用一個(gè)簡(jiǎn)單的例子來(lái)給演示一下基本使用岂丘!

我們有一個(gè)注冊(cè)的接口:

@PostMapping("/sign-up")
public ResponseEntity signUp(@RequestBody @Valid UserRegisterRequest userRegisterRequest) {
  userService.save(userRegisterRequest);
  return ResponseEntity.ok().build();
}

UserRegisterRequest對(duì)象:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserRegisterRequest {
    @NotBlank
    private String userName;
    @NotBlank
    private String password;
    @FullName
    @NotBlank
    private String fullName;
}

我們發(fā)送 post 請(qǐng)求到這個(gè)接口,并且 body 攜帶 JSON 數(shù)據(jù):

{"userName":"coder","fullName":"shuangkou","password":"123456"}

這樣我們的后端就可以直接把 json 格式的數(shù)據(jù)映射到我們的 UserRegisterRequest 類(lèi)上眠饮。

image

?? 需要注意的是:一個(gè)請(qǐng)求方法只可以有一個(gè)@RequestBody奥帘,但是可以有多個(gè)@RequestParam@PathVariable。 如果你的方法必須要用兩個(gè) @RequestBody來(lái)接受數(shù)據(jù)的話仪召,大概率是你的數(shù)據(jù)庫(kù)設(shè)計(jì)或者系統(tǒng)設(shè)計(jì)出問(wèn)題了寨蹋!

5. 讀取配置信息

很多時(shí)候我們需要將一些常用的配置信息比如阿里云 oss松蒜、發(fā)送短信、微信認(rèn)證的相關(guān)配置信息等等放到配置文件中已旧。

下面我們來(lái)看一下 Spring 為我們提供了哪些方式幫助我們從配置文件中讀取這些配置信息秸苗。

我們的數(shù)據(jù)源application.yml內(nèi)容如下::

wuhan2020: 2020年初武漢爆發(fā)了新型冠狀病毒,疫情嚴(yán)重运褪,但是惊楼,我相信一切都會(huì)過(guò)去!武漢加油秸讹!中國(guó)加油檀咙!

my-profile:
  name: Guide哥
  email: koushuangbwcx@163.com

library:
  location: 湖北武漢加油中國(guó)加油
  books:
    - name: 天才基本法
      description: 二十二歲的林朝夕在父親確診阿爾茨海默病這天,得知自己暗戀多年的校園男神裴之即將出國(guó)深造的消息——對(duì)方考取的學(xué)校嗦枢,恰是父親當(dāng)年為她放棄的那所。
    - name: 時(shí)間的秩序
      description: 為什么我們記得過(guò)去屯断,而非未來(lái)文虏?時(shí)間“流逝”意味著什么?是我們存在于時(shí)間之內(nèi)殖演,還是時(shí)間存在于我們之中氧秘?卡洛·羅韋利用詩(shī)意的文字,邀請(qǐng)我們思考這一亙古難題——時(shí)間的本質(zhì)趴久。
    - name: 了不起的我
      description: 如何養(yǎng)成一個(gè)新習(xí)慣丸相?如何讓心智變得更成熟?如何擁有高質(zhì)量的關(guān)系彼棍? 如何走出人生的艱難時(shí)刻灭忠?

5.1. @value(常用)

使用 @Value("${property}") 讀取比較簡(jiǎn)單的配置信息:

@Value("${wuhan2020}")
String wuhan2020;

5.2. @ConfigurationProperties(常用)

通過(guò)@ConfigurationProperties讀取配置信息并與 bean 綁定。

@Component
@ConfigurationProperties(prefix = "library")
class LibraryProperties {
    @NotEmpty
    private String location;
    private List<Book> books;

    @Setter
    @Getter
    @ToString
    static class Book {
        String name;
        String description;
    }
  省略getter/setter
  ......
}

你可以像使用普通的 Spring bean 一樣座硕,將其注入到類(lèi)中使用弛作。

5.3. PropertySource(不常用)

@PropertySource讀取指定 properties 文件

@Component
@PropertySource("classpath:website.properties")

class WebSite {
    @Value("${url}")
    private String url;

  省略getter/setter
  ......
}

更多內(nèi)容請(qǐng)查看我的這篇文章:《10 分鐘搞定 SpringBoot 如何優(yōu)雅讀取配置文件?》 华匾。

6. 參數(shù)校驗(yàn)

數(shù)據(jù)的校驗(yàn)的重要性就不用說(shuō)了映琳,即使在前端對(duì)數(shù)據(jù)進(jìn)行校驗(yàn)的情況下,我們還是要對(duì)傳入后端的數(shù)據(jù)再進(jìn)行一遍校驗(yàn)蜘拉,避免用戶繞過(guò)瀏覽器直接通過(guò)一些 HTTP 工具直接向后端請(qǐng)求一些違法數(shù)據(jù)萨西。

JSR(Java Specification Requests) 是一套 JavaBean 參數(shù)校驗(yàn)的標(biāo)準(zhǔn),它定義了很多常用的校驗(yàn)注解旭旭,我們可以直接將這些注解加在我們 JavaBean 的屬性上面谎脯,這樣就可以在需要校驗(yàn)的時(shí)候進(jìn)行校驗(yàn)了,非常方便持寄!

校驗(yàn)的時(shí)候我們實(shí)際用的是 Hibernate Validator 框架穿肄。Hibernate Validator 是 Hibernate 團(tuán)隊(duì)最初的數(shù)據(jù)校驗(yàn)框架年局,Hibernate Validator 4.x 是 Bean Validation 1.0(JSR 303)的參考實(shí)現(xiàn),Hibernate Validator 5.x 是 Bean Validation 1.1(JSR 349)的參考實(shí)現(xiàn)咸产,目前最新版的 Hibernate Validator 6.x 是 Bean Validation 2.0(JSR 380)的參考實(shí)現(xiàn)矢否。

SpringBoot 項(xiàng)目的 spring-boot-starter-web 依賴中已經(jīng)有 hibernate-validator 包,不需要引用相關(guān)依賴脑溢。如下圖所示(通過(guò) idea 插件—Maven Helper 生成):

image

非 SpringBoot 項(xiàng)目需要自行引入相關(guān)依賴包僵朗,這里不多做講解,具體可以查看我的這篇文章:《如何在 Spring/Spring Boot 中做參數(shù)校驗(yàn)屑彻?你需要了解的都在這里验庙!》。

?? 需要注意的是: 所有的注解社牲,推薦使用 JSR 注解粪薛,即javax.validation.constraints,而不是org.hibernate.validator.constraints

6.1. 一些常用的字段驗(yàn)證的注解

  • @NotEmpty 被注釋的字符串的不能為 null 也不能為空
  • @NotBlank 被注釋的字符串非 null搏恤,并且必須包含一個(gè)非空白字符
  • @Null 被注釋的元素必須為 null
  • @NotNull 被注釋的元素必須不為 null
  • @AssertTrue 被注釋的元素必須為 true
  • @AssertFalse 被注釋的元素必須為 false
  • @Pattern(regex=,flag=)被注釋的元素必須符合指定的正則表達(dá)式
  • @Email 被注釋的元素必須是 Email 格式违寿。
  • @Min(value)被注釋的元素必須是一個(gè)數(shù)字,其值必須大于等于指定的最小值
  • @Max(value)被注釋的元素必須是一個(gè)數(shù)字熟空,其值必須小于等于指定的最大值
  • @DecimalMin(value)被注釋的元素必須是一個(gè)數(shù)字藤巢,其值必須大于等于指定的最小值
  • @DecimalMax(value) 被注釋的元素必須是一個(gè)數(shù)字,其值必須小于等于指定的最大值
  • @Size(max=, min=)被注釋的元素的大小必須在指定的范圍內(nèi)
  • @Digits (integer, fraction)被注釋的元素必須是一個(gè)數(shù)字息罗,其值必須在可接受的范圍內(nèi)
  • @Past被注釋的元素必須是一個(gè)過(guò)去的日期
  • @Future 被注釋的元素必須是一個(gè)將來(lái)的日期
  • ......

6.2. 驗(yàn)證請(qǐng)求體(RequestBody)

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {

    @NotNull(message = "classId 不能為空")
    private String classId;

    @Size(max = 33)
    @NotNull(message = "name 不能為空")
    private String name;

    @Pattern(regexp = "((^Man$|^Woman$|^UGM$))", message = "sex 值不在可選范圍")
    @NotNull(message = "sex 不能為空")
    private String sex;

    @Email(message = "email 格式不正確")
    @NotNull(message = "email 不能為空")
    private String email;

}

我們?cè)谛枰?yàn)證的參數(shù)上加上了@Valid注解掂咒,如果驗(yàn)證失敗,它將拋出MethodArgumentNotValidException迈喉。

@RestController
@RequestMapping("/api")
public class PersonController {

    @PostMapping("/person")
    public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) {
        return ResponseEntity.ok().body(person);
    }
}

6.3. 驗(yàn)證請(qǐng)求參數(shù)(Path Variables 和 Request Parameters)

一定一定不要忘記在類(lèi)上加上 Validated 注解了绍刮,這個(gè)參數(shù)可以告訴 Spring 去校驗(yàn)方法參數(shù)。

@RestController
@RequestMapping("/api")
@Validated
public class PersonController {

    @GetMapping("/person/{id}")
    public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超過(guò) id 的范圍了") Integer id) {
        return ResponseEntity.ok().body(id);
    }
}

更多關(guān)于如何在 Spring 項(xiàng)目中進(jìn)行參數(shù)校驗(yàn)的內(nèi)容挨摸,請(qǐng)看《如何在 Spring/Spring Boot 中做參數(shù)校驗(yàn)录淡?你需要了解的都在這里!》這篇文章油坝。

7. 全局處理 Controller 層異常

介紹一下我們 Spring 項(xiàng)目必備的全局處理 Controller 層異常嫉戚。

相關(guān)注解:

  1. @ControllerAdvice :注解定義全局異常處理類(lèi)
  2. @ExceptionHandler :注解聲明異常處理方法

如何使用呢娱两?拿我們?cè)诘?5 節(jié)參數(shù)校驗(yàn)這塊來(lái)舉例子身坐。如果方法參數(shù)不對(duì)的話就會(huì)拋出MethodArgumentNotValidException,我們來(lái)處理這個(gè)異常溯泣。

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * 請(qǐng)求參數(shù)異常處理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {
       ......
    }
}

更多關(guān)于 Spring Boot 異常處理的內(nèi)容瞬女,請(qǐng)看我的這兩篇文章:

  1. SpringBoot 處理異常的幾種常見(jiàn)姿勢(shì)
  2. 使用枚舉簡(jiǎn)單封裝一個(gè)優(yōu)雅的 Spring Boot 全局異常處理窍帝!

8. JPA 相關(guān)

8.1. 創(chuàng)建表

@Entity聲明一個(gè)類(lèi)對(duì)應(yīng)一個(gè)數(shù)據(jù)庫(kù)實(shí)體。

@Table 設(shè)置表明

@Entity
@Table(name = "role")
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;
    省略getter/setter......
}

8.2. 創(chuàng)建主鍵

@Id :聲明一個(gè)字段為主鍵诽偷。

使用@Id聲明之后坤学,我們還需要定義主鍵的生成策略疯坤。我們可以使用 @GeneratedValue 指定主鍵生成策略。

1.通過(guò) @GeneratedValue直接使用 JPA 內(nèi)置提供的四種主鍵生成策略來(lái)指定主鍵生成策略深浮。

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

JPA 使用枚舉定義了 4 中常見(jiàn)的主鍵生成策略压怠,如下:

Guide 哥:枚舉替代常量的一種用法

public enum GenerationType {

    /**
     * 使用一個(gè)特定的數(shù)據(jù)庫(kù)表格來(lái)保存主鍵
     * 持久化引擎通過(guò)關(guān)系數(shù)據(jù)庫(kù)的一張?zhí)囟ǖ谋砀駚?lái)生成主鍵,
     */
    TABLE,

    /**
     *在某些數(shù)據(jù)庫(kù)中,不支持主鍵自增長(zhǎng),比如Oracle、PostgreSQL其提供了一種叫做"序列(sequence)"的機(jī)制生成主鍵
     */
    SEQUENCE,

    /**
     * 主鍵自增長(zhǎng)
     */
    IDENTITY,

    /**
     *把主鍵生成策略交給持久化引擎(persistence engine),
     *持久化引擎會(huì)根據(jù)數(shù)據(jù)庫(kù)在以上三種主鍵生成 策略中選擇其中一種
     */
    AUTO
}

@GeneratedValue注解默認(rèn)使用的策略是GenerationType.AUTO

public @interface GeneratedValue {

    GenerationType strategy() default AUTO;
    String generator() default "";
}

一般使用 MySQL 數(shù)據(jù)庫(kù)的話飞苇,使用GenerationType.IDENTITY策略比較普遍一點(diǎn)(分布式系統(tǒng)的話需要另外考慮使用分布式 ID)菌瘫。

2.通過(guò) @GenericGenerator聲明一個(gè)主鍵策略,然后 @GeneratedValue使用這個(gè)策略

@Id
@GeneratedValue(generator = "IdentityIdGenerator")
@GenericGenerator(name = "IdentityIdGenerator", strategy = "identity")
private Long id;

等價(jià)于:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

jpa 提供的主鍵生成策略有如下幾種:

public class DefaultIdentifierGeneratorFactory
        implements MutableIdentifierGeneratorFactory, Serializable, ServiceRegistryAwareService {

    @SuppressWarnings("deprecation")
    public DefaultIdentifierGeneratorFactory() {
        register( "uuid2", UUIDGenerator.class );
        register( "guid", GUIDGenerator.class );            // can be done with UUIDGenerator + strategy
        register( "uuid", UUIDHexGenerator.class );         // "deprecated" for new use
        register( "uuid.hex", UUIDHexGenerator.class );     // uuid.hex is deprecated
        register( "assigned", Assigned.class );
        register( "identity", IdentityGenerator.class );
        register( "select", SelectGenerator.class );
        register( "sequence", SequenceStyleGenerator.class );
        register( "seqhilo", SequenceHiLoGenerator.class );
        register( "increment", IncrementGenerator.class );
        register( "foreign", ForeignGenerator.class );
        register( "sequence-identity", SequenceIdentityGenerator.class );
        register( "enhanced-sequence", SequenceStyleGenerator.class );
        register( "enhanced-table", TableGenerator.class );
    }

    public void register(String strategy, Class generatorClass) {
        LOG.debugf( "Registering IdentifierGenerator strategy [%s] -> [%s]", strategy, generatorClass.getName() );
        final Class previous = generatorStrategyToClassNameMap.put( strategy, generatorClass );
        if ( previous != null ) {
            LOG.debugf( "    - overriding [%s]", previous.getName() );
        }
    }

}

8.3. 設(shè)置字段類(lèi)型

@Column 聲明字段布卡。

示例:

設(shè)置屬性 userName 對(duì)應(yīng)的數(shù)據(jù)庫(kù)字段名為 user_name雨让,長(zhǎng)度為 32,非空

@Column(name = "user_name", nullable = false, length=32)
private String userName;

設(shè)置字段類(lèi)型并且加默認(rèn)值忿等,這個(gè)還是挺常用的栖忠。

Column(columnDefinition = "tinyint(1) default 1")
private Boolean enabled;

8.4. 指定不持久化特定字段

@Transient :聲明不需要與數(shù)據(jù)庫(kù)映射的字段,在保存的時(shí)候不需要保存進(jìn)數(shù)據(jù)庫(kù) 贸街。

如果我們想讓secrect 這個(gè)字段不被持久化庵寞,可以使用 @Transient關(guān)鍵字聲明。

Entity(name="USER")
public class User {

    ......
    @Transient
    private String secrect; // not persistent because of @Transient

}

除了 @Transient關(guān)鍵字聲明匾浪, 還可以采用下面幾種方法:

static String secrect; // not persistent because of static
final String secrect = “Satish”; // not persistent because of final
transient String secrect; // not persistent because of transient

一般使用注解的方式比較多皇帮。

8.5. 聲明大字段

@Lob:聲明某個(gè)字段為大字段卷哩。

@Lob
private String content;

更詳細(xì)的聲明:

@Lob
//指定 Lob 類(lèi)型數(shù)據(jù)的獲取策略蛋辈, FetchType.EAGER 表示非延遲 加載,而 FetchType. LAZY 表示延遲加載 将谊;
@Basic(fetch = FetchType.EAGER)
//columnDefinition 屬性指定數(shù)據(jù)表對(duì)應(yīng)的 Lob 字段類(lèi)型
@Column(name = "content", columnDefinition = "LONGTEXT NOT NULL")
private String content;

8.6. 創(chuàng)建枚舉類(lèi)型的字段

可以使用枚舉類(lèi)型的字段冷溶,不過(guò)枚舉字段要用@Enumerated注解修飾。

public enum Gender {
    MALE("男性"),
    FEMALE("女性");

    private String value;
    Gender(String str){
        value=str;
    }
}
@Entity
@Table(name = "role")
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;
    @Enumerated(EnumType.STRING)
    private Gender gender;
    省略getter/setter......
}

數(shù)據(jù)庫(kù)里面對(duì)應(yīng)存儲(chǔ)的是 MAIL/FEMAIL尊浓。

8.7. 增加審計(jì)功能

只要繼承了 AbstractAuditBase的類(lèi)都會(huì)默認(rèn)加上下面四個(gè)字段逞频。

@Data
@AllArgsConstructor
@NoArgsConstructor
@MappedSuperclass
@EntityListeners(value = AuditingEntityListener.class)
public abstract class AbstractAuditBase {

    @CreatedDate
    @Column(updatable = false)
    @JsonIgnore
    private Instant createdAt;

    @LastModifiedDate
    @JsonIgnore
    private Instant updatedAt;

    @CreatedBy
    @Column(updatable = false)
    @JsonIgnore
    private String createdBy;

    @LastModifiedBy
    @JsonIgnore
    private String updatedBy;
}

我們對(duì)應(yīng)的審計(jì)功能對(duì)應(yīng)地配置類(lèi)可能是下面這樣的(Spring Security 項(xiàng)目):


@Configuration
@EnableJpaAuditing
public class AuditSecurityConfiguration {
    @Bean
    AuditorAware<String> auditorAware() {
        return () -> Optional.ofNullable(SecurityContextHolder.getContext())
                .map(SecurityContext::getAuthentication)
                .filter(Authentication::isAuthenticated)
                .map(Authentication::getName);
    }
}

簡(jiǎn)單介紹一下上面設(shè)計(jì)到的一些注解:

  1. @CreatedDate: 表示該字段為創(chuàng)建時(shí)間時(shí)間字段,在這個(gè)實(shí)體被 insert 的時(shí)候栋齿,會(huì)設(shè)置值

  2. @CreatedBy :表示該字段為創(chuàng)建人苗胀,在這個(gè)實(shí)體被 insert 的時(shí)候,會(huì)設(shè)置值

    @LastModifiedDate瓦堵、@LastModifiedBy同理基协。

@EnableJpaAuditing:開(kāi)啟 JPA 審計(jì)功能。

8.8. 刪除/修改數(shù)據(jù)

@Modifying 注解提示 JPA 該操作是修改操作,注意還要配合@Transactional注解使用菇用。

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {

    @Modifying
    @Transactional(rollbackFor = Exception.class)
    void deleteByUserName(String userName);
}

8.9. 關(guān)聯(lián)關(guān)系

  • @OneToOne 聲明一對(duì)一關(guān)系
  • @OneToMany 聲明一對(duì)多關(guān)系
  • @ManyToOne聲明多對(duì)一關(guān)系
  • MangToMang聲明多對(duì)多關(guān)系

更多關(guān)于 Spring Boot JPA 的文章請(qǐng)看我的這篇文章:一文搞懂如何在 Spring Boot 正確中使用 JPA 澜驮。

9. 事務(wù) @Transactional

在要開(kāi)啟事務(wù)的方法上使用@Transactional注解即可!

@Transactional(rollbackFor = Exception.class)
public void save() {
  ......
}

我們知道 Exception 分為運(yùn)行時(shí)異常 RuntimeException 和非運(yùn)行時(shí)異常。在@Transactional注解中如果不配置rollbackFor屬性,那么事物只會(huì)在遇到RuntimeException的時(shí)候才會(huì)回滾,加上rollbackFor=Exception.class,可以讓事物在遇到非運(yùn)行時(shí)異常時(shí)也回滾惋鸥。

@Transactional 注解一般用在可以作用在類(lèi)或者方法上杂穷。

  • 作用于類(lèi):當(dāng)把@Transactional 注解放在類(lèi)上時(shí)悍缠,表示所有該類(lèi)的public 方法都配置相同的事務(wù)屬性信息。
  • 作用于方法:當(dāng)類(lèi)配置了@Transactional耐量,方法也配置了@Transactional飞蚓,方法的事務(wù)會(huì)覆蓋類(lèi)的事務(wù)配置信息。

更多關(guān)于關(guān)于 Spring 事務(wù)的內(nèi)容請(qǐng)查看:

  1. 可能是最漂亮的 Spring 事務(wù)管理詳解
  2. 一口氣說(shuō)出 6 種 @Transactional 注解失效場(chǎng)景

10. json 數(shù)據(jù)處理

10.1. 過(guò)濾 json 數(shù)據(jù)

@JsonIgnoreProperties 作用在類(lèi)上用于過(guò)濾掉特定字段不返回或者不解析拴鸵。

//生成json時(shí)將userRoles屬性過(guò)濾
@JsonIgnoreProperties({"userRoles"})
public class User {

    private String userName;
    private String fullName;
    private String password;
    @JsonIgnore
    private List<UserRole> userRoles = new ArrayList<>();
}

@JsonIgnore一般用于類(lèi)的屬性上玷坠,作用和上面的@JsonIgnoreProperties 一樣。


public class User {

    private String userName;
    private String fullName;
    private String password;
   //生成json時(shí)將userRoles屬性過(guò)濾
    @JsonIgnore
    private List<UserRole> userRoles = new ArrayList<>();
}

10.2. 格式化 json 數(shù)據(jù)

@JsonFormat一般用來(lái)格式化 json 數(shù)據(jù)劲藐。:

比如:

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT")
private Date date;

10.3. 扁平化對(duì)象

@Getter
@Setter
@ToString
public class Account {
    @JsonUnwrapped
    private Location location;
    @JsonUnwrapped
    private PersonInfo personInfo;

  @Getter
  @Setter
  @ToString
  public static class Location {
     private String provinceName;
     private String countyName;
  }
  @Getter
  @Setter
  @ToString
  public static class PersonInfo {
    private String userName;
    private String fullName;
  }
}

未扁平化之前:

{
    "location": {
        "provinceName":"湖北",
        "countyName":"武漢"
    },
    "personInfo": {
        "userName": "coder1234",
        "fullName": "shaungkou"
    }
}

使用@JsonUnwrapped 扁平對(duì)象之后:

@Getter
@Setter
@ToString
public class Account {
    @JsonUnwrapped
    private Location location;
    @JsonUnwrapped
    private PersonInfo personInfo;
    ......
}
{
  "provinceName":"湖北",
  "countyName":"武漢",
  "userName": "coder1234",
  "fullName": "shaungkou"
}

11. 測(cè)試相關(guān)

@ActiveProfiles一般作用于測(cè)試類(lèi)上八堡, 用于聲明生效的 Spring 配置文件。

@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("test")
@Slf4j
public abstract class TestBase {
  ......
}

@Test聲明一個(gè)方法為測(cè)試方法

@Transactional被聲明的測(cè)試方法的數(shù)據(jù)會(huì)回滾聘芜,避免污染測(cè)試數(shù)據(jù)兄渺。

@WithMockUser Spring Security 提供的,用來(lái)模擬一個(gè)真實(shí)用戶汰现,并且可以賦予權(quán)限挂谍。

    @Test
    @Transactional
    @WithMockUser(username = "user-id-18163138155", authorities = "ROLE_TEACHER")
    void should_import_student_success() throws Exception {
        ......
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市瞎饲,隨后出現(xiàn)的幾起案子口叙,更是在濱河造成了極大的恐慌,老刑警劉巖嗅战,帶你破解...
    沈念sama閱讀 219,366評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件妄田,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡驮捍,警方通過(guò)查閱死者的電腦和手機(jī)疟呐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)东且,“玉大人启具,你說(shuō)我怎么就攤上這事∩河荆” “怎么了鲁冯?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,689評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)色查。 經(jīng)常有香客問(wèn)我薯演,道長(zhǎng),這世上最難降的妖魔是什么综慎? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,925評(píng)論 1 295
  • 正文 為了忘掉前任涣仿,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘好港。我一直安慰自己愉镰,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布钧汹。 她就那樣靜靜地躺著丈探,像睡著了一般。 火紅的嫁衣襯著肌膚如雪拔莱。 梳的紋絲不亂的頭發(fā)上碗降,一...
    開(kāi)封第一講書(shū)人閱讀 51,727評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音塘秦,去河邊找鬼讼渊。 笑死,一個(gè)胖子當(dāng)著我的面吹牛尊剔,可吹牛的內(nèi)容都是我干的爪幻。 我是一名探鬼主播,決...
    沈念sama閱讀 40,447評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼须误,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼挨稿!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起京痢,我...
    開(kāi)封第一講書(shū)人閱讀 39,349評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤奶甘,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后祭椰,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體臭家,經(jīng)...
    沈念sama閱讀 45,820評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評(píng)論 3 337
  • 正文 我和宋清朗相戀三年吭产,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了侣监。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鸭轮。...
    茶點(diǎn)故事閱讀 40,127評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡臣淤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出窃爷,到底是詐尸還是另有隱情邑蒋,我是刑警寧澤,帶...
    沈念sama閱讀 35,812評(píng)論 5 346
  • 正文 年R本政府宣布按厘,位于F島的核電站医吊,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏逮京。R本人自食惡果不足惜卿堂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧草描,春花似錦览绿、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,017評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至逛绵,卻和暖如春怀各,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背术浪。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,142評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工瓢对, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人胰苏。 一個(gè)月前我還...
    沈念sama閱讀 48,388評(píng)論 3 373
  • 正文 我出身青樓沥曹,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親碟联。 傳聞我的和親對(duì)象是個(gè)殘疾皇子妓美,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評(píng)論 2 355