2015-01-06 47 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 –