使用jpa将映射值添加到数据库中

时间:2015-01-06 11:51:12

标签: jpa dictionary

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

型号:

@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类将值放入map中,如下所示:

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页面中的select标签(简单用户添加表单),从中将数据保存到数据库中。保存数据后,customerType的格式为customerType.corporatecustomerType.private,但应为CorporatePrivate

1 个答案:

答案 0 :(得分:1)

我认为你以错误的方式使用@ElementCollection。如果这样有效,当您从数据库中读取实体时,如何填充地图键? customerTypes应位于单独的表格中,请查看this thread以获得类似问题的解决方案。像这样的东西

@ElementCollection
@MapKeyColumn(name="customer_type_key")
@Column(name="customer_type_value")
@CollectionTable(name="customer_types", joinColumns=@JoinColumn(name="customer_id"))
Map<String, String> attributes = new HashMap<String, String>();

<强>更新

关于您的评论,您希望有一个字段,您可以在其中以某种格式放置地图中的值。在这种情况下,您根本不需要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}。如果你想要不同的格式,你需要一些自定义逻辑。