Unknown column when trying to add data to a database - java

I am working on a simple CRUD project using Spring, Hibernate & JPA.
It's a basic coupon system, Coupon object has parameters, one of them is Coupon Type. When typing in the vales in the jsp which is bound to the server:
<h1> Create Coupon </h1>
<form:form action="company/create" method="POST" modelAttribute="theCoupon">
<input name="title"/>
<input name="startDate"/>
<input name="endDate"/>
<input name="amount"/>
<input name="message"/>
<input name="price"/>
<input name="image"/>
<select name="couponType">
<option>SPORTS</option>
<option>GAMING</option>
</select>
<input type="submit" value="submit">
</form:form>
this is the controller :
#PostMapping("/add")
public String newCoupon(Model theModel) {
List<CouponType> couponType = new ArrayList<CouponType>( Arrays.asList(CouponType.values()));
System.out.println(couponType);
theModel.addAttribute("couponType", couponType);
theModel.addAttribute("theCoupon", new Coupon());
return "add";
}
#RequestMapping("/create")
public String add(#ModelAttribute("theCoupon") Coupon theCoupon) {
theCoupon.setId(0);
System.out.println(theCoupon);
couponService.save(theCoupon);
return "savedCoupon";
}
I am getting this error:
java.sql.SQLSyntaxErrorException: Unknown column 'coupon0_.coupon_type' in 'field list'
Here is a screenshot of the database structure, the names are the same I have no idea whats the problem.
Also, here is the Coupon pojo:
#Entity
#Table(name = "coupon")
public class Coupon {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#Column(name = "title")
private String title;
#Column(name = "startDate")
private String startDate;
#Column(name = "endDate")
private String endDate;
#Column(name = "amount")
private int amount; // decrease amount on every customer purchase
#Column(name = "couponType")
private String couponType;
#Column(name = "message")
private String message;
#Column(name = "price")
private double price;
#Column(name = "image")
private String image;
public Coupon(long id, String title, String startDate, String endDate, int amount, String couponType,
String message, double price, String image) {
super();
this.id = id;
this.title = title;
this.startDate = startDate;
this.endDate = endDate;
this.amount = amount;
this.couponType = couponType;
this.message = message;
this.price = price;
this.image = image;
}
public Coupon() {
super();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getCouponType() {
return couponType;
}
public void setCouponType(String couponType) {
this.couponType = couponType;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Override
public String toString() {
return "Coupon [id=" + id + ", title=" + title + ", startDate=" + startDate + ", endDate=" + endDate
+ ", amount=" + amount + ", couponType=" + couponType + ", message=" + message + ", price=" + price
+ ", image=" + image + "]";
}
}
Hope anyone of you could spot the problem, any help would be appreciated!

[SOLVED]
The problem was that I was using two words in my var, like couponType, would be coupon_type on the data base.
changed it to type only, the pojo & the database & now it works fine!
hope this helps to anyone that had this problem.

Related

JSON parse error, unable to deserialize value of type `java.time.LocalDate` in STS 4.15.3 windows version

I'm new to this tool and I'm having trouble with this specific issue. I looked for an example But could not find something similar, better, I found a possible solution, but in my case It doesn't work.
I have this narrow project that resembles our famous CRUD, and I'm trying to reference the primary key from one table to another.
Client Entity:
#Entity
#Table(name = "client")
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "cpf", length = 14)
private String cpf;
#Column(name = "name", length = 100)
private String name;
#Column(name = "birth_date")
private LocalDate birthDate;
#Column(name = "address", length = 255)
private String address;
#Column(name = "telephone", length = 14)
private String telephone;
#Column(name = "email", length = 200)
private String email;
#Column(name = "date_register", insertable = true, updatable = false)
private LocalDate dateRegister;
public Client() {
super();
}
public Client(Long id, String cpf, String name, LocalDate birthDate, String address, String telephone, String email, LocalDate dateRegister) {
super();
this.id = id;
this.cpf = cpf;
this.name = name;
this.birthDate = birthDate;
this.address = address;
this.telephone = telephone;
this.email = email;
this.dateRegister = dateRegister;
}
public Client(String cpf, String name, LocalDate birthDate, String address, String telephone, String email, LocalDate dateRegister) {
super();
this.cpf = cpf;
this.name = name;
this.birthDate = birthDate;
this.address = address;
this.telephone = telephone;
this.email = email;
this.dateRegister = dateRegister;
}
#PrePersist
public void prePersist() {
setDateRegister(LocalDate.now());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDateRegister() {
return dateRegister;
}
public void setDateRegister(LocalDate dateRegister) {
this.dateRegister = dateRegister;
}
#Override
public String toString() {
return "Client [id=" + id + ", cpf=" + cpf + ", name=" + name + ", birthDate=" + birthDate + ", address="
+ address + ", telephone=" + telephone + ", email=" + email + ", dateRegister=" + dateRegister + "]";
}
}
Sale Entity:
#Entity
#Table(name = "sale")
public class Sale {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "client_id")
private Client client;
#OneToMany(mappedBy = "sale")
private List<SaleItem> items;
#Column(name = "payment_type", length = 10)
#Enumerated(EnumType.STRING)
private PaymentType paymentType;
#Column(name = "amount")
private BigDecimal amount;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public List<SaleItem> getItems() {
return items;
}
public void setItems(List<SaleItem> items) {
this.items = items;
}
public PaymentType getPaymentType() {
return paymentType;
}
public void setPaymentType(PaymentType paymentType) {
this.paymentType = paymentType;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
#Override
public String toString() {
return "Sale [id=" + id + ", client=" + client + ", items=" + items + ", paymentType=" + paymentType
+ ", amount=" + amount + "]";
}
}
The objective is to link the client to a sale through its primary key. These two codes refer to the sales repository and its controller:
SaleRepository:
public interface SaleRepository extends JpaRepository<Sale, Long> {
}
SaleController:
#RestController
#RequestMapping("/api/sales")
#CrossOrigin("*")
public class SaleController {
#Autowired
private SaleRepository repository;
#Autowired
private SaleItemRepository saleItemrepository;
#PostMapping
#Transactional
public void save(#RequestBody Sale sale) {
repository.save(sale);
sale.getItems().stream().forEach(saleItem -> saleItem.setSale(sale));
saleItemrepository.saveAll(sale.getItems());
}
}
And the problem is exactly how this reference is being made. In the current private Client client; way , the client object is being passed in full instead of its id, that's why it throws this following error when I try to register the sale.
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDate` from String "31/05/1968": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '31/05/1968' could not be parsed at index 0; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDate` from String "31/05/1968": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '31/05/1968' could not be parsed at index 0<EOL> at [Source: (PushbackInputStream); line: 1, column: 87] (through reference chain: MyNameIsRafaelSampaio.github.com.bruxo_vendas_ltda_api.model.Sale["client"]->MyNameIsRafaelSampaio.github.com.bruxo_vendas_ltda_api.model.Client["birthDate"])]
As was to be expected, since the column birthDate present in the client entity is not being treated correctly in the sale entity. I did research on a possible solution but none made much sense to me, I believe for being a newbie, one of the solutions that I found more understandable was the use of the #MapsId tag. I tried to make changes to adapt, but I was not successful, if you can help I will be grateful.

