2015-11-06 305 views
0

我正在接收JSON请求的值的简单列表部分,我希望将其保存为逗号分隔值。尝试使用以下,但它没有奏效。JPA:将值列表保存为逗号分隔值

@Column(nullable = true) 
@GeneratedValue(strategy = GenerationType.AUTO) 
private ArrayList<String> services = new ArrayList<String>() ; 

@Column(nullable = true) 
@ElementCollection(targetClass = String.class) 
private List<String> services = new ArrayList<String>() ; 

@ElementCollection抛出异常说table services does not exist

+1

ElementCollection仍然存储在单独的表中收集,每行一个字符串。我不知道你在哪里读取它将元素存储为逗号分隔值。您需要一个自定义类型或转换的JPA属性。此外,使用GeneratedValue注释字符串列表没有任何意义。 –

+1

您可以尝试使用AttributeConverters作为替代方法:http://hantsy.blogspot.com/2013/12/jpa-21-attribute-converter.html – Ish

回答

2

的@ElementCollection需要一个表来存储值的倍数行,

所以,你可以定义为一个字符串列,并加入/爆炸的getter和setter方法,这样

private String services; 

public setServices(String services[]) //Can be Array or List 
{ 
    // this.services = Iterate services[] and create a comma separated string or Use ArrayUtils 
} 

public String[] getServices() //Can be Array or List 
{ 
    // services.split(",") to get a list of Strings, then typecast/parse them to Strings before returning or use Arrays.asList(arguments.split(",")); 
} 
+0

也可以将值存储到临时列表中,并将其转换为和从只有在写入/读取到数据库时才有字符串值。参见[Entity listeners](https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/listeners.html) - 这会提高性能,因为当yoe读取时转换不会总是发生/向实体写入值。或者您也可以使用[AttributeConverter](http://hantsy.blogspot.com/2013/12/jpa-21-attribute-converter.html),如@Ish所示 – OndrejM