7

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";
}

1 Answer 1

2

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

12
  • I actually left out the method="post" when I was editing the actual post. I've updated my question with the controller I have originally created. I'll try out your's , but can you suggest what is actually wrong with mine?
    – shyam
    Commented Apr 15, 2015 at 10:08
  • when you run the form page can you goto the html source view and paste the source which is rendered for the form element along with the input and select elements inside the form element. Commented Apr 15, 2015 at 11:03
  • <select class="form-control" id="category" name="category"> <option value="4">Foo</option> <option value="2">Bar</option> <option value="3">FooBar</option> <option value="1">BarFoo</option> </select>
    – shyam
    Commented Apr 16, 2015 at 3:55
  • I tried submitting data as json from the command line using curl, but with no success.
    – shyam
    Commented Apr 16, 2015 at 4:11
  • 1
    Hope you have public getters and setters for the Category Please recheck that too. The names should be getCategory and setCategory Commented Apr 21, 2015 at 9:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.