Cannot resolve 'name' - spring

Hi all, I'm currently doing a crud app using spring mvc, hibernate and thymeleaf. I am trying to create a new user but the compiler is complaining that it can't recognize the name field, even though I have this field in the User class. What can be the problem?
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>New User</title>
</head>
<body>
<form th:method="POST" th:action="#{/users}" th:object="${user}">
<input type="text" th:field="*{name}" id="name">
</form>
</body>
</html>
User class:
package web.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#GenericGenerator(name = "increment", strategy = "increment")
private int id;
#Column(name = "name", nullable = false, length = 50)
private String name;
public User() {}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
}
UserController:
package web.controller;
import jdk.internal.icu.text.NormalizerBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import web.model.User;
import web.service.UserService;
#Controller
#RequestMapping("/users")
public class UserController {
#Autowired
private UserService userService;
#GetMapping
public String listUsers(Model model) {
model.addAttribute("users", userService.getAllUsers());
return "users";
}
#GetMapping("/{id}")
public String show(#PathVariable("id") int id, Model model) {
model.addAttribute("user", userService.getUserById(id));
return "show";
}
#GetMapping("/new")
public String newUser(Model model) {
model.addAttribute("user", new User());
return "new";
}
#PostMapping()
public String create(#ModelAttribute("user") User user) {
userService.add(user);
return "redirect:/users";
}
}
What could be the problem?

Related

Problem with populating a dropdown list ManyToOne - Spring

I have a problem populating a drop down list with a ManyToOne relationship.
I have two entities, Product referencing Category with Category ID ...
But I can't populate the category list with the Spring form tag and get the pointer to the category in the product table of the database.
Can anyone kindly explain to me how to solve this problem?
DB Product Category Structure
JSP Form Output
PRODUCT CLASS
package it.relazioni.one;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(length = 100, nullable = false)
private String nameProduct;
#Column
private int price;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "idCategory")
private Category category;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNameProduct() {
return nameProduct;
}
public void setNameProduct(String nameProduct) {
this.nameProduct = nameProduct;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
CATEGORY CLASS
package it.relazioni.one;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(length = 45, nullable = false, unique = true)
private String nameCategory;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNameCategory() {
return nameCategory;
}
public void setNameCategory(String nameCategory) {
this.nameCategory = nameCategory;
}
public Category(Integer id, String nameCategory) {
super();
this.id = id;
this.nameCategory = nameCategory;
}
public Category(Integer id) {
super();
this.id = id;
}
public Category(String nameCategory) {
super();
this.nameCategory = nameCategory;
}
}
CONTROLLER CODE
#GetMapping("/createProd")
public ModelAndView createProduct(#ModelAttribute("newProduct") Product p, Model model) {
List<Category> categories = (List<Category>) catRep.findAll();
model.addAttribute("categories", categories);
return new ModelAndView("createProduct", "newProduct", new Product());
}
#PostMapping("/createProductForm")
public ModelAndView createProductForm(#ModelAttribute("newProduct") Product p) {
System.out.println(p.getNameProduct() + " " + p.getCategory());
pdRep.save(p);
return new ModelAndView("createProduct", "newProduct", p);
}
JSP CODE
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form action="createProductForm" method="post" modelAttribute="newProduct">
<form:input path="nameProduct"/>
<form:input path="price" type="number"/>
<form:select path="category">
<form:options items="${categories}"></form:options>
</form:select>
<form:button>Create Product!</form:button>
</form:form>
</body>
</html>

Why am I getting null for the date when I create a Todo entity?

What is wrong with my to-do application? I want the user to be able to add a todo and have it be saved in my MySQL database with the time it was created, but I don't know what I'm doing wrong.
I am new to learning Springboot and would appreciate any suggestions or advice.
Todo Entity:
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.util.Date;
#Entity(name = "Todo")
#NoArgsConstructor
#Table(name = "todos")
public class Todo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name="description")
private String description;
#Column(name="target_date")
#CreationTimestamp
private Date targetDate;
public Todo(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getTargetDate() {
return targetDate;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
#Override
public String toString() {
return "Todo{" +
"id=" + id +
", description='" + description + '\'' +
", targetDate=" + targetDate +
'}';
}
}
Adding a Todo with Spring Data JPA
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.List;
#Repository
#Component
public interface TodoRepository extends JpaRepository<Todo, Integer> {
#Modifying
#Query(value = "INSERT INTO todos (description) VALUES (:description)", nativeQuery=true)
#Transactional
void addTodo(#Param("description") String description);
}
TodoController
#RestController
#RequestMapping(value = "/api/v1/todos")
#AllArgsConstructor
public class TodoController {
#Autowired
private ITodoService todoService;
#PostMapping(value = "/add-todo")
public String addTodo(#RequestParam String description) {
Todo todo = new Todo();
todo.setDescription(description);
todoService.addTodo(todo);
return todo.toString();
}
after getting a post request, the target_date is getting NULL in MySQL
I assume you can solve it by using persist():
#Autowired EntityManager entityManager;
#PostMapping(value = "/add-todo")
public String addTodo(#RequestParam String description) {
Todo todo = new Todo();
todo.setDescription(description);
entityManager.persist(todo);
return todo.toString();
}

EL1008E: Property or field 'isAvailable' cannot be found on object of type 'com.inventory.domain.Item' - maybe not public or not valid?

I have one boolean field in item bean all other fields are populating but only isAvailable is not populating in ui using thymeleaf I am getting error as property can't not found I am not getting the root cause
Is there any specific way to read the boolean field in thymeleaf. because in .html page when i tried to read boolean value st.isAvailable its throwing error in backend property not found hence not populating value
Item Bean
package com.inventory.domain;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
#Entity
#Table(name = "item")
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int item_id;
#ManyToOne
#JoinColumn(name = "category_id")
private Category categoryId;
#Column(name = "item_name",unique = true)
private String itemName;
#Column(name = "current_stock_quantity")
private double currentStockQuantity;
public double getCurrentStockQuantity() {
return currentStockQuantity;
}
#Column(name = "unit")
#Enumerated(EnumType.STRING)
private ItemWeightUnit unit;
#Column(name = "current_purchase_price")
private double currentPurchasePrice;
#Column(name = "is_available")
private boolean isAvailable;
#Column(name = "is_active")
private boolean isActive;
#Column(name = "item_description")
#Lob
private String itemDescription;
#OneToMany(mappedBy = "item",cascade = CascadeType.ALL)
private List<Vendor> vendor = new ArrayList<Vendor>();
#OneToMany(mappedBy = "item",cascade = CascadeType.ALL)
#OrderBy("transaction_date ASC")
private SortedSet<ItemTransaction> itemTransaction=new TreeSet<ItemTransaction>();
#OneToMany(mappedBy = "item",cascade = CascadeType.ALL)
#OrderBy("date ASC")
private SortedSet<PricingHistory> priceHistory=new TreeSet<PricingHistory>();
public SortedSet<ItemTransaction> getItemTransaction() {
return itemTransaction;
}
public void setItemTransaction(SortedSet<ItemTransaction> itemTransaction) {
this.itemTransaction = itemTransaction;
}
public void setCurrentStockQuantity(double currentStockQuantity) {
this.currentStockQuantity = currentStockQuantity;
}
public List<Vendor> getVendor() {
return vendor;
}
public void setVendor(List<Vendor> vendor) {
this.vendor = vendor;
}
public int getItem_id() {
return item_id;
}
public void setItem_id(int item_id) {
this.item_id = item_id;
}
public Category getCategoryId() {
return categoryId;
}
public void setCategoryId(Category categoryId) {
this.categoryId = categoryId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public boolean isAvailable() {
return isAvailable;
}
public void setAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public ItemWeightUnit getUnit() {
return unit;
}
public void setUnit(ItemWeightUnit unit) {
this.unit = unit;
}
public double getCurrentPurchasePrice() {
return currentPurchasePrice;
}
public void setCurrentPurchasePrice(double currentPurchasePrice) {
this.currentPurchasePrice = currentPurchasePrice;
}
public SortedSet<PricingHistory> getPriceHistory() {
return priceHistory;
}
public void setPriceHistory(SortedSet<PricingHistory> priceHistory) {
this.priceHistory = priceHistory;
}
}
<tbody>
<tr th:each="st,iter : ${items}">
<td th:text="${iter.count}"></td>
<td th:text="${st.itemName}"></td>
<td th:text="${st.currentStockQuantity}"></td>
<td th:text="${st.unit}"></td>
<td th:text="${st.currentPurchasePrice}"></td>
<div th:if="${st.isAvailable} == true">
<td>Yes</td>
</div>
<div th:unless="${st.isAvailable} == false">
<td>No</td>
</div>
<td>
<a href="#" class="btn btn-default" th:href="#{/karyawan/form(id=${st.id})}"
title="Edit Data"><span class="glyphicon glyphicon-edit"></span></a>
<a href="#" class="btn btn-default" th:href="#{/karyawan/delete(id=${st.id})}"
title="Delete Data"><span class="glyphicon glyphicon-trash"></span></a>
</td>
</tr>
<tr th:if="${#lists.isEmpty(items.content)}">
<td colspan="13" class="text-center">Data Not Found</td>
</tr>
</tbody>
Getter and Setter for isAvailable method is not correct, when deserializing and serializing then you need to update them.
public boolean getIsAvailable() {
return isAvailable;
}
public void setIsAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}

I want to fetch my product details in database but it throws excepion org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not mapped

I'm keep getting an exception. I've tried to solve this problem for a few days now...
Please help me...
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not mapped [from Product]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
This is my ProductController
package com.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.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.model.Categories;
import com.model.Product;
import com.service.ProductService;
#Controller
public class ProductController {
#Autowired
private ProductService productService;
// Getters and Setters
public ProductService getProductService() {
return productService;
}
public void setProductService(ProductService productService) {
this.productService = productService;
}
// Request Mapping
#RequestMapping("/getAllProducts")
public ModelAndView getAllProducts() {
List<Product> products = productService.getAllProducts();
return new ModelAndView("productList", "products", products);
}
#RequestMapping("getProductById/{productId}")
public ModelAndView getProductById(#PathVariable(value = "productId") String productId) {
Product product = productService.getProductById(productId);
return new ModelAndView("productPage", "productObj", product);
}
#RequestMapping("/delete/{productId}")
public String deleteProduct(#PathVariable(value = "productId") String productId) {
productService.deleteProduct(productId);
return "redirect:/getAllProducts";
}
#RequestMapping(value = "/admin/product/addProduct", method = RequestMethod.GET)
public String getProductForm(Model model) {
Product product = new Product();
Categories category = new Categories();
category.setCategoryId("1");
product.setProductCategory(category);
model.addAttribute("productFormObj", product);
return "productForm";
}
#RequestMapping(value = "/admin/product/addProduct", method = RequestMethod.POST)
public String addProduct(#ModelAttribute(value = "productFormObj") Product product) {
productService.addProduct(product);
return "redirect:/getAllProducts";
}
}
This is my ProductClass
package com.model;
import java.util.Locale.Category;
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.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "product")
public class Product {
#Id
#Column
#GeneratedValue(strategy = GenerationType.AUTO)
private String productId;
#Column
private String productDescription;
#Column
private String productManufacturer;
#Column
private String productName;
#Column
private double productPrice;
#Column(name="stockunit")
private String unitStock;
#ManyToOne
#JoinColumn(name="categoryId")
private Categories productCategory;
// Getters and Setter
public String getProductId() {
return productId;
}
public Categories getProductCategory() {
return productCategory;
}
public String getProductDescription() {
return productDescription;
}
public String getProductManufacturer() {
return productManufacturer;
}
public String getProductName() {
return productName;
}
public double getProductPrice() {
return productPrice;
}
public String getUnitStock() {
return unitStock;
}
public void setProductId(String productId) {
this.productId = productId;
}
public void setProductCategory(Categories category) {
this.productCategory = category;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public void setProductManufacturer(String productManufacturer) {
this.productManufacturer = productManufacturer;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public void setUnitStock(String unitStock) {
this.unitStock = unitStock;
}
//Constructors
public Product(String productId, Categories productCategory, String productDescription, String productManufacturer,
String productName, double productPrice, String unitStock) {
super();
this.productId = productId;
this.productCategory = productCategory;
this.productDescription = productDescription;
this.productManufacturer = productManufacturer;
this.productName = productName;
this.productPrice = productPrice;
this.unitStock = unitStock;
}
public Product(){
}
}
This is my application Context
<!-- for Entity Classes annotated Classes package -->
<property name="packagesToScan">
<list>
<value>com.model.Product</value>
<value>com.model.Categories</value>
</list>
</property>
</bean>
My Category Class
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "categories")
public class Categories {
#Id
private String categoryId;
#Column
private String Categories;
#OneToMany(mappedBy = "categories")
private List<Product> product;
//And Respective Getters and Setters
ProductList page
<tbody>
<c:forEach items="${products}" var="prod">
<tr>
<td>${prod.productId}</td>
<td>${prod.productCategory}</td>
<td>${prod.productName}</td>
<td>${prod.productPrice}</td>
<td>${prod.unitStock}</td>
<td>${prod.productDescription}</td>
<td>${prod.productManufacturer}</td>
<td>
<span class="glyphicon glyphicon-info"></span>
<span class="glyphicon glyphicon-trash"></span>
</td>
</tr>
</c:forEach>
After a long analyse i have found the solution for this problem
I have modified some code in my daoImpl.
this is older code.
List<Product> products = session.createQuery("from Product").list();
I have changed this to
List<Product> products = session.createCriteria(Product.class).list();
And some changes in appication Context as #v.ladynev said :
<property name="packagesToScan">
<list>
<value>com.model</value>
</list>
</property>
You should specify a package here, not classes
<property name="packagesToScan">
<list>
<value>com.model</value>
</list>
</property>

Save a form in jsp with dropdown listfrom from database in Spring MVC

I'm trying to save Account object in the hibernate .please find the following code.
#RequestMapping(value = "/saveAccount", method = RequestMethod.POST)
public ModelAndView saveAccount(#ModelAttribute("account") Account account,
BindingResult result) {
Session session = sessionFactory.openSession();
System.out.println(account.getFirstName());
System.out.println(account.getLastName());
System.out.println(account.getSubject());
System.out.println(account.getCity().getCityName());
session.save(account);
return new ModelAndView("redirect:/form.html");
}
My jsp page have a form with First Name,Last Name ,city and subject fields.
I'm getting city dropdown fromatabase.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib
prefix="c"
uri="http://java.sun.com/jsp/jstl/core"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Contact Form</h3>
<div class="container">
<form method="post" action="/sdnext/saveAccount.html">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstName" placeholder="Your name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastName" placeholder="Your last name..">
<label for="country">City</label>
<select name="city" id="cityName" >
<c:forEach var="cityname" items="${lists}">
<option value="${cityname.cityName}">${cityname.cityName}</option>
</c:forEach>
</select>
<label for="subject">Subject</label>
<textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
DataBase bean classes are here
package test.*;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name= "Account")
public class Account implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
private String firstName;
private String LastName;
#OneToOne
private City city;
private String subject;
}
package test.*;
#Entity
#Table(name= "City")
public class City implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private String cityName;
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
}
I have used one to one mapping to city object.But i'm not able to save city object in database,rest all firstNme,LastName and subjects are getting saved.its showing in network console,but data is not getting saved in database.Please help me fix this.Thanking you..
By creating the dto we can persists the values selected from the dropdown.and its working for me .
<option value="${cityname}">${cityname.cityName}</option>
The problem is you are sending cityname.cityName (String) which cannot be mapped to City object so,
send the complete city object as the value. Hibernate will take care of mapping.

Resources