我在CSV中设置了一个Spring批处理作业。
在读取器中,它创建ProductCSV对象,它使用FlatFileReader表示每一行。
在编写器中,它将每行转换为实际的对象对象,使用hibernate使用扩展的ItemWriter将其映射到数据库中。
工作很好,我唯一的问题是ENUM类型的字段。我得到的错误是:
字段“类别”上的对象‘目标’中的字段错误:拒绝值某些类别;代码typeMismatch.target.category、typeMismatch.category、typeMismatch;参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码target.category,类别;参数[];默认消息类别;默认消息[未能将'java.lang.String‘类型的属性值转换为属性’类别‘所需的'com.project.enums.ProductCategory’类型;嵌套例外是java.lang.IllegalStateException:无法将java.lang.String类型的值转换为属性“类别”所需的类型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类型?任何帮助或建议都是非常感谢的,如果你需要更多的信息,请直接问。
发布于 2013-09-20 13:00:41
问题是标准的Spring >枚举转换是使用枚举的名称(SomeCategory,AnotherCategory)完成的,而不是他的displayName。
我的建议是将枚举的显示名称转换为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中所述。
https://stackoverflow.com/questions/18916482
复制相似问题