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

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>

Related

created_by is always set to null in the database and Version does not work properly

I am trying to implement one entity to see how Auditing works in spring. I have tow issues here:
First issue is that "created_by" field is always set to null in the database, although I have created a bean of AuditAware and set it to myself.
Second issue is that whenever I want to insert something into the country table, it forces me to provide the version number. It is not the behaviour I want as I expect version gets picked up by the spring itself
I appreciate if someone could help me to tackle these two issues.
AbstractMethodEntity is as follow:
package com.xx.xxx.hotel;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.time.LocalDateTime;
#MappedSuperclass
#EntityListeners({ AuditingEntityListener.class })
public abstract class AbstractModelEntity<U> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "created_by")
#CreatedBy
private U CreatedBy;
#Column(name = "create_date")
#CreatedDate
private LocalDateTime createdDate;
#Version
private long version;
#Column(name = "modified_by")
#LastModifiedBy
private U lastModifiedBy;
#Column(name = "modified_date")
#LastModifiedDate
private LocalDateTime lastModifiedDate;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public U getCreatedBy() {
return CreatedBy;
}
public void setCreatedBy(U createdBy) {
CreatedBy = createdBy;
}
public LocalDateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(LocalDateTime createdDate) {
this.createdDate = createdDate;
}
public U getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(U lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public LocalDateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(LocalDateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
The Country entity:
package com.xx.xxx.hotel.service.country;
import com.miraftabi.hossein.hotel.AbstractModelEntity;
import org.hibernate.envers.AuditOverride;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Audited
#AuditOverride(forClass = AbstractModelEntity.class, isAudited = true)
#Table(name = "country")
public class CountryEntity extends AbstractModelEntity<String> {
#Column(name = "name", nullable = false)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
AuditAwareImpl file:
package com.xx.xxx.hotel.service;
import org.springframework.data.domain.AuditorAware;
import java.util.Optional;
public class AuditorAwareImpl implements AuditorAware<String> {
#Override
public Optional<String> getCurrentAuditor() {
return Optional.of("Hossein");
}
}
AuditConfiguraiton file:
package com.xx.xxx.hotel.config;
import com.xx.xxx.hotel.service.AuditorAwareImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
#Configuration
#EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class AuditConfiguration {
#Bean
public AuditorAware<String> auditorAware() {
return new AuditorAwareImpl();
}
}
RepositoryConfiguration file:
package com.xx.xxx.hotel.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.envers.repository.support.EnversRevisionRepositoryFactoryBean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#Configuration
#EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
public class RepositoryConfiguration {
}
CountryRevisionRepository file:
package com.xx.xxx.hotel.service.country;
import org.springframework.data.repository.history.RevisionRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface CountryRevisionRepository extends RevisionRepository<CountryEntity, Long, Integer> {
}
Application.properties:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/hotel
spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

hibernate & spring, invalid identifier

I have stuck on dealing with DB by using hibernate orm in spring mvc environment.
I have some tables; but I'm not gonna tell you my tables(If you want, I will edit this post)
The problem is that when hibernate runs, it generates sql - I can see the sql by configuring "hbm2_ddl auto" - but the sql has invalid identifier.
select newsreplie0_.news_article# as news6_3_4_, newsreplie0_.reply# as reply1_4_,
newsreplie0_.reply# as reply1_4_3_, newsreplie0_.account_account# as account5_4_3_,
newsreplie0_.content as content4_3_, newsreplie0_.dt as dt4_3_,
newsreplie0_.news_article# as news6_4_3_, newsreplie0_.reply_at as reply4_4_3_,
account1_.account# as account1_0_0_, account1_.email as email0_0_,
account1_.passwd as passwd0_0_, accountpro2_.account# as account1_1_1_,
accountpro2_.nickname as nickname1_1_, accountsec3_.account# as account1_2_2_,
accountsec3_.activate_key as activate2_2_2_, accountsec3_.activated as activated2_2_,
accountsec3_.enabled as enabled2_2_, accountsec3_.login_failed as login5_2_2_
from news_reply newsreplie0_
left outer join
cookingstep.account account1_ on newsreplie0_.account_account#=account1_.account#
left outer join
cookingstep.account_profile accountpro2_ on account1_.account#=accountpro2_.account#
left outer join
cookingstep.account_security accountsec3_ on account1_.account#=accountsec3_.account#
where newsreplie0_.news_article#=9
{FAILED after 4 msec}
The above statement is a sql generated by hibernate. And the error is:
java.sql.SQLSyntaxErrorException:
ORA-00904: "NEWSREPLIE0_"."ACCOUNT_ACCOUNT#": Invalid Identifier
In that exception message, there is a column called "ACCOUNT_ACCOUNT#".
It should be just "ACCOUNT#", not following "ACCOUNT_".
So, how to remove the word ?
EDIT:
Thank you all for your reply. I have asked similar question before.
And I checked out that article, it seems the problem was #JoinColumn annotation missing. Now it works out.
Here is my Entities.
Account.java for user information
package com.musicovery12.cookingstep.persistence.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
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.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name="account", catalog="cookingstep", uniqueConstraints= {
#UniqueConstraint(columnNames="email")
})
public class Account implements Serializable{
private static final long serialVersionUID = 1L;
private int accountId;
private String email;
private String password;
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
private AccountProfile profile;
private AccountSecurity security;
private Set<News> newsList;
private Set<NewsReply> newsReplyList;
public Account() {}
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_account")
#SequenceGenerator(name="seq_account", sequenceName="seq_account", allocationSize=1)
#Column(name="account#", unique=true, nullable=false)
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
#Column(name="email", unique=true, nullable=false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="passwd", nullable=false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#OneToMany(mappedBy="pk.account", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
#OneToOne(mappedBy="account", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public AccountProfile getProfile() {
return profile;
}
public void setProfile(AccountProfile profile) {
this.profile = profile;
}
#OneToOne(mappedBy="account", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public AccountSecurity getSecurity() {
return security;
}
public void setSecurity(AccountSecurity security) {
this.security = security;
}
#OneToMany(mappedBy="account", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public Set<News> getNewsList() {
return newsList;
}
public void setNewsList(Set<News> newsList) {
this.newsList = newsList;
}
#OneToMany(mappedBy="account", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public Set<NewsReply> getNewsReplyList() {
return newsReplyList;
}
public void setNewsReplyList(Set<NewsReply> newsReplyList) {
this.newsReplyList = newsReplyList;
}
}
and NewsReply.java for news community article's reply list.
package com.musicovery12.cookingstep.persistence.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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="news_reply")
public class NewsReply {
private int replyId;
private News news;
private Date date;
private String content;
private Account account;
private int replyAt;
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="gen_seq")
#SequenceGenerator(name="gen_seq", sequenceName="gen_seq", allocationSize=1)
#Column(name="reply#", unique=true, nullable=false)
public int getReplyId() {
return replyId;
}
public void setReplyId(int replyId) {
this.replyId = replyId;
}
#Temporal(TemporalType.DATE)
#Column(name="dt")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Column(name="content", nullable=false)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Column(name="reply_at")
public int getReplyAt() {
return replyAt;
}
public void setReplyAt(int replyAt) {
this.replyAt = replyAt;
}
#ManyToOne
public News getNews() {
return news;
}
public void setNews(News news) {
this.news = news;
}
#ManyToOne
#JoinColumn(name="account#", referencedColumnName="account#")
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
in NewsReply.java, there was no JoinColumn annotation to point foreing key column name.
Thank you.
#ManyToOne
#JoinColumn(name="account#", referencedColumnName="account#")
public Account getAccount() {
return account;
}
This is the problem, you tell hibernate the table has a technical name of account# what is not allowed.
What you can do is to force hibernate to use that # by defining
#ManyToOne
#JoinColumn(name="`account#`", referencedColumnName="`account#`")
public Account getAccount() {
return account;
}
But this is bad style and you have to do it on the owning-side too.
Why dont you let hibernate create the entitys for you? He is much more precisly!

