29.3.1. 实体类

通常,JPA实体类被定义到一个persistence.xml文件,在Spring Boot中,这个文件被’实体扫描’取代。默认情况,Spring Boot会查找主配置类(被@EnableAutoConfiguration@SpringBootApplication注解的类)下的所有包。

任何被@Entity@Embeddable@MappedSuperclass注解的类都将被考虑,一个普通的实体类看起来像这样:

  1. package com.example.myapp.domain;
  2. import java.io.Serializable;
  3. import javax.persistence.*;
  4. @Entity
  5. public class City implements Serializable {
  6. @Id
  7. @GeneratedValue
  8. private Long id;
  9. @Column(nullable = false)
  10. private String name;
  11. @Column(nullable = false)
  12. private String state;
  13. // ... additional members, often include @OneToMany mappings
  14. protected City() {
  15. // no-args constructor required by JPA spec
  16. // this one is protected since it shouldn't be used directly
  17. }
  18. public City(String name, String state) {
  19. this.name = name;
  20. this.country = country;
  21. }
  22. public String getName() {
  23. return this.name;
  24. }
  25. public String getState() {
  26. return this.state;
  27. }
  28. // ... etc
  29. }

你可以使用@EntityScan注解自定义实体扫描路径,具体参考@Entity definitions from Spring configuration.md"">Section 74.4, “Separate @Entity definitions from Spring configuration”。