Problem with populating a dropdown list ManyToOne - Spring - 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>

Related

Cannot resolve 'name'

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?

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

404 Error in Associate Mapping

I am developing shopping cart web app which have completed up to display product to add cart. I am trying to map every customer (One To One) to cart Entity, cart entity (one to one) to cart item Entity, and cart item entity (Many to One) to Product entity. But I got a 404 error.
Please check my code below.
Mapping plan:
Customer-----one to one------>Cart----one to one---->Cart Item----Many to one--->Product
Customer Entity
package com.model;
import javax.persistence.CascadeType;
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.OneToOne;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
public class Customer {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="Cid")
private int customerId;
#Column(name="password")
#NotEmpty(message="Name is mandatory")
private String password;
#Column(name="Email")
#NotEmpty(message="Name is mandatory")
private String email;
#NotEmpty(message="First Name is mandatory")
#Column(name="firstname")
private String firstName;
#NotEmpty(message="Last Name is mandatory")
#Column(name="lastname")
private String lastName;
#Column(name="Mobile")
#NotEmpty(message="Mobile is mandatory")
private String mobile;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="address_id")
private Address delAdderss;
private boolean enabled;
private String role;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="cart_id")
private Cart cart;
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int name) {
this.customerId = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Address getDelAdderss() {
return delAdderss;
}
public void setDelAdderss(Address delAdderss) {
this.delAdderss = delAdderss;
}
}
Cart Entity
package com.model;
import javax.persistence.CascadeType;
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.OneToOne;
#Entity
public class Cart {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int cart_id;
#Column
private double total;
#Column
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="item_id")
private CartItem cartItem;
public int getCart_id() {
return cart_id;
}
public void setCart_id(int cart_id) {
this.cart_id = cart_id;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public CartItem getCartItem() {
return cartItem;
}
public void setCartItem(CartItem cartItem) {
this.cartItem = cartItem;
}
}
Cart Item Entity
package com.model;
import java.util.List;
import javax.persistence.CascadeType;
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.OneToMany;
import javax.persistence.OneToOne;
#Entity
public class CartItem {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int item_id;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id")
private List<Product> product;
public int getItem_id() {
return item_id;
}
public void setItem_id(int item_id) {
this.item_id = item_id;
}
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
}
Product Entity
package com.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;
import org.springframework.web.multipart.MultipartFile;
#Entity
public class Product {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column
private String product_Name;
#Column
private String descripction;
#Column
private int price;
#Column
private Date mfg_Date;
#Transient
private MultipartFile image;
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProduct_Name() {
return product_Name;
}
public void setProduct_Name(String product_Name) {
this.product_Name = product_Name;
}
public String getDescripction() {
return descripction;
}
public void setDescripction(String descripction) {
this.descripction = descripction;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Date getMfg_Date() {
return mfg_Date;
}
public void setMfg_Date(Date mfg_Date) {
this.mfg_Date = mfg_Date;
}
}
Why are you using cart item entity, According to me it should be Customer one on one with Cart, And a Cart as one to many with Products. I think there is no need for cart items table/entity.

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