Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

1.37. Java Record 新特性

Record 替代 POJO 类

POJO类:

		
@Data
public class Point {
    private String x;
    private String y;
}		
		
		

record 实现方式

		
public record Point(String x, String y) {
}		
		
		

Record 作为 Properties

		
@ConfigurationProperties(prefix = "user")
public record UserProperties(String firstName, String lastName) {
}		
		
		

Record 作为实体类

		
package cn.netkiller.record;

import jakarta.persistence.*;

@Entity
@Table(name = "member")
public record Member(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id", unique = true, nullable = false, insertable = true, updatable = false)
        Long id,
        String name

) {
}
		
		

Record 作为 Service

		
@Service
public record PersonService(PersonRepository personRepository){

  	//保存person
    public Person save(Person person){
        Person person = new Person(person.firstName(), person.lastName(), person.age());
        return personRepository.save(person);
    }
  
 	//按照lastName查询people,返回值只有firstName和lastName
    public List<PersonOnlyWithName> findByLastName(String lastName){
        return personRepository.findByLastName(lastName);
    }
}		
		
		
		
public interface PersonRepository extends JpaRepository<Person, Long> {
    List<PersonOnlyWithName> findByLastName(String lastName);
}		
		
		

Record 作为 Controller

		
@RestController
@RequestMapping("/people")
public record PersonController(PersonService personService) {

    @PostMapping
    public ResponseEntity<Person> save(@RequestBody Person person){
        return ResponseEntity.ok(personService.save(person));
    }

    @GetMapping("/findByLastName")
    public ResponseEntity<List<PersonOnlyWithName>> findByLastName(String lastName){
        return ResponseEntity.ok(personService.findByLastName(lastName));
    }
}