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.corporate
或customerType.private
,但应为Corporate
或Private
。
答案 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}
。如果你想要不同的格式,你需要一些自定义逻辑。