Hibernate relationship code

Getting following error while executing the Hibernate program for a relationship:
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: com.Employee.Department.Department, at table: Employee, for columns: [org.hibernate.mapping.Column(dept)]
The code is shown in below:
Employee.java: Contains the 1-M relationship
package com.Employee.Employee;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.Employee.Department.Department;
#Entity
#Table(name = "Employee_1toMany")
public class Employee {
#Id
#GeneratedValue
#Column(name = "EId")
private int emp_id;
#Column(name = "EName")
private String name;
private Department dept;
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToOne
#JoinColumn(name = "DepartmentID")
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
}
Department.java: Contains M to 1 relationship
package com.Employee.Department;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.Employee.Employee.Employee;
#Entity
#Table(name = "Department_1toMany")
public class Department {
#Id
#GeneratedValue
#Column(name = "DId")
private int Dept_id;
#Column(name = "DName")
private String Dept_name;
private List<Employee> emp;
public int getDept_id() {
return Dept_id;
}
public void setDept_id(int dept_id) {
Dept_id = dept_id;
}
public String getDept_name() {
return Dept_name;
}
public void setDept_name(String dept_name) {
Dept_name = dept_name;
}
#OneToMany(targetEntity = Employee.class, mappedBy = "dept", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<Employee> getEmp() {
return emp;
}
public void setEmp(List<Employee> emp) {
this.emp = emp;
}
}
MainClass.java:
package com.Employee.MainClass;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.Employee.Department.Department;
import com.Employee.Employee.Employee;
public class MainApp {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Department dept = new Department();
dept.setDept_name("Modern College");
Employee emp1 = new Employee();
emp1.setName("Rakesh");
Employee emp2 = new Employee();
emp2.setName("Sagar");
emp1.setDept(dept);
emp2.setDept(dept);
session.save(dept);
session.save(emp1);
session.save(emp2);
tx.commit();
}
}
hibernate.cfg.xml: This is the configuration class
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/EMP_PRACTISE</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.Employee.Department.Department"></mapping>
<mapping class="com.Employee.Employee.Employee"></mapping>
</session-factory>
</hibernate-configuration>
Exception in detail:
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: com.Employee.Department.Department, at table: Employee, for columns: [org.hibernate.mapping.Column(dept)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:455)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:422)
at org.hibernate.mapping.Property.isValid(Property.java:226)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:597)
at org.hibernate.mapping.RootClass.validate(RootClass.java:265)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:451)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at com.Employee.MainClass.MainApp.main(MainApp.java:13)
I believe you cannot mix fields and getter methods annotations. Place them to corresponding fields.
Employee.java
#ManyToOne
#JoinColumn(name = "DepartmentID")
private Department dept;
// mapping annotation on the field
public Department getDept() {
return dept;
}
Department.java
#OneToMany(targetEntity = Employee.class, mappedBy = "dept", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Employee> emp;
// mapping annotation on the field
public List<Employee> getEmp() {
return emp;
}

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.

