Spring Boot 从Mybatis检索内部字段Map〈Object,String>

mu0hgdu0  于 2023-01-20  发布在  Spring
关注(0)|答案(1)|浏览(137)

我有类CartItem

@Data
public class Cart {

    private Long id;
    private Map<Item, Long> items;

    public Cart() {
        items = new HashMap<>();
    }
}

@Data
public class Item {

    private Long id;
    private String name;
    private String description;
    private BigDecimal price;
    private ItemType type;
    private Boolean available;

}

我想从XML格式的Mybatis数据库中获取内部包含HashMap的对象。我将使用以下数据进行查询:

SELECT c.id          as cart_id,
           i.id          as item_id,
           i.name        as item_name,
           i.description as item_description,
           i.price       as item_price,
           i.type        as item_type,
           i.available   as item_available,
           ci.quantity   as item_quantity
    FROM carts c
             JOIN carts_items ci ON c.id = ci.cart_id
             LEFT JOIN items i on i.id = ci.item_id
    WHERE c.id = #{id}

所以我还没有找到任何解决这个问题的方法,我希望你能用代码示例来帮助我

gjmwrych

gjmwrych1#

我决定稍微改变一下我的结构,我添加了private List<CartItem> cartItems;,在那里我存储所有的项目字段和数量。而且我还覆盖了getItems()方法:

public Map<Item, Long> getItems() {
        return cartItems.stream()
            .collect(Collectors.toMap(CartItem::getItem, CartItem::getQuantity));
    }

因此,现在我将数据设置到CartItem对象列表中,并在需要时将它们Map到Map中

相关问题