#OneToOne Annotation Error : references an unknown entity:

I work on learning app, in fact making relationships between two tables.
User - Base table that can have one primary account
PrimaryAccount - that is also reference to PrimaryTransactions with OnetoMany annotation,
PrimaryTransaction - has reference to PrimaryAccount as many transaction related to primary Account.
Although (as per my perception) I'm mentioning right reference between both class but getting an error as follows. Perhaps error lies because of PrimaryAccount.java doesn't have reference for User.java whereas User.java does have for PrimaryAccount.java.
I wonder that the instructor I follow successful runing his app in this way.
Any help will be appreciated.
Error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'entityManagerFactory' defined in class path resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation
of init method failed; nested exception is org.hibernate.AnnotationException: #OneToOne or
#ManyToOne on com.userfront.domain.PrimaryTransaction.primaryAccount references an unknown
entity: com.userfront.domain.PrimaryAccount
PrimaryAccount.java
package com.userfront.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
public class PrimaryAccount {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private int accountNumber;
private BigDecimal accountBalance;
#OneToMany(mappedBy = "primaryAccount", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JsonIgnore
private List<PrimaryTransaction> primaryTransactionList;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public BigDecimal getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(BigDecimal accountBalance) {
this.accountBalance = accountBalance;
}
public List<PrimaryTransaction> getPrimaryTransactionList() {
return primaryTransactionList;
}
public void setPrimaryTransactionList(List<PrimaryTransaction> primaryTransactionList) {
this.primaryTransactionList = primaryTransactionList;
}
}
PrimaryTransaction.java
package com.userfront.domain;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
#Entity
public class PrimaryTransaction {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Date date;
private String description;
private double amount;
public PrimaryTransaction() {
}
public PrimaryTransaction(Date date, String description, String type, String status, double amount, BigDecimal availableBalance, PrimaryAccount primaryAccount) {
this.date = date;
this.description = description;
this.amount = amount;
this.primaryAccount = primaryAccount;
}
#ManyToOne
#JoinColumn(name = "primary_account_id")
private PrimaryAccount primaryAccount;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public PrimaryAccount getPrimaryAccount() {
return primaryAccount;
}
public void setPrimaryAccount(PrimaryAccount primaryAccount) {
this.primaryAccount = primaryAccount;
}
}
User.java
package com.userfront.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "userId", nullable = false, updatable = false)
private Long userId;
private String username;
private String password;
private String firstName;
private String lastName;
#Column(name = "email", nullable = false, updatable = false)
private String email;
private String phone;
private boolean enable = true;
#OneToOne
private PrimaryAccount primaryAccount;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public PrimaryAccount getPrimaryAccount() {
return primaryAccount;
}
public void setPrimaryAccount(PrimaryAccount primaryAccount) {
this.primaryAccount = primaryAccount;
}
#Override
public String toString() {
return "User{" +
"userId=" + userId +
", username='" + username + '\'' +
", password='" + password + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
", enable=" + enable +
", primaryAccount=" + primaryAccount +
'}';
}
}
You have to add #Entity annotation to PrimaryAccount
In Spring Data Jpa, you have to annotate the class with #Entity Annotation,That's why the bean is not created and also if you want you can mention #Table annotation to mention the table name.