Hibernate Error Invalid Column Name

I am trying to make a one to many and many to one relation in hibernate and spring.
below is my code for product class
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="Product")
public class Product implements Serializable{
#Id
#Column(name="productId")
#GeneratedValue
private Integer productId;
#Column(name="productName")
private String productName;
#Column(name="productPrice")
private int productPrice;
//---------------------------------------item mapped to category------------------------------------------//
#ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinTable(
name="CategoryProduct",
joinColumns= #JoinColumn(name="productId")
)
private Category category;
//--------------------------------------------------------------------------------------------------------//
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getProductPrice() {
return productPrice;
}
public void setProductPrice(int productPrice) {
this.productPrice = productPrice;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
below is my code for category class
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name="Category")
public class Category implements Serializable{
#Id
#Column(name="categoryId")
#GeneratedValue
private Integer categoryId;
#Column(name="categoryName")
private String categoryName;
#OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#JoinTable(
name="CategoryProduct",
joinColumns = #JoinColumn(name="categoryId"),
inverseJoinColumns = #JoinColumn(name="productId")
)
public Set<Product> product;
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Set<Product> getProduct() {
return product;
}
public void setProduct(Set<Product> product) {
this.product = product;
}
}
Whenever i run the code i am getting Invalid column name 'category_categoryId'.
Structure of my tables
Product has column as productId, poductName and productPrice
category has columns as categoryId, categoryName
categoryproducts has columns as categoryId and productId
you forgot to put inverseJoinColumns at your #JoinTable in Product Class. This cause hibernate to use their convention of joinTable which is <ClassName>_<columnName>. Change it to
#JoinTable(
name="CategoryProduct",
joinColumns = #JoinColumn(name="productId"),
inverseJoinColumns = #JoinColumn(name="categoryId")
)
private Category category;
However, seeing at your design, you are actually creating 2 uni-directional association between product and category. If you want to create bi-directional association, I suggest you change the One side (Category), to use mappedBy
#OneToMany(mappedBy="category", cascade=CascadeType.ALL,fetch=FetchType.EAGER)
public Set<Product> product;
It will generally achieve the same result. Hope it helps!

Resources