JPA 如何从多对多关系中的对象数组列表中获取属性

我正在努力研究如何从充满对象的数组列表中获取属性。我想找到属于某一餐的所有菜肴,并按 dishType 过滤这些菜肴,并将它们显示在视图的表格中。


所以我写了方法 getDishNameByType 但它会返回 null。任何帮助将不胜感激!


Meal.Java


public class Meal {


    @Id

    @GeneratedValue

    private Long id;


    @ManyToMany

    private Set<Dish> dishesList = new HashSet<>();



    public String getDishNameByType(String dishType) {  

        for (Dish dish : dishesList) {

            if (dishType == dish.getDishType()) {

                return dish.getDishName();

            }

        }

        return null;    

    }

}

Dish.Java


public class Dish {


    @Id

    @GeneratedValue

    private Long id;   


    private String dishName;


    private String dishType;


    @ManyToMany(mappedBy = "dishesList")

    private Set<Meal> mealsList = new HashSet<>();

查看.html


<tr th:if="${mealPage.empty}">

    <td colspan="7" th:text="#{meals.list.table.empty}">No meals found</td>

</tr>

<tr th:each="meal : ${mealPage}">

    <td th:text="${meal.id}">1</td>

    <td th:each="dish : ${meal.dishesList}"

    th:text="${meal.getDishNameByType("Maincourse")}"></td>


</tr>


HUX布斯
浏览 80回答 1
1回答

12345678_0001

如果你有两个对象,obj1和obj2,那么obj1 == obj2当true且仅当这两个对象完全相同时。String foo = "abc";String bar = "abc";boolean same = (foo == bar); //falseboolean similar = (foo.equals(bar)); //true所以你需要打电话equals:public String getDishNameByType(String dishType) {&nbsp;&nbsp;&nbsp; &nbsp; for (Dish dish : dishesList) {&nbsp; &nbsp; &nbsp; &nbsp; if ((dishType.equals(dish.getDishType()))) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return dish.getDishName();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return null;&nbsp; &nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java