【问题标题】:JPA Entity class without "@Column" annotation没有“@Column”注释的 JPA 实体类
【发布时间】:2021-10-01 20:52:24
【问题描述】:

我有这段代码,作者在其中创建了一个 JPA 实体。不知何故,它成功地工作了,这对我来说似乎很奇怪,因为并非每个字段都用“@Column”注释。基于此,这是我的问题:

如果每个字段都没有“列”注释(“id”除外),这个类如何才能正常工作(所有数据都成功记录在数据库中)?

/**
     * @author Ram Alapure
     * @since 05-04-2017
     */
   
    @Entity
    @Table(name="User")
    public class User {
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name = "id", updatable = false, nullable = false)
        private long id;
        
    private String firstName;
    
    private String lastName;
    
    private LocalDate dob;
    
    private String gender;
    
    private String role;
    
    private String email;
    
    private String password;

    @Override
    public String toString() {
        return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + ", email="
                + email + "]";
    }

    
}

例如,这里有另一个类也可以正常工作。但是这一次,在每个字段中都有一个“@Column”注释。我认为这是 JPA 从字段创建列的先决条件。

  @Entity
@Table(name = "address")
public class Address {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "address_id")
    private long id;
    
    @Column(name = "rua")
    private String street;
    
    @Column(name = "number")
    private int number;
    
    @Column(name = "complement")
    private String complement;
    
    @Column(name = "suburb")
    private String suburb;
    
    @Column(name = "city")
    private String city;
    
    @Column(name = "state")
    private String state;
    
    @Column(name = "country")
    private String country;
    
    @Column(name = "cep")

Getter 和 Setter 被隐藏在所有代码中,因为它们看起来就像普通的 getter 和 setter,没有必要显示出来。

【问题讨论】:

    标签: spring spring-boot hibernate jpa spring-data-jpa


    【解决方案1】:

    这个注释意味着在数据库@Entity中创建表,类中的所有字段都同名

    spring boot 扫描此注解@Entity 后扫描 是用字段在IOC中注入和创建Bean

    但如果使用@Column,如果更改数据库中的列名称,则有助于与表字段进行映射

    当扫描组件并看到这个注解时,bean 会在数据库中使用列名更改为名称,因为我们需要与数据库成功映射

    【讨论】:

    • Spring 不检测实体,您的 JPA 提供程序可以。虽然 Spring Boot 也可以检测到它们,但只是将它们交给 JPA。 Spring 不使用@Entity 类。
    • 是的对不起这个错误的定义只是弹簧启动使用注释
    【解决方案2】:

    如果你没有指定@Column 注解(可选),那么 Hibernate 使用默认命名策略,使用驼峰式大小写。

    firstName 字段成为数据库中的 first_name 列。

    您还可以根据需要定义自己的命名策略。

    来自文档。

    策略; Hibernate 5 定义了物理和隐式命名策略。 Spring Boot 默认配置 SpringPhysicalNamingStrategy。此实现提供与 Hibernate 4 相同的表结构:所有点都被下划线替换,驼峰式大小写也被下划线替换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2018-05-04
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      相关资源
      最近更新 更多