2015-01-06 66 views
0

标题说明了一切。现在我的代码将关键值添加到数据库中,我认为问题出在我的模型类或servlet类中。我还想Map<String, String>值保存到String customerType使用jpa将地图值添加到数据库中

型号:

@Id 
@SequenceGenerator(name = "my_seq", sequenceName = "seq1", allocationSize = 1) 
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq") 
public long id; 
private String firstName; 
private String customerType; 

@ElementCollection 
@Column(name="customerType") 
public Map<String, String> customerTypes; 

我把值代入地图,使用servlet类,它看起来像这样:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 


    showForm(request, response); 

} 
private void showForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{ 
    Map<String, String> map = new LinkedHashMap<String, String>(); 

     map.put("",""); 
     map.put("customerType.private", "Private"); 
     map.put("customerType.corporate", "Corporate"); 

    Customer customer = new Customer(); 

    customer.setCustomerTypes(map); 
    request.setAttribute("customer", customer); 

    request.getRequestDispatcher("/Add.jsp").forward(request, response);  
} 

NB!我将地图值发送到Add.jsp页面中的选择标记(简单用户添加表单),从数据保存到数据库的位置。当数据得到保存时,customerType的格式为customerType.corporatecustomerType.private,但应该是CorporatePrivate

回答

1

我认为你是以错误的方式使用@ElementCollection。如果这样工作,当您从数据库中读取实体时,如何填充映射键? customerTypes应该放在一个单独的表格中,看看this thread以解决类似的问题。事情是这样的

@ElementCollection 
@MapKeyColumn(name="customer_type_key") 
@Column(name="customer_type_value") 
@CollectionTable(name="customer_types", [email protected](name="customer_id")) 
Map<String, String> attributes = new HashMap<String, String>(); 

UPDATE

关于你的评论,你想有一个领域,你会把值在某些格式的地图。在这种情况下,根本不需要customerTypes,但如果您需要某些东西,则可以将其保留为@Transient字段。

@Transient 
Map<String, String> attributes = new HashMap<String, String>(); 

对于大多数简单的实现,你可以使用Map#toString()作为价值customerType场。

Servlet的:在这之后

... 
    Map<String, String> map = new LinkedHashMap<String, String>(); 

    map.put("customerType.private", "Private"); 
    map.put("customerType.corporate", "Corporate"); 

    Customer customer = new Customer(); 
    customer.setCustomerType(map.toString()); 
... 

customerType的价值将是{customerType.private=Private, customerType.corporate=Corporate}。如果您需要不同的格式,您将需要一些自定义逻辑。

+0

基本上,你建议我摆脱字符串customerType,并保存地图<字符串,字符串>,而不是?所以我不必为地图创建另一张桌子。 –

+0

我不确定你想要完成什么。你想拥有一组客户类型,还是只有一个客户类型?或者你想有一个'customerType'字段,在其中放置地图,格式类似于'customerType.corporate:Corporate,customerType.private:Private'? –

+0

您可以放置​​地图的字段,格式类似于customerType.corporate:Corporate,customerType.private:Private –