简体   繁体   中英

spring boot String converter to Object fails

I am building an app where I need to display list of categories to select from drop-down menu. What I do is:

 @ModelAttribute("categories")
public List<Category> getAllCategories(){
    return categoryRepository.findAll();
}

I have entities: Product, Category - they are ManyToOne (products->category). When I select any of the drop-down options I get :

 Failed to convert property value of type java.lang.String to required type com.slodkacysia.bakeryshop.entity.Category for property category; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.ManyToOne com.slodkacysia.bakeryshop.entity.Category] for value 2; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Provided id of the wrong type for class com.slodkacysia.bakeryshop.entity.Category. Expected: class java.lang.Long, got class java.lang.Integer; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class com.slodkacysia.bakeryshop.entity.Category. Expected: class java.lang.Long, got class java.lang.Integer

I have tried with the following converter:

@Configuration
public class WebAppConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

    }
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(CategoryConverter());
    }
    @Bean
    public Converter CategoryConverter(){
        return new CategoryConverter();
    }
}


import com.slodkacysia.bakeryshop.entity.Category;
import com.slodkacysia.bakeryshop.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.List;
@Component
public class CategoryConverter implements Converter<String, List<Category>> {

    @Autowired
    private CategoryRepository categoryRepository;



    @Override
    public List<Category> convert(String s) {
        List<Category> result = new ArrayList<>();
        result.add(categoryRepository.findById(Long.parseLong(s)));
        return result;
    }

}

entities:

package com.slodkacysia.bakeryshop.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    private String name;
    private String description;

    private String image_url;

    private BigDecimal price;

    public List<CartItem> getCartItems() {
        return cartItems;
    }

    public void setCartItems(List<CartItem> cartItems) {
        this.cartItems = cartItems;
    }
    @ManyToOne
    private Category category;

    @OneToMany(mappedBy = "product")
    private List<CartItem> cartItems;

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    private Integer available_quantity;




    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getImage_url() {
        return image_url;
    }

    public void setImage_url(String image_url) {
        this.image_url = image_url;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public Integer getAvailable_quantity() {
        return available_quantity;
    }

    public void setAvailable_quantity(Integer available_quantity) {
        this.available_quantity = available_quantity;
    }
}



package com.slodkacysia.bakeryshop.entity;

import javax.persistence.*;

@Entity
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
    public String getFullNameCategory() {
        return name;
    }

    @Override
    public String toString() {
        return "Category{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

and view:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
    <title>Product administration</title>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<a>
    <%@include file="/WEB-INF/header.jsp" %></a><br>
<%--@elvariable id="product" type="pl.coderslab.entity.Product"--%>
<form:form modelAttribute="product" >
    Nazwa <form:input path="name"/>
    <form:errors path="name" cssClass="error" /><br>

    Opis <form:input path="description" />
    <form:errors path="description" cssClass="error" /><br>

    Image URL <form:input path="image_url" />
    <form:errors path="image_url" cssClass="error" /><br>

    <br/>

    Price <form:input path="price"/>
    <form:errors path="price" cssClass="error" /><br>

    <br>
    Available Quantity <form:input path="available_quantity"/>
    <form:errors path="available_quantity" cssClass="error" /><br>

    <br>
    <form:select path="category" items="${categories}" itemLabel="fullNameCategory" itemValue="id"/>
    <form:errors path="category" cssClass="error" /><br>

    <br>
    <input type="submit">
</form:form>
</body>
</html>

Question: what do I need to get rid of these errors? thank you

I managed to resolve the issue in an ugly way. By adding property to category object it allowed to push the contnent of the form to the controller.




The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM