Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSTing data with many to one relationship using Thymeleaf

I have a simple model class Product which exhibits a many to one relationship with ProductCategory:

Product class:

@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 class

@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()

}

I am using Spring boot with Thymeleaf to create the necessary forms for the usual CRUD operations.

Here is the essential portion of my html page which I use to add a new Product object into the database.

<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>

The problem is, when I try and insert the resulting Product object from the controller (I know I haven't shown it here, mostly because I don't think that is actually the cause of the problem), there is a

MySQLIntegrityConstraintViolationException: Column 'category_id' cannot be null

I have tried changing the value of the option to ${category.id}, but even that doesn't fix it.

In a nutshell

How do I actually pass a complex object as a POST parameter into a controller using Thymeleaf?

Update

Contrary to my first thoughts, this might actually be related to my Controller, so here is my 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";
}
like image 242
shyam Avatar asked Apr 15 '15 09:04

shyam


1 Answers

Note that I have changed the form method to POST.

From thymeleafs perspective I can assure the below code should work.

<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>

Provided that your controller looks like this.

@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);
        ....
    }
}

Update

Your models should have proper getters and setters with the correct names. For example, for the property category You should have,

public ProductCategory getCategory(){
    return category;
}

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

NOTE - I have not compiled this code, I got it extracted from my current working project and replace the names with your class names

like image 199
Faraj Farook Avatar answered Sep 29 '22 09:09

Faraj Farook