我已将Spring Batch作业设置为以CSV格式读取。
在阅读器中,它使用FlatFileReader创建表示每行的ProductCSV对象。
在编写器中,它然后将每一行转换为一个实际的Object对象,使用扩展的ItemWriter将hibernate映射到数据库中。
很有效我唯一的问题是ENUM类型的字段。我得到的错误是:
字段'category'上的对象'target'中的字段错误:被拒绝的值[Some Category];代码[typeMismatch.target.category,typeMismatch.category,typeMismatch.com.project.enums.ProductCategory,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:codes [target.category,category];参数[];默认消息[类别]];默认消息[无法将类型'java.lang.String'的属性值转换为属性'category'的必需类型'com.project.enums.ProductCategory';嵌套异常是java.lang.IllegalStateException:无法将类型[java.lang.String]的值转换为属性“category”的必需类型[com.project.ProductCategory]:找不到匹配的编辑器或转换策略]
这是ENUM的样子:
package com.project.enums;
public enum ProductCategory
{
SomeCategory( "Some Category" ),
AnotherCategory( "Another Category" );
final String display;
private ProductCategory( String display )
{
this.display = display;
}
@Override
public String toString()
{
return display;
}
}
以下是ProductCSV对象的样子:
package com.project.LoadSavingInfo;
import com.project.enums.ProductCategory;
public class ProductCSV
{
private ProductCategory category;
public ProductCategory getCategory()
{
return this.category;
}
public void setCategory( ProductCategory category )
{
this.category = category;
}
}
以下是实际对象的样子:
package com.project;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import com.project.enums.ProductCategory;
@Entity
@Table( name = "product" )
public class Product
{
@Column( nullable = false )
@Enumerated(EnumType.STRING)
private ProductCategory category;
public ProductCategory getCategory()
{
return category;
}
public void setCategory( ProductCategory category )
{
this.category = category;
}
}
因此,当它从CSV中读取类似“某些类别”的内容时,如何将其转换为ENUM类型?非常感谢任何帮助或建议,如果您需要更多信息,请询问。
答案 0 :(得分:0)
问题是标准的Spring text-> enum转换是使用enum的名称(SomeCategory
,AnotherCategory
)而不是他的displayName
完成的。
我的建议是将enum的显示名称转换为ItemProcessor
中的ProductCategory对象:
class MyItemProcessor<ProductCSV,Product> {
public Product process(ProductCSV item) {
Product p = new Product();
p.setCategory(ProductCategory.fromDisplayName(item.getCategory());
}
}
作为副作用,您必须声明
public class ProductCSV {
private String category;
public String getCategory() {
return this.category;
}
public void setCategory( String category ) {
this.category = category;
}
}
你手上有完整的过程(这是我的首选方式,更清洁)。
另一个解决方案是使用您当前的类并编写自定义枚举属性编辑器/转换,如Spring custom converter for all Enums中所述。