• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

question-closed Przesyłanie formularza Spring MVC z polem powiązanym z inną encją

Object Storage Arubacloud
0 głosów
460 wizyt
pytanie zadane 7 marca 2019 w Java przez mibdbz Gaduła (4,300 p.)
zamknięte 8 marca 2019 przez mibdbz

Dzień dobry.

Mam problem z przesłaniem formularza Spring MVC do bazy danych poprzez Hibernate. Pole productType w mojej encji "Product" jest kluczem obcym z encji "ProductType". Podczas przesyłania formularza wyskakuje mi błąd HTTP Status 400 - Bad Request. Jest to spowodane tym, że pole to nie jest typem prostym. Nie mam pomysłu jak w pliku jsp dodać to pole formularza, aby przesyłać cały formularz jednym przyciskiem submit.

Controller(chodzi o metodę saveProduct):


package pl.mibdbz.diabetes.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import pl.mibdbz.diabetes.entity.Product;
import pl.mibdbz.diabetes.entity.ProductType;
import pl.mibdbz.diabetes.service.ProductService;

@Controller
@RequestMapping("/product")
public class ProductController {
    
    @Autowired
    private ProductService productService;
    
    @GetMapping("/list")
    public String listProducts(Model theModel) {
        
        List<Product> theProducts = productService.getProducts();
        
        theModel.addAttribute("products", theProducts);
        
        System.out.println(theProducts);
        
        return "list-products";
    }
    
    
    @RequestMapping("/showFormForAdd")
    public String showFormForAdd(Model theModel) {
        
        Product theProduct = new Product();
        
        theModel.addAttribute("product", theProduct);
        
        return "product-form";
    }
    
    @PostMapping("/saveProduct")
    public String saveProduct(@ModelAttribute("product") Product theProduct) {

        productService.saveProduct(theProduct);
        
        return "redirect:/product/list";
    }
 
}

Encja Product:


package pl.mibdbz.diabetes.entity;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "product")
public class Product {
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;
    
    @Column(name="name")
    private String name;
    
    @Column(name="kcal")
    private int kcal;
    
    @Column(name="carbohydrates")
    private float carbohydrates;
    
    @Column(name="protein")
    private float protein;
    
    @Column(name="fat")
    private float fat;
    
    @OneToOne(cascade={CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="product_type_id")
    private ProductType productType;
    
    
    
    
    public Product() {
        
    }

    public Product(String name, int kcal, float carbohydrates, float protein, float fat) {
        this.name = name;
        this.kcal = kcal;
        this.carbohydrates = carbohydrates;
        this.protein = protein;
        this.fat = fat;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getKcal() {
        return kcal;
    }

    public void setKcal(int kcal) {
        this.kcal = kcal;
    }

    public float getCarbohydrates() {
        return carbohydrates;
    }

    public void setCarbohydrates(float carbohydrates) {
        this.carbohydrates = carbohydrates;
    }

    public float getProtein() {
        return protein;
    }

    public void setProtein(float protein) {
        this.protein = protein;
    }

    public float getFat() {
        return fat;
    }

    public void setFat(float fat) {
        this.fat = fat;
    }

    public ProductType getProductType() {
        return productType;
    }

    public void setProductType(ProductType productType) {
        this.productType = productType;
    }

    @Override
    public String toString() {
        return "Product{" + "id=" + id + ", name=" + name + ", kcal=" + kcal + ", carbohydrates=" + carbohydrates + ", protein=" + protein + ", fat=" + fat + ", productType=" + productType + '}';
    }
    
}

Encja PorductType:


package pl.mibdbz.diabetes.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="product_type")
public class ProductType {
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;
    
    @Column(name="name")
    private String name;
    
    @Column(name="short_name")
    private String shortName;
    
    public ProductType() {
        
    }

    public ProductType(String name, String shortName) {
        this.name = name;
        this.shortName = shortName;
    }
    

    
    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getShortName() {
        return shortName;
    }

    public void setShortName(String shortName) {
        this.shortName = shortName;
    }