Having an issue retrieving list from database using Ecplise

I'm currently working on a coupon project. While working on my facade class, I encounter an issue getting a list of coupons that customer has purchased by entering his ID from a table with foreign keys.
The method I was using:
#Override
public List<Coupon> getPurchasedCoupons(int customerID) throws SQLException {
{
Connection connection = pool.getConnection();
ArrayList<Coupon> customerCoupon = new ArrayList<>();
ArrayList<Long> customerCouponID = new ArrayList<>();
Statement stmt = null;
long coupID = 0;
stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT * FROM `couponsystem`.`customers_vs_coupons` WHERE (`CUSTOMER_ID` = '?')");
while ((resultSet != null) && (resultSet.next())) {
coupID = resultSet.getLong("COUPON_ID");
customerCouponID.add(coupID);
}
Iterator<Long> myIterator = customerCouponID.iterator();
while (myIterator.hasNext()) {
Long couponID = myIterator.next();
resultSet = stmt.executeQuery(
"SELECT * FROM `couponsystem`.`customers_vs_coupons` where COUPON_ID = " + couponID);
while (resultSet.next()) {
Coupon coupon = new Coupon(resultSet.getInt(1), resultSet.getInt(2),
Category.categoryFor(resultSet.getInt(3)), resultSet.getString(4), resultSet.getString(5),
resultSet.getDate(6), resultSet.getDate(7), resultSet.getInt(8), resultSet.getDouble(9),
resultSet.getString(10));
customerCoupon.add(coupon);
}
}
ConnectionPool.getInstance().restoreConnection(connection);
return customerCoupon;
}
}
Coupon class:
import java.util.Date;
public class Coupon {
private int id;
private int companyID;
private Category category;
private String title;
private String description;
private Date startDate;
private Date endDate;
private int amount;
private double price;
private String image;
public Coupon(int companyID, Category category, String title, String description, Date startDate, Date endDate,
int amount, double price, String image) {
this.companyID = companyID;
this.category = category;
this.title = title;
this.description = description;
this.startDate = startDate;
this.endDate = endDate;
this.amount = amount;
this.price = price;
this.image = image;
}
public Coupon(int id, int companyID, Category category, String title, String description, Date startDate,
Date endDate, int amount, double price, String image) {
this.id = id;
this.companyID = companyID;
this.category = category;
this.title = title;
this.description = description;
this.startDate = startDate;
this.endDate = endDate;
this.amount = amount;
this.price = price;
this.image = image;
}
public Coupon() {
super();
}
public void setId(int id) {
this.id = id;
}
public void setCompanyID(int companyID) {
this.companyID = companyID;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getId() {
return id;
}
public int getCompanyID() {
return companyID;
}
#Override
public String toString() {
return "Coupon: ID = " + id + ", Company ID = " + companyID + ", Category = " + category + ", Title = " + title
+ ", Description = " + description + ", Start Date = " + startDate + ", End Date = " + endDate
+ ", Amount = " + amount + ", Price = " + price + ", IMAGE = " + image;
}
}
Calling the method:
public List<Coupon> getCustomerCoupons() throws SQLException {
return coup.getPurchasedCoupons(customerID);
}
My SQL table:
Coupon_vs_Customer table contains only 2 rows. which both are foreign keys to other tables.
CustomerID is connected to table of 'CUSTOMERS' while coupon_ID is connected to table 'COUPONS'
CustomerID Coupon_ID
1 1
1 2
1 3
As you can see above customer with ID 1 owns 3 coupons, and I'm trying to read them in a list on my eclipse project.
I do not get any exception, however I get returned an empty arraylist. I cannot seem to solve this issue since I am quite new to JDBC.
Your first query tries to find customers with id = "?". Maybe this was an attempt to create a prepared statement but then you need a few more steps
String query = "SELECT COUPON_ID FROM couponsystem.customers_vs_coupons WHERE CUSTOMER_ID = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, customerID);
ResultSet resultSet = statement.executeQuery();

How to handle message error in Entity when using #MockMvc

I using #MockMvc test in spring controller but i have a question.
How to handle message error when MockMvc test not pass method.
Entity:
#Entity
#ApiModel(description = "All details about the Product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO,generator = "system-uuid")
#GenericGenerator(name = "system-uuid",strategy = "uuid2")
private String id;
#NotNull(message = "name can not null")
#ApiModelProperty(notes = "The name is product")
private String name;
#ApiModelProperty(notes = "The type is product")
private String type;
#NotNull(message = "category can not null")
private String category;
private String description;
private Double prince;
public Product() {
}
public Product(String name, String type, String category, String description, Double prince) {
this.name = name;
this.type = type;
this.category = category;
this.description = description;
this.prince = prince;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrince() {
return prince;
}
public void setPrince(Double prince) {
this.prince = prince;
}
#Override
public String toString() {
return "Product{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", type='" + type + '\'' +
", category='" + category + '\'' +
", description='" + description + '\'' +
", prince=" + prince +
'}';
}
}
StudentController:
#RestController
#RequestMapping("/products")
public class ProductController {
#PostMapping
public ResponseEntity<ProductDto> createProduct(#RequestBody Product product) {
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(product.getId()).toUri();
return ResponseEntity.created(location).body(productService.createProduct(product));
}
}
In above entity, I want using #MockMvc test createProduct. If name in product is null, i want show message in #MockMvc . It look like: "name can not null" . If pass, i don't want show it. Bellow my test:
#Test
public void givenProductURIWithPost_whenMockMVC_thenVerifyResponse() {
this.mockMvc.perform(post("/products")).andDo(print())
.andExpect(status().isOk()).andExpect(content()
.contentType("application/json;charset=UTF-8"))
}
I have two question:
1.How to show message "name can not null" if name in product is
null in #mockmvc.
2. If my project in 20 field in Products entity : Example: name,category.. I can test sequence field in Products or only test
one time contain all field.

Passing mapped object through form:select tags

I keep getting 400 Bad Request error whenever im trying to pass an entire object through form:select.
HTTP Status 400 – Bad Request
Type Status Report
Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
This is my select form:
<html>
<head>
<title>Dodaj produkt do aukcji</title>
</head>
<body>
<form:form action="saveProduct${auction.id}" modelAttribute="newProduct" method="POST">
<label>Nazwa:</label> <form:input path="name"/><br>
<label>Cena:</label> <form:input path="price"/><br>
<label>Kategoria:</label>
<form:select path="productCategory">
<form:options items="${productCategories}" itemLabel="name"/>
</form:select><br>
<input type="submit" value="Dodaj" class="save"/><br>
</form:form>
</body>
</html>
Controller:
#GetMapping("/addProductPage")
public String addProductPage(#RequestParam("auctionId") int id,Model theModel) {
Collection <ProductCategory> pCategories = productCategoryService.getProductCategories();
Auction auction = auctionService.getAuction(id);
Product product = new Product();
ProductCategory pCategory = new ProductCategory();
theModel.addAttribute("auction", auction);
theModel.addAttribute("newProduct", product);
theModel.addAttribute("productCategories", pCategories);
return "add-product";
}
#PostMapping("/saveProduct{someId}")
public String saveProduct(#ModelAttribute("newProduct") Product product, #PathVariable(value="someId") String someId) {
Auction auction = auctionService.getAuction(Integer.parseInt(someId));
Collection<Product> products = auction.getProducts();
products.add(product);
auction.setProducts(products);
product.setAuction(auction);
auctionService.saveAuction(auction);
productService.saveProduct(product);
return "redirect:/showMyAuctions";
}
Product entity:
#Entity
#Table(name="product")
public class Product {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="product_id")
private int id;
#Column(name="name")
private String name;
#Column(name="price")
private float price;
#ManyToOne
#JoinColumn(name="category_id")
private ProductCategory productCategory;
#ManyToOne
#JoinColumn(name="auction_id")
private Auction auction;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public ProductCategory getProductCategory() {
return productCategory;
}
public void setProductCategory(ProductCategory productCategory) {
this.productCategory = productCategory;
}
public Auction getAuction() {
return auction;
}
public void setAuction(Auction auction) {
this.auction = auction;
}
#Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", price=" + price + ", productCategory=" + productCategory
+ "]";
}
}
Product category entity:
#Entity
#Table(name="product_category")
public class ProductCategory {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="category_id")
private int id;
#Column(name="name")
private String name;
#OneToMany(mappedBy="productCategory", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
Collection<Product> products;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Product> getProducts() {
return products;
}
public void setProducts(Collection<Product> products) {
this.products = products;
}
#Override
public String toString() {
return "ProductCategory [id=" + id + ", name=" + name + "]";
}
}
What i want is the chosen product category to be added to the product.
Spring expect productCategory to be an object but it's name of productCategory as specified in tag.
you need to try something like:
<form:select path="productCategory.name">
<form:options items="${productCategories}" itemLabel="name" itemValue= "name"/>
</form:select>

Categories

Resources