簡體   English   中英

如何只發送@ManyToMany休眠表中的ID?

[英]How to send only the id in the @ManyToMany hibernate table?

我正在創建一個網站,當用戶進行個人資料設置時,他們將提交他們知道的語言。 這些語言是從數據庫中名為language的表中提取的,該表具有2列id和name。 我使用復選框來顯示數據庫中可用語言的列表,例如...

<label for="languages_spoken">Select the languages you can speak in:</label>
<div id="languages_spoken" th:each="language : ${supportedLanguages}">
    <input type="checkbox" name="languagesSpoken" th:value="${language}">
    <label th:text="${language.name}"></label>
</div>

現在在服務器端,我想將所選語言存儲到用戶的配置文件表中的數據庫中。 因此,我制作了一個帶有@Entity注釋的配置文件類,該類具有一個用於語言以及getter和setter的字段,如下所示:

@Entity
public class Profile {
    ...
    @ManyToMany
    private List<Language> canSpeak;
    ...
    public List<Language> getCanSpeak() {
        return canSpeak;
    }
    public void setCanSpeak(List<Language> canSpeak) {
        this.canSpeak = canSpeak;
    }
    ...
}

現在的問題是,服務器接收的請求具有字符串格式的所有內容。 因此,在setCanSpeak(List canSpeak)方法中,它接收到String []類型的參數,因此引發了錯誤

我決定解決此問題,無需將整個對象作為th:value發送回去,因為它將僅存儲用戶選擇的語言的ID,因此我嘗試了此方法...

<label for="languages_spoken">Select the languages you can speak in:</label>
<div id="languages_spoken" th:each="language : ${supportedLanguages}">
     <input type="checkbox" name="languagesSpoken" th:value="${language.id}">
     <label th:text="${language.name}"></label>
</div>

並將配置文件實體字段從“語言列表”更改為“整數列表”,因為該語言的ID為Integer類型。

但是,當我在該字段中添加@ManyToMany批注時,它拋出了異常,因為Integer在我的項目中不是實體。

org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class:

好的,這里發生了一些事情。 您只需要保存一個整數這一事實並不意味着您需要將實體模型對象更改為List<Integer>

您仍然需要保存一個語言對象 List<Language>List<Language>

因此,我不知道您如何處理您的請求,但是我很確定您需要執行以下操作:

  1. 在servlet或控制器中獲取數據請求
  2. 調用您的持久方法並創建所有需要設置的語言對象,只需設置每個對象的ID 屬性
  3. 將所有對象放入List<Language>
  4. 將該列表設置為您的Profile entity
  5. 堅持您的個人資料實體

也許代碼示例可以為您提供更好的主意(假設這是您的持久性邏輯,RequestData是包含所有需要持久化的信息的對象):

 void persist(RequestData data) { ... // you need to persist a Profile, so set all of your info: Profile profile = new Profile(); profile.setX(...); profile.setY(...); // then you need to save languages selected by user only by ID, so: List<Integer> ids = data.getListOfIds(); // get your data List<Language> languages = new ArrayList<Language>(); // create your objects // create and set a list of languages for(Integer i : ids) { Language l = new Language(); l.setId(i); languages.add(l); } profile.setLanguages(languages); // finally persist your profile object using whatever approach you need // example: em.save(profile); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM