spring-data-jpa @Enumerated(EnumType.STRING)生成int列而不是varchar

cgh8pdjw  于 2022-11-10  发布在  Spring
关注(0)|答案(3)|浏览(147)

我正在使用springjpa和hib以及msSqlserver。我有一个带有enum属性的实体,带有@Enumerated(EnumType.STRING)注解。当生成数据库模式时,用enum值填充的列具有int类型而不是char类型。
用于设置数据库属性的Bean方法:

private Properties getHibernateProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.dialect","org.hibernate.dialect.SQLServer2012Dialect");

    properties.setProperty("hibernate.hbm2ddl.auto","create-drop");       
    properties.setProperty("ejb.naming_strategy","layer.controller.configuration.PhysicalNamingStrategyImpl");
    properties.setProperty("hibernate.search.default.directory_provider","filesystem");

    return properties;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setShowSql(Boolean.TRUE);        
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setDataSource(dataSource());
    factory.setPackagesToScan("layer.domain","layer.application.security.authentication.entities");
    factory.setJpaProperties(getHibernateProperties());
    factory.afterPropertiesSet();

    return factory;
}

枚举和实体:

public enum Elenco {
    A,
    B,
    C,
    D;
}

@Entity
@Table(name="elenco")
public class ElencoClass extends BaseEntity<Long> {

    @Column(name="nomeECognome")
    private String nome;

    @Enumerated(EnumType.STRING)
    @Column(columnDefinition = "varchar")
    private Elenco ele;

    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Override
    protected Long getId() {
        return id;
    }

    @Override
    protected void setId(Long id) {

        super.id=id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Elenco getEle() {
        return ele;
    }

    public void setEle(Elenco ele) {
        this.ele = ele;
    }
}

这是由spring生成的表:

CREATE TABLE [dbo].[elenco](
    [id] [bigint] IDENTITY(1,1) NOT NULL,
    [ele] [int] NULL,
    [nome] [varchar](255) NULL,
f5emj3cl

f5emj3cl1#

如果你能在getter方法上写上@Enumerated(EnumType.STRING),那就可以了。

mwg9r5ms

mwg9r5ms2#

您尝试过这个方法吗?您仍然需要在get方法中使用@Column注解来指定列名而不是列定义。

@Enumerated(EnumType.STRING)
@Column(name="ele")
public Elenco getEle() {...}
hrirmatl

hrirmatl3#

使用此选项:

@Column(name = "ele", nullable = false, columnDefinition = "enum('ELE1', 'ELE2')")

相关问题