java - 使用 Thymeleaf 发布具有多对一关系的数据

标签 java spring-boot thymeleaf

我有一个简单的模型类 Product,它展示了与 ProductCategory 的多对一关系:

产品类别:

@Entity
@Table(name="product")
public class Product {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;

@Column(name="name")
private String name;

@Column(name="description")
private String description;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="category_id")
private ProductCategory category;

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 getPdfUrl() {
    return pdfUrl;
}

public void setPdfUrl(String pdfUrl) {
    this.pdfUrl = pdfUrl;
}

public ProductCategory getCategory() {
    return category;
}

public void setCategoryId(ProductCategory category) {
    this.category = category;
}

}

ProductCategory 类

@Entity
@Table(name="product_category",uniqueConstraints={@UniqueConstraint(columnNames="name")})
public class ProductCategory {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;

@Column(name="name")
private String name;

@OneToMany(fetch=FetchType.LAZY, mappedBy="category")
private Set<Product> products = new HashSet<Product>(0);

// getters() & setters()

}

我将 Spring boot 与 Thymeleaf 结合使用,为通常的 CRUD 操作创建必要的表单。

这是我的 html 页面的基本部分,我用它来将新的 Product 对象添加到数据库中。

<form action="#" th:action="/product/save" th:object="${newProduct}" method="POST">
  <input type="text" th:field="*{name}" />
  <input type="text" th:field="*{description}" />
  <select th:field="*{category}">
    <option th:each="category: ${productCategories}" th:value="${category}" th:text="${category.name}" />
  </select>
  <button type="submit">Submit</button>
</form>

问题是,当我尝试从 Controller 插入生成的 Product 对象时(我知道我没有在这里显示它,主要是因为我不认为这实际上是问题),有一个

MySQLIntegrityConstraintViolationException: Column 'category_id' cannot be null

我已经尝试将 optionvalue 更改为 ${category.id},但即使那样也无法解决问题。

简而言之

我如何使用 Thymeleaf 将复杂对象作为 POST 参数实际传递到 Controller 中?

更新

与我最初的想法相反,这实际上可能与我的 Controller 有关,所以这是我的 ProductController:

@RequestMapping(value="/product/save", method=RequestMethod.POST)
public String saveProduct(@Valid @ModelAttribute("newProduct") Product product, ModelMap model) {
    productRepo.save(product);
    model.addAttribute("productCategories", productCategoryRepo.findAll());
    return "admin-home";
}

@RequestMapping(value="/product/save")
public String addProduct(ModelMap model) {
    model.addAttribute("newProduct", new Product());
    model.addAttribute("productCategories", productCategoryRepo.findAll());
    return "add-product";
}

最佳答案

请注意,我已将表单方法更改为 POST。

从 thymeleafs 的角度来看,我可以保证下面的代码应该有效。

<form method="POST" th:action="@{/product/save}" th:object="${newProduct}">
    ....
    <select th:field="*{category}" class="form-control">
       <option th:each="category: ${productCategories}" th:value="${category.id}" th:text="${category.name}"></option>
    </select>

前提是你的 Controller 看起来像这样。

@RequestMapping(value = "/product/save")
public String create(Model model) {
    model.addAttribute("productCategories", productCategoryService.findAll());
    model.addAttribute("newproduct", new Product()); //or try to fetch an existing object
    return '<your view path>';
}

@RequestMapping(value = "/product/save", method = RequestMethod.POST)
public String create(Model model, @Valid @ModelAttribute("newProduct") Product newProduct, BindingResult result) {
    if(result.hasErrors()){
        //error handling  
        ....
    }else {
        //or calling the repository to save the newProduct
        productService.save(newProduct);
        ....
    }
}

更新

您的模型应该具有正确名称的正确 getter 和 setter。例如,对于属性 category 你应该有,

public ProductCategory getCategory(){
    return category;
}

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

注意 - 我没有编译这段代码,我从我当前的工作项目中提取了它并将名称替换为你的类名

关于java - 使用 Thymeleaf 发布具有多对一关系的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29646133/

相关文章:

java - 应用关闭时的Android调用功能

java - 数据库对象POJO中的文件(Springboot)

Spring 启动 : thymeleaf is not rendering fragments correctly

spring-mvc - 新的Spring MVC 4中的样式表

spring-boot+thymeleaf crud :edit a row

javascript - Css 样式根据值文本更改

java - 为什么我在现有源上使用 Spring-boot 和 thymeleaf 时会收到错误 404?

java - 反向数组错误

java - 尝试在 Android 中打开 Excel 文件时不断收到 FileNotFound 异常

java - 当我尝试在 Android 应用程序上切换 Activity 时,我出现白屏