【问题标题】:Adding map values into database using jpa使用 jpa 将地图值添加到数据库中
【发布时间】:2015-01-06 11:51:11
【问题描述】:

标题说明了一切。现在我的代码将键值添加到数据库中,我认为问题出在我的模型类或 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 类将值放入映射中,如下所示:

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);    
}

注意!我将地图值发送到 Add.jsp 页面中的选择标签(简单的用户添加表单),数据从那里保存到数据库中。当数据被保存时,customerType 的格式为customerType.corporatecustomerType.private,但应为CorporatePrivate

【问题讨论】:

    标签: jpa dictionary


    【解决方案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}。如果您想要不同的格式,您将需要一些自定义逻辑。

    【讨论】:

    • 基本上你建议我去掉 String customerType,而是保存 Map ?所以我不必为地图创建另一个表。
    • 我不确定您要完成什么。您想要拥有一组客户类型,还是只有一个客户类型?或者你想有一个customerType 字段来放置地图,格式类似于customerType.corporate: Corporate, customerType.private: Private
    • 放置地图的字段,格式类似于 customerType.corporate: Corporate, customerType.private: Private
    猜你喜欢
    • 2017-01-22
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多