    @Override
    public String toString() {
        return "ProductType{" + "id=" + id + ", name=" + name + ", shortName=" + shortName + '}';
    }
    
    
}
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
%>

<!DOCTYPE html>
<html lang="pl-PL">
    <head>
        
        <meta charset="UTF-8">
        
        <title>Dodawanie Produktu</title>
        
        <link type="text/css"
              rel="stylesheet"
              href="${pageContext.request.contextPath}/resources/css/style.css" />
        
        <link type="text/css"
              rel="stylesheet"
              href="${pageContext.request.contextPath}/resources/css/add-customer-style.css" />
        
    </head>
    
    <body>
        <div id="wrapper">
            <div id="header">
                <h2>DIABETES - Przelicznik Wymienników</h2>
            </div>
        </div>
        
        <div id="container">
            <h3>Zapisz Produkt</h3>
            
            <form:form action="saveProduct" modelAttribute="product" method="POST">
                <table>
                    <tbody>
                        <tr>
                            <td><label>Nazwa:</label></td>
                            <td><form:input path="name" /></td>
                        </tr>
                        
                        <tr>
                            <td><label>Kcal:</label></td>
                            <td><form:input path="kcal" /></td>
                        </tr>
                        
                        <tr>
                            <td><label>Węglowodany:</label></td>
                            <td><form:input path="carbohydrates" /></td>
                        </tr>
                        
                        <tr>
                            <td><label>Białka:</label></td>
                            <td><form:input path="protein" /></td>
                        </tr>
                        
                        <tr>
                            <td><label>Tłuszcze:</label></td>
                            <td><form:input path="fat" /></td>
                        </tr>
                        
                        <tr>
                            <td><label>Typ Produktu:</label></td>
                            <td><form:input path="productType" /></td>
                        </tr>
                        
                        <tr>
                            <td><label></label></td>
                            <td><input type="submit" value="Zapisz" class="save" /></td>
                        </tr>
                        
                    </tbody>
                </table>
                
            </form:form>
            
            <div style="clear: both;"></div>
            
            <p>
                <a href="${pageContext.request.contextPath}/product/list">Powrót do Listy</a>
            </p>
            
        </div>
    </body>
</html>

Link do githuba: link

komentarz zamknięcia: Dostałem odpowiedź

1 odpowiedź

0 głosów
odpowiedź 7 marca 2019 przez mbabane Szeryf (79,280 p.)
wybrane 8 marca 2019 przez mibdbz
 
Najlepsza

Nie pamiętam dokładnie ale w formularzu robi się coś na zasadzie:

<td><form:input path="product.productType.name" /></td>

 

komentarz 8 marca 2019 przez mibdbz Gaduła (4,300 p.)
Twoja pamięć na pewno nie zawodzi. Działa! Wystarczyło samo productType.name. Bardzo dziękuję za pomoc. Zamykam

Podobne pytania

0 głosów
1 odpowiedź 395 wizyt
0 głosów
2 odpowiedzi 521 wizyt
0 głosów
0 odpowiedzi 162 wizyt

92,575 zapytań

141,424 odpowiedzi

319,649 komentarzy

61,960 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj.

Akademia Sekuraka

Kolejna edycja największej imprezy hakerskiej w Polsce, czyli Mega Sekurak Hacking Party odbędzie się już 20 maja 2024r. Z tej okazji mamy dla Was kod: pasjamshp - jeżeli wpiszecie go w koszyku, to wówczas otrzymacie 40% zniżki na bilet w wersji standard!

Więcej informacji na temat imprezy znajdziecie tutaj. Dziękujemy ekipie Sekuraka za taką fajną zniżkę dla wszystkich Pasjonatów!

Akademia Sekuraka

Niedawno wystartował dodruk tej świetnej, rozchwytywanej książki (około 940 stron). Mamy dla Was kod: pasja (wpiszcie go w koszyku), dzięki któremu otrzymujemy 10% zniżki - dziękujemy zaprzyjaźnionej ekipie Sekuraka za taki bonus dla Pasjonatów! Książka to pierwszy tom z serii o ITsec, który łagodnie wprowadzi w świat bezpieczeństwa IT każdą osobę - warto, polecamy!

...