@Enumerated(EnumType.STRING) 生成 int 列而不是 varchar



我正在使用带有休眠和ms Sqlserver的Spring jpa。我有一个带有@Enumerated(EnumType.STRING)注释的枚举属性的实体。生成数据库架构时,填充有枚举值的列具有 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,

如果你可以在getter方法上写@Enumerated(EnumType.STRING(,那将起作用。

你试过这个吗?您仍然需要@Column批注来指定 get 方法中的列名而不是列定义。

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

使用这个:

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

相关内容

  • 没有找到相关文章

最新更新