Spring Form中的Hibernate ManyToOne关联

时间:2017-07-05 16:10:18

标签: java spring hibernate spring-mvc jpa

我有两个带有@ManyToOne关联的实体,以及一个添加产品的表单。除了类别和制造商属性外,一切正常。有什么想法吗?

以下是Product类:

@Entity
public class Product implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@NotEmpty(message = "Le champ nom ne peut être vide")
private String name;

@NotEmpty(message = "Le champ description ne peut être vide")
private String description;

@Min(value = 0, message = "Le prix du produit ne peux pas être négatif")
@NotNull(message = "Le champ prix ne peut pas être vide")
private Double price;

@ManyToOne
private Category category;

@Min(value = 0, message = "Le stock du produit ne peut pas être négatif")
@NotNull(message = "Le champ stock ne peut pas être vide")
private Long stock;

@ManyToOne
private Manufacturer manufacturer;

@Transient
private MultipartFile image;

这是Category类:

@Entity
public class Category {
@Id
private Long id;

@NotEmpty(message = "Le champ nom est vide.")
private String name;

private String description;
private String picture;

这是控制器:

@RequestMapping(value = "admin/inventaire/ajout", method = RequestMethod.POST)
public String ajoutProduitPost(@Valid @ModelAttribute("product") Product product,
        BindingResult result, HttpServletRequest request) {

    if (result.hasErrors()) {
        return "addProduct";
    }

    productDao.addProduct(product);

    MultipartFile productImage = product.getImage();
    String contextPath = context.getRealPath("/");

    Path path = Paths.get(contextPath + "/WEB-INF/resources/images/product   /"+product.getId()+".png");

    if (productImage != null && !productImage.isEmpty()) {
        try {
            productImage.transferTo(new File(path.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Product image saving failed", e);
        }
    }

    return "redirect:/admin/inventaire";
}

最后是JSP:

    <%@include file="/WEB-INF/views/template/header.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8" language="java"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<div class="container-wrapper">
    <div class ="container">

        <div class="page-header">
            <h1>Ajout d'un nouveau produit</h1>
        </div>
        <form:form action="${pageContext.request.contextPath}/admin/inventaire/ajout" method="post"
                   modelAttribute="product" enctype="multipart/form-data">
            <!-- NOM -->
            <div class="form-group" >
                <label for = "productName">Name</label>
                <form:input path="name" id="productName" class="form-control "/> <form:errors path="name" cssStyle="color:#ff0000;"/>
            </div>
            <!-- DESCRIPTION -->
            <div class = "form-group">
                <label for = "description">Description</label>
                <form:textarea path = "description" id="description" class ="form-control"/> <form:errors path="description" cssStyle="color:#ff0000;"/>
            </div>
            <!-- STOCK -->
            <div class="form-group">
                <label for="stock">Quantité en stock</label> 
                <form:input path="stock" id="stock" class="form-control"/> <form:errors path="stock" cssStyle="color:#ff0000;"/>
            </div>
            <!-- PRIX -->
            <div class="form-group">
                <label for="price">Prix</label>
                <form:input path="price" id="price" class="form-control"/> <form:errors path="price" cssStyle="color:#ff0000;"/>
            </div>
            <!-- CATEGORY -->
            <div class="form-group">
                <label for="category">Catégorie</label>
                <form:select path="category">
                    <form:option value="-" label="--Please Select"/>
                    <form:options items="${categoryList}" itemValue="id" itemLabel="name"/>
                </form:select>
            </div>
            <!-- FABRICANT -->

            <!-- IMAGE -->
            <div class="form-group">
                <label class = "control-label" for= "image">Image</label>
                <form:input id="image" path = "image" type="file" class="form:input-large"/>
            </div>

            <input type="submit" value="Envoyer" class="btn btn-default">
            <a href="<c:url value="/admin/inventaire" />" class="btn btn-default">Annuler</a>

        </form:form>
    </div>
</div>
    <%@include file="/WEB-INF/views/template/footer.jsp" %>

我认为问题在于表单将类别的id发送给控制器,但它期望对象为Category。我无法找到解决方案。

2 个答案:

答案 0 :(得分:0)

首先,你需要使用@JoinColumn来映射@ManyToOne,例如你可以使用引用代码:

@ManyToOne
@JoinColumn(name = "id")
private Category category;

然后将类别ID输入控制器并按ID查找类别。现在你有了Category Entity的对象,将Object类别设置为Product。并将cascade = CascadeType.ALL, fetch = FetchType.LAZY用于ManyToOne关系。

答案 1 :(得分:0)

<form:select path="category.id">

正如Mayank所指出的,为类别和制造商添加@JoinColumn(name="mapped_table_column_id")注释