I'm using XML mapping. I tried to make a many to many association between Invoice and Product (an invoice can contain many products and a product can belong to many invoices). My approach was to make an association called "InvoiceLine" that will contain a single product, its quantity and total and this InvoiceLine would belong to a single Invoice.
-An Invoice has many invoiceLines
-An InvoiceLine has many Products and has an attribute which is the Invoice Id that corresponds to the invoice
While searching for a way to make this mapping, I came to know that you can't make a many to many association with an extra column and that I need to make 2 one-to-many associations to replace that many-to-many association.
This is what I tried but I keep getting the error:
19359 [http-nio-8088-exec-3] ERROR org.hibernate.property.BasicPropertyAccessor - IllegalArgumentException in class: model.InvoiceLine, getter method of property: Product
org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of model.InvoiceLine.Product
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:195)
at org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValue(AbstractComponentTuplizer.java:87)
at org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValues(AbstractComponentTuplizer.java:93)
at org.hibernate.tuple.component.PojoComponentTuplizer.getPropertyValues(PojoComponentTuplizer.java:109)
at org.hibernate.type.serComponentType.getPropertyValues(ComponentType.java:376)
at org.hibernate.type.ComponentType.getHashCode(ComponentType.java:207)
at org.hibernate.engine.EntityKey.generateHashCode(EntityKey.java:126)
at org.hibernate.engine.EntityKey.<init>(EntityKey.java:70)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:184)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:144)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:562)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:550)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:546)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:342)
at com.sun.proxy.$Proxy5.save(Unknown Source)
at dao.GenericDaoHibernateImpl.add(GenericDaoHibernateImpl.java:49)
at dao.InvoiceLineDaoImpl.ajouter(InvoiceLineDaoImpl.java:12)
at services.InvoiceLineServiceImpl.ajouter(InvoiceLineServiceImpl.java:25)
at controller.InvoiceLineServlet.doPost(InvoiceLineServlet.java:123)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:169)
... 50 more
Here are my mapping classes, the association entity and the servlet.
InvoiceLine.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="model.InvoiceLine" table="INVOICE_LINE">
<composite-id name="id" class="model.InvoiceLine">
<key-many-to-one name="Product" entity-name="model.Product"
column="CODE_PRODUCT" />
<key-many-to-one name="Invoice" entity-name="model.Invoice"
column="ID_INVOICE"/>
</composite-id>
<property name="qte" column="quantity" />
<property name="total" column="TOTAL" />
</class>
</hibernate-mapping>
Product.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="model.Product" table="PRODUCT">
<meta attribute="class-description">
</meta>
<id name="codeProduct" column="CODE_PRODUCT">
<generator class="native"/>
</id>
<property name="name" column="NAME" />
<property name="description" column="DESCRIPTION" />
<property name="price" column="PRICE" />
<property name="quantityStock" column="QUANTITY_STOCK" />
<many-to-one name="category" class="model.category" fetch="select" update="true">
<column name="CODE_CATEGORY" not-null="true" />
</many-to-one>
<set name="invoiceline" table="INVOICE_LINE" inverse="true"
fetch="select" cascade="all">
<key>
<column name="CODE_PRODUCT" not-null="true" />
</key>
<one-to-many class="model.InvoiceLine" />
</set>
</class>
</hibernate-mapping>
Invoice.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="model.Invoice" table="INVOICE">
<meta attribute="class-description">
</meta>
<id name="id" column="ID_INVOICE">
<generator class="native"/>
</id>
<property name="date" column="DATE" />
<property name="total" column="TOTAL" />
<many-to-one name="client" class="model.Client" fetch="select" update="true">
<column name="ID_CLIENT" not-null="true" />
</many-to-one>
<set name="InvoiceLine" table="INVOICE_LINE" inverse="true"
fetch="select" cascade="all">
<key>
<column name="ID_INVOICE" not-null="true" />
</key>
<one-to-many class="model.InvoiceLine" />
</set>
</class>
</hibernate-mapping>
And this is the SERVLET
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if ((request.getParameter("addInvoiceLine")) != null) {
RequestDispatcher dispatcher = request.getRequestDispatcher("/View/AddInvoiceLine.jsp");
dispatcher.forward(request, response);
//get the InvoiceId from a select list
String[] invoice = request.getParameterValues("invoice");
int codeInvoice = Integer.parseInt(invoice[0]);
//get the ProductId from a select list
String[] product= request.getParameterValues("product");
int codeProd = Integer.parseInt(product[0]);
//get the quantity from a textField and convert it to integer
String stringQuantity = request.getParameter("quantity");
int quantity= Integer.parseInt(stringQuantity);
InvoiceServiceImpl InvoiceService = new InvoiceServiceImpl();
Invoice invoice= invoiceService.return(codeInvoice);
ProductServiceImpl productService = new ProductServiceImpl();
Product product = productService.return(codeProd);
InvoiceLineServiceImpl invoiceLineServiceImpl = new InvoiceLineServiceImpl();
InvoiceLine invoiceLine= new InvoiceLine(quantity);
invoiceLine.setProduct(product);
invoiceLine.setInvoice(invoice);
invoiceLineServiceImpl.add(invoiceLine);
The line that throws the error is:
invoiceLineServiceImpl.add(invoiceLine);
the method add is inherited from this GenericDao:
package dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
#SuppressWarnings("unchecked")
public abstract class GenericDaoHibernateImpl<E, PK extends Serializable> implements GenericDao<E, PK> {
/**
* By defining this class as abstract, we prevent Spring from creating
* instance of this class If not defined as abstract,
* getClass().getGenericSuperClass() would return Object. There would be
* exception because Object class does not hava constructor with parameters.
*/
protected Class<? extends E> daoType;
public static SessionFactory sessionFactory;
#SuppressWarnings("rawtypes")
public GenericDaoHibernateImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
daoType = (Class) pt.getActualTypeArguments()[0];
}
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable t) {
t.printStackTrace();
}
}
public static SessionFactory getSession() {
return sessionFactory;
}
protected Session currentSession() {
return getSession().getCurrentSession();
}
#Override
public void add(E entity) {
currentSession().beginTransaction();
currentSession().save(entity);
currentSession().getTransaction().commit();
}
#Override
public void update(E entity) {
currentSession().beginTransaction();
currentSession().update(entity);
currentSession().getTransaction().commit();
}
#Override
public void remove(E entity) {
currentSession().beginTransaction();
// E oldEntity = (E) currentSession().l;
currentSession().delete(entity);
currentSession().getTransaction().commit();
}
#Override
public E find(PK key) {
currentSession().beginTransaction();
return (E) currentSession().get(daoType, key);
}
#Override
public List<E> getAll() {
currentSession().beginTransaction();
return currentSession().createCriteria(daoType).list();
}
}
Please note that the method add works perfectly for other entities like Product, so that got me thinking that the issue is with the xml mapping of InvoiceLineand not the java code
This is my InvoiceLine entity
package model;
import java.io.Serializable;
public class InvoiceLine implements Serializable{
private long id;
private double total;
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private Product product;
private Invoice invoice;
private int quantity;
public InvoiceLine() {
super();
}
public InvoiceLine(int quantity) {
super();
this.quantity= quantity;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Invoice getInvoice() {
return invoice;
}
public void setInvoice(Invoice invoice) {
this.invoice= invoice;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity= quantity;
}
}
Product entity
package model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Product implements Serializable{
private int codeProduct;
private String name;
private String description;
private Double price;
private int quantityStock;
private Category category;
private Set<InvoiceLine> invoiceLine= new HashSet<InvoiceLine>();
public Set<InvoiceLine> getInvoiceLine() {
return invoiceLine;
}
public void setInvoiceLine(Set<InvoiceLine> invoiceLine) {
this.invoiceLine= invoiceLine;
}
public Product() {
}
public Product(String name, String description, Double price, int quantityStock) {
this.name = name;
this.description = description;
this.price = price;
this.quantityStock = quantityStock;
}
// getters and setters
public int getCodeProduct() {
return codeProduct;
}
public void setCodeProduct(int codeProduct) {
this.codeProduct = codeProduct;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price= price;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public int getQuantityStock() {
return quantityStock;
}
public void setQuantityStock(int quantityStock) {
this.quantityStock = quantityStock;
}
}
try using
<many-to-one name="category" class="model.Category" fetch="select" update="true"> in product.hbm.xml
and
<key-many-to-one name="product" entity-name="model.Product"
column="CODE_PRODUCT" />
in InvoiceLine.hbm.xml
Related
I receive this exception when I run the code below to display items that belong to a specific category in the JTable:
private void categoryComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
try {
DefaultTableModel dtm = new DefaultTableModel();
String cat = this.categoryComboBox.getSelectedItem().toString();
session=sessionFactory.openSession();
transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(Items.class);
//HERE LIES THE PROBLEM BUT I HAVE NO CLUE HOW TO SOLVE IT
List<Items> itemlist = criteria.add(Restrictions.eq("category", cat).ignoreCase()).list();
transaction.commit();
session.close();
if (dtm.getColumnCount()==0) {
dtm.addColumn("Name");
dtm.addColumn("Category");
dtm.addColumn("Quantity");
dtm.addColumn("Net Price (per unit)");
dtm.addColumn("Gross Pice (per unit)");
dtm.addColumn("Net Price (total)");
dtm.addColumn("Gross Price (total)");
}
Font f = new Font("Georgia", Font.BOLD, 16);
JTableHeader header = itemTable.getTableHeader();
header.setFont(f);
itemTable.setRowHeight(25);
if (getQuantity().isEmpty()) {for (int i = 0; i < itemlist.size(); i++) {
dtm.addRow(new Object[]{itemlist.get(i).getName(), itemlist.get(i).getCategory().getName(),"-",itemlist.get(i).getNetPrice(), Math.round((Double.valueOf(itemlist.get(i).getNetPrice())*(1d+itemlist.get(i).getVatRate()/100d))), "-", "-"});
}
} else {
for (int i = 0; i < itemlist.size(); i++) {
dtm.addRow(new Object[]{itemlist.get(i).getName(), itemlist.get(i).getCategory().getName(), getQuantity().get(itemlist.get(i).getItemId()).getQuantity(), itemlist.get(i).getNetPrice(), itemlist.get(i).getNetPrice()*(itemlist.get(i).getVatRate()+1), getQuantity().get(itemlist.get(i).getItemId()).getQuantity()*itemlist.get(i).getNetPrice(), itemlist.get(i).getNetPrice()*(itemlist.get(i).getVatRate()+1)*getQuantity().get(itemlist.get(i).getItemId()).getQuantity()});
}
}
this.itemTable.setModel(dtm);} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
e.printStackTrace();
}
}
Also here are my XML mapping classes also:
Caregories.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Feb 9, 2019, 3:57:52 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="classes.Categories" table="CATEGORIES" schema="APP" optimistic-lock="version">
<id name="categoryId" type="int">
<column name="CATEGORY_ID" />
<generator class="native" />
</id>
<property name="name" type="string">
<column name="NAME" length="100" />
</property>
<set name="items" table="ITEMS" inverse="false" cascade="all" lazy="false" fetch="select">
<key>
<column name="CATEGORY_ID" not-null="true" />
</key>
<one-to-many class="classes.Items" />
</set>
</class>
</hibernate-mapping>
Items.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="classes.Items" table="ITEMS" schema="APP" optimistic-lock="version">
<id name="itemId" type="int" column="ITEM_ID">
<generator class="native" />
</id>
<property name="name" type="string" column="NAME" length="100"/>
<property name="netPrice" type="java.lang.Integer" column="NET_PRICE"/>
<property name="vatRate" type="java.lang.Integer" column="VAT_RATE"/>
<many-to-one name="category" class="classes.Categories" fetch="select" column="CATEGORY_ID" not-null="true" lazy="false"/>
</class>
</hibernate-mapping>
Here is the entity-relationship diagram of my database
Categories.java
package classes;
// Generated Feb 9, 2019, 3:57:50 PM by Hibernate Tools 4.3.1
import java.util.Set;
public class Categories implements java.io.Serializable {
private int categoryId;
private String name;
private Set<Items> items;
public Categories() {
}
public Categories(int categoryId, String name, Set<Items> items) {
this.categoryId = categoryId;
this.name = name;
this.items = items;
}
public int getCategoryId() {
return this.categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}
}
Items.java
package classes;
public class Items implements java.io.Serializable {
private int itemId;
private String name;
private Integer netPrice;
private Integer vatRate;
private Categories category;
public Items() {
}
public Items(int itemId, String name, Integer netPrice, Integer vatRate, Categories category) {
this.itemId = itemId;
this.name = name;
this.netPrice = netPrice;
this.vatRate = vatRate;
this.category = category;
}
public int getItemId() {
return this.itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNetPrice() {
return this.netPrice;
}
public void setNetPrice(Integer netPrice) {
this.netPrice = netPrice;
}
public Integer getVatRate() {
return this.vatRate;
}
public void setVatRate(Integer vatRate) {
this.vatRate = vatRate;
}
public Categories getCategory() {
return category;
}
public void setCategory(Categories category) {
this.category = category;
}
}
org.hibernate.PropertyAccessException: IllegalArgumentException
occurred calling getter of classes.Categories.categoryId at
org.hibernate.property.access.spi.GetterMethodImpl.get(GetterMethodImpl.java:65)
at
org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:224)
at
org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4933)
at
org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4633)
at
org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:226)
at
org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:276)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:495)
at org.hibernate.type.EntityType.nullSafeSet(EntityType.java:288) at
org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:2102)
at org.hibernate.loader.Loader.bindParameterValues(Loader.java:2071)
at
org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:2006)
at
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1920)
at
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
at org.hibernate.loader.Loader.doQuery(Loader.java:937) at
org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340)
at org.hibernate.loader.Loader.doList(Loader.java:2695) at
org.hibernate.loader.Loader.doList(Loader.java:2678) at
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2512) at
org.hibernate.loader.Loader.list(Loader.java:2507) at
org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:109)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1999) at
org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:370) at
stock.view.StockView.categoryComboBoxActionPerformed(StockView.java:530)
at
stock.view.StockView$FormListener.actionPerformed(StockView.java:344)
at
java.desktop/javax.swing.JComboBox.fireActionEvent(JComboBox.java:1264)
at
java.desktop/javax.swing.JComboBox.contentsChanged(JComboBox.java:1337)
at
java.desktop/javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:123)
at
java.desktop/javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:94)
at
java.desktop/javax.swing.DefaultComboBoxModel.addElement(DefaultComboBoxModel.java:132)
at java.desktop/javax.swing.JComboBox.addItem(JComboBox.java:716) at
stock.view.StockView.FillUpComboBox(StockView.java:103) at
stock.view.StockView.(StockView.java:41) at
main.view.MainMenu.stockMenuItemActionPerformed(MainMenu.java:290) at
main.view.MainMenu$FormListener.actionPerformed(MainMenu.java:240) at
java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at
java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at
java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at
java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at
java.desktop/javax.swing.AbstractButton.doClick(AbstractButton.java:369)
at
java.desktop/javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1020)
at
java.desktop/javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1064)
at
java.desktop/java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:297)
at
java.desktop/java.awt.Component.processMouseEvent(Component.java:6632)
at
java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6397)
at java.desktop/java.awt.Container.processEvent(Container.java:2263)
at
java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5008)
at
java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4840)
at
java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918)
at
java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547)
at
java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488)
at
java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2772)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4840)
at
java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721) at
java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715) at
java.base/java.security.AccessController.doPrivileged(Native Method)
at
java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at
java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745) at
java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743) at
java.base/java.security.AccessController.doPrivileged(Native Method)
at
java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at
java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at
java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at
java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at
java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at
java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at
java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at
java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.lang.IllegalArgumentException: object is not an
instance of declaring class at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566) at
org.hibernate.property.access.spi.GetterMethodImpl.get(GetterMethodImpl.java:42)
... 71 more
criteria.add(Restrictions.eq("category", cat).ignoreCase()) this is wrong. You can't compare relationship with a string. Here is one example coming straight from Hibernate documentation how it should be done:
List<Items> itemlist = sess.createCriteria(Items.class)
.createAlias("category",c)
.add( Restrictions.eq("c.name", cat))
.list();
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html
Another observation is that you are using inverse = false . IMO you want it to be inverse=true
Situation: I have 2 classes with relation oneToMany (Category oneToMany Product),
when creating Product like this:
Category c1 = new Category("Printer");
Category c2 = new Category("Scanner");
Category c3 = new Category("Phone");
Factory.getInstance().getCategoryDAO().addCategory(c1);//id1
Factory.getInstance().getCategoryDAO().addCategory(c2);//id2
Factory.getInstance().getCategoryDAO().addCategory(c3);//id3
//Product(catID, name, price)
Product p1 = new Product(2,"Panasonic", new BigDecimal("322.12"));
Product p2 = new Product(2,"Samsung", new BigDecimal("700.01"));
Product p3 = new Product(3,"NOKIA", new BigDecimal("12000.12"));
Factory.getInstance().getProductDAO().addProduct(p1);
Factory.getInstance().getProductDAO().addProduct(p2);
Factory.getInstance().getProductDAO().addProduct(p3);
I came into this exception:
Hibernate: insert into categories (CATEGORY_ID, CATEGORY_NAME) values (null, ?)
Hibernate: insert into categories (CATEGORY_ID, CATEGORY_NAME) values (null, ?)
Hibernate: insert into categories (CATEGORY_ID, CATEGORY_NAME) values (null, ?)
авг 22, 2016 12:06:21 AM org.hibernate.property.BasicPropertyAccessor$BasicGetter get
ERROR: HHH000122: IllegalArgumentException in class: model.Category, getter method of property: id
авг 22, 2016 12:06:36 AM org.hibernate.property.BasicPropertyAccessor$BasicGetter get
ERROR: HHH000122: IllegalArgumentException in class: model.Category, getter method of property: id
авг 22, 2016 12:06:37 AM org.hibernate.property.BasicPropertyAccessor$BasicGetter get
ERROR: HHH000122: IllegalArgumentException in class: model.Category, getter method of property: id
Class Category:
public class Category {
private Integer id;
private String name;
private Set<Product> products;
public Category(String name) {
this.name = name;
this.products = new HashSet<Product>(0);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Set<Product> getProducts() {
return products;
}
public void setProducts(Set<Product> products) {
this.products = products;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Class Product :
public class Product {
private Integer id;
private Integer catId;
private String name;
private BigDecimal price;
public Product(Integer catId, String name, BigDecimal price) {
this.catId = catId;
this.name = name;
this.price = price;
}
public Integer getId() {
return id;
}
public Integer getCatId() {
return catId;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public void setId(Integer id) {
this.id = id;
}
public void setCatId(Integer catId) {
this.catId = catId;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
And Category mapping:
<class name="model.Category" table="categories">
<id name="id" type="java.lang.Integer">
<column name="CATEGORY_ID"/>
<generator class="identity"/>
</id>
<property name="name" type="java.lang.String">
<column name="CATEGORY_NAME" not-null="true" unique="true"/>
</property>
<set name="products" table="products" lazy="false" inverse="true" fetch="select">
<key>
<column name="CAT_ID" not-null="true"/>
</key>
<one-to-many class="model.Product"/>
</set>
</class>
And Product mapping:
<hibernate-mapping>
<class name="model.Product" table="products">
<id name="id" type="java.lang.Integer">
<column name="PRODUCT_ID"/>
<generator class="identity"/>
</id>
<property name="name" type="java.lang.String">
<column name="PRODUCT_NAME"/>
</property>
<property name="price" type="java.math.BigDecimal" precision="2" scale="16" >
<column name="PRODUCT_PRICE"/>
</property>
<many-to-one name="catId" class="model.Category" fetch="select">
<column name="CAT_ID" not-null="true"/>
</many-to-one>
</class>
I found solution by myself.
I replaced private Integer catId; with private Category category; in Product class.
so I want to get data from my DB, but I always get this exception, saying that my getAll() method is returning null. I don't know what to do, can anyone help me?
Thanks
WarehouseHasProduct.java
public class WarehouseHasProduct implements java.io.Serializable {
private Integer id;
private Product product = new Product();
private Warehouse warehouse = new Warehouse();
private int stock;
public WarehouseHasProduct() {
}
public WarehouseHasProduct(Product product, Warehouse warehouse, int stock) {
this.product = product;
this.warehouse = warehouse;
this.stock = stock;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Product getProduct() {
return this.product;
}
public void setProduct(Product product) {
this.product = product;
}
public Warehouse getWarehouse() {
return this.warehouse;
}
public void setWarehouse(Warehouse warehouse) {
this.warehouse = warehouse;
}
public int getStock() {
return this.stock;
}
public void setStock(int stock) {
this.stock = stock;
}
}
Warehouse.java
public class Warehouse implements java.io.Serializable {
private Integer id;
private String description;
private Set<WarehouseHasProduct> warehouseHasProducts = new HashSet<WarehouseHasProduct>(
0);
public Warehouse() {
}
public Warehouse(String description) {
this.description = description;
}
public Warehouse(String description,
Set<WarehouseHasProduct> warehouseHasProducts) {
this.description = description;
this.warehouseHasProducts = warehouseHasProducts;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<WarehouseHasProduct> getWarehouseHasProducts() {
return this.warehouseHasProducts;
}
public void setWarehouseHasProducts(
Set<WarehouseHasProduct> warehouseHasProducts) {
this.warehouseHasProducts = warehouseHasProducts;
}
}
Product.java
public class Product implements java.io.Serializable {
private Integer id;
private ProductType productType;
private String productName;
private String description;
private double price;
private Set<WarehouseHasProduct> warehouseHasProducts = new HashSet<WarehouseHasProduct>(
0);
private Set<Order> orders = new HashSet<Order>(0);
public Product() {
}
public Product(ProductType productType, String productName,
String description, double price) {
this.productType = productType;
this.productName = productName;
this.description = description;
this.price = price;
}
public Product(ProductType productType, String productName,
String description, double price,
Set<WarehouseHasProduct> warehouseHasProducts, Set<Order> orders) {
this.productType = productType;
this.productName = productName;
this.description = description;
this.price = price;
this.warehouseHasProducts = warehouseHasProducts;
this.orders = orders;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public ProductType getProductType() {
return this.productType;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public Set<WarehouseHasProduct> getWarehouseHasProducts() {
return this.warehouseHasProducts;
}
public void setWarehouseHasProducts(
Set<WarehouseHasProduct> warehouseHasProducts) {
this.warehouseHasProducts = warehouseHasProducts;
}
public Set<Order> getOrders() {
return this.orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
WarehouseHasProduct.hbm.xml
<hibernate-mapping>
<class name="com.app.hibernate.data.WarehouseHasProduct" table="warehouse_has_product" catalog="test">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<many-to-one name="product" class="com.app.hibernate.data.Product" fetch="select">
<column name="product_id" not-null="true" />
</many-to-one>
<many-to-one name="warehouse" class="com.app.hibernate.data.Warehouse" fetch="select">
<column name="warehouse_id" not-null="true" />
</many-to-one>
<property name="stock" type="int">
<column name="stock" not-null="true" />
</property>
</class>
</hibernate-mapping>
Warehouse.hbm.xml
<hibernate-mapping>
<class name="com.app.hibernate.data.Warehouse" table="warehouse" catalog="test">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="description" type="string">
<column name="description" length="100" not-null="true" />
</property>
<set name="warehouseHasProducts" table="warehouse_has_product" inverse="true" lazy="true" fetch="select">
<key>
<column name="warehouse_id" not-null="true" />
</key>
<one-to-many class="com.app.hibernate.data.WarehouseHasProduct" />
</set>
</class>
</hibernate-mapping>
Product.hbm.xml
<hibernate-mapping>
<class name="com.app.hibernate.data.Product" table="product" catalog="test">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<many-to-one name="productType" class="com.app.hibernate.data.ProductType" fetch="select">
<column name="type_id" not-null="true" />
</many-to-one>
<property name="productName" type="string">
<column name="productName" length="100" not-null="true" />
</property>
<property name="description" type="string">
<column name="description" length="100" not-null="true" />
</property>
<property name="price" type="double">
<column name="price" precision="22" scale="0" not-null="true" />
</property>
<set name="warehouseHasProducts" table="warehouse_has_product" inverse="true" lazy="true" fetch="select">
<key>
<column name="product_id" not-null="true" />
</key>
<one-to-many class="com.app.hibernate.data.WarehouseHasProduct" />
</set>
<set name="orders" table="order_has_product" inverse="false" lazy="true" fetch="select">
<key>
<column name="product_id" not-null="true" />
</key>
<many-to-many entity-name="com.app.hibernate.data.Order">
<column name="order_id" not-null="true" />
</many-to-many>
</set>
</class>
</hibernate-mapping>
WarehouseHasProductService.java
#Component
public class WarehouseHasProductService {
#Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Transactional
public void register(WarehouseHasProduct whp){
// Acquire session
Session session = sessionFactory.getCurrentSession();
// Save employee, saving behavior get done in a transactional manner
session.save(whp);
}
#SuppressWarnings("unchecked")
#Transactional
public List<WarehouseHasProduct> getAll(){
// Acquire session
Session session = sessionFactory.getCurrentSession();
List list = session.createQuery("from com.app.hibernate.data.WarehouseHasProduct").list();
return list;
}
}
RegisterWarehouseHasProduct.java
#ManagedBean
#SessionScoped
public class RegisterWarehouseHasProduct{
#ManagedProperty("#{whpService}")
private WarehouseHasProductService whpService;
private WarehouseHasProduct whp = new WarehouseHasProduct();
public WarehouseHasProductService getWhpService() {
return whpService;
}
public void setWhpService(WarehouseHasProductService whpService) {
this.whpService = whpService;
}
public WarehouseHasProduct getWhp() {
return whp;
}
public void setWhp(WarehouseHasProduct whp) {
this.whp = whp;
}
public String register() {
// Calling Business Service
whpService.register(whp);
// Add message
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("The Product "+whp.getId()+" Is Registered Successfully"));
return "";
}
public List<WarehouseHasProduct> getAll(){
return whpService.getAll();
}
}
Home.xhtml
<p:dataTable var="p" value="#{registerProduct.getAllProducts()}">
<f:facet name="header">
Products List
</f:facet>
<p:column headerText="Code">
<h:outputText value="#{p.id}" />
</p:column>
<p:column headerText="Name">
<h:outputText value="#{p.productName}" />
</p:column>
<p:column headerText="Description">
<h:outputText value="#{p.description}" />
</p:column>
<p:column headerText="Type">
<h:outputText value="#{p.productType.description}" />
</p:column>
<p:column headerText="Price">
<h:outputText value="#{p.price}" />
</p:column>
</p:dataTable>
I really appreciate an answer. Thank you!
This is My LOGIN1.java class
import java.io.Serializable;
public class LOGIN1 implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String Email;
private String Password;
private Registration registration;
public Registration getRegistration() {
return registration;
}
public void setRegistration(Registration registration) {
this.registration = registration;
}
public int getId()
{
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
}
This Is My Registration.java
import java.io.Serializable;
public class Registration implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String contact;
private String Name;
private String amount;
private LOGIN1 login1;
public LOGIN1 getLogin1() {
return login1;
}
public void setLogin1(LOGIN1 login1) {
this.login1 = login1;
}
public int getId()
{
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
This Is My LOGIN1.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="LOGIN1" table="LOGIN1">
<id name="id" column="id" type="integer">
<generator class="increment"/>
</id>
<property name="Email" column="EMAIL" type="string"></property>
<property name="Password" column="Password" type="string"></property>
<one-to-one name="registration" class="Registration" cascade="save-update"></one-to-one>
</class>
</hibernate-mapping>
this is my Registration.hbm.xml
<id name="id" column="id" type="integer">
<generator class="foreign">
<param name="property">rg</param>
</generator>
</id>
<one-to-one name="login1" class="LOGIN1" constrained="true"></one-to-one>
<property name="Name" column="Name" type="string"></property>
<property name="contact" column="contct" type="string"></property>
<property name="amount" column="iamt" type="string"></property>
</class>
</hibernate-mapping>
This is my hibernate.cfg
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;databaseName=HiberNate</property>
<property name="hibernate.connection.username">aaa</property>
<property name="hibernate.connection.password">aaa</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="show_sql">true</property>
<mapping resource="LOGIN1.hbm.xml"></mapping>
<mapping resource="Registration.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
This is My Hiberservlets
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
#WebServlet("/HiberServlet")
public class HiberServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HiberServlet() {
}
#SuppressWarnings("deprecation")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
out.print("Hello");
String a,b,c,d,e;
a=request.getParameter("cnm");
b=request.getParameter("cntno");
c=request.getParameter("amt");
d=request.getParameter("eml");
e=request.getParameter("pwd");
Session s=HibernateUtil.openSession();
Transaction tx = s.beginTransaction();
try {
LOGIN1 ln=new LOGIN1();
ln.setEmail(d);
ln.setPassword(e);
s.save(ln);
Criteria cr=s.createCriteria(LOGIN1.class);
cr.add(Restrictions.eq("Email",d));
cr.add(Restrictions.eq("Password",e));
int i=ln.getId();
Registration rg=new Registration();
rg.setId(i);
rg.setName(a);
rg.setContact(b);
rg.setAmount(c);
s.save(rg);
tx.commit();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
if(s!=null)
{
s.flush();
s.close();
}
}
catch(HibernateException e)
{
System.out.print(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
i am trying This but its Give error like
java.lang.NullPointerException
org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:650)
org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:4736)
org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:96)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:118)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
HiberServlet.doGet(HiberServlet.java:77)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
And i am Using eclipse.what is problem in this code.
This
org.hibernate.PropertyNotFoundException: field [LOGIN1] not found on Registration
indicates, that your mapping does not match your class. There is probably no LOGIN1 property in the class. If it exists at all it is probably called login1 in lower case letters
Good evening all,
I am trying to update a field in my page and keep getting an exception thrown.
I have a main object "car" that has a foreign key to "Model"
when I built my page I created a select box to list all the models. So now when I choose a model and submit the form I get the exception thrown below. All of the fields that are in the Car table update fine as long as I do not include the model field. Once I try to include the model field, code breaks on submitting.
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/sellcar.jsp at line 28
25: <c:forEach items="${cars}" var="car">
26: <option
27: value='<c:out value="${car.model.modId}"/>'
28: <c:if test="${car.model.model == status.value.model}">SELECTED</c:if>>
29: <c:out value="${car.model.model}" />
30: </option>
31: </c:forEach>
**Stacktrace:**
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:521)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:111)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1045)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:810)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:723)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:360)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
javax.el.PropertyNotFoundException: Property 'model' not found on type java.lang.String
javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:214)
javax.el.BeanELResolver$BeanProperties.access$400(BeanELResolver.java:191)
javax.el.BeanELResolver.property(BeanELResolver.java:300)
javax.el.BeanELResolver.getValue(BeanELResolver.java:81)
javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
org.apache.el.parser.AstValue.getValue(AstValue.java:123)
org.apache.el.parser.AstEqual.getValue(AstEqual.java:38)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:938)
org.apache.jsp.WEB_002dINF.jsp.sellcar_jsp._jspx_meth_c_005fif_005f0(sellcar_jsp.java:847)
org.apache.jsp.WEB_002dINF.jsp.sellcar_jsp._jspx_meth_c_005fforEach_005f0(sellcar_jsp.java:791)
org.apache.jsp.WEB_002dINF.jsp.sellcar_jsp._jspService(sellcar_jsp.java:107)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:111)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1045)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:810)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:723)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:360)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
</b>
My Models:
Car:
package com.usedcarsearch.domain;
// Generated Feb 19, 2013 10:31:37 PM by Hibernate Tools 3.4.0.CR1
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
/**
* Car generated by hbm2java
*/
public class Car implements java.io.Serializable {
private Integer carId;
private Make make;
private State state;
private Model model;
private City city;
private String vin;
private int year;
private String image;
private String engine;
private String trans;
private String mileage;
private BigDecimal price;
private String color;
private BigDecimal hwyMpg;
private BigDecimal cityMpg;
private String address;
private String accessories;
private String comments;
private Set buyers = new HashSet(0);
private Set ownerships = new HashSet(0);
private Set carSearchLists = new HashSet(0);
public Car() {
}
public Car(Make make, State state, Model model, City city, int year,
String engine, String trans, String mileage) {
this.make = make;
this.state = state;
this.model = model;
this.city = city;
this.year = year;
this.engine = engine;
this.trans = trans;
this.mileage = mileage;
}
public Car(Make make, State state, Model model, City city, String vin,
int year, String image, String engine, String trans,
String mileage, BigDecimal price, String color, BigDecimal hwyMpg,
BigDecimal cityMpg, String address, String accessories,
String comments, Set buyers, Set ownerships, Set carSearchLists) {
this.make = make;
this.state = state;
this.model = model;
this.city = city;
this.vin = vin;
this.year = year;
this.image = image;
this.engine = engine;
this.trans = trans;
this.mileage = mileage;
this.price = price;
this.color = color;
this.hwyMpg = hwyMpg;
this.cityMpg = cityMpg;
this.address = address;
this.accessories = accessories;
this.comments = comments;
this.buyers = buyers;
this.ownerships = ownerships;
this.carSearchLists = carSearchLists;
}
public Integer getCarId() {
return this.carId;
}
public void setCarId(Integer carId) {
this.carId = carId;
}
public Make getMake() {
return this.make;
}
public void setMake(Make make) {
this.make = make;
}
public State getState() {
return this.state;
}
public void setState(State state) {
this.state = state;
}
public Model getModel() {
return this.model;
}
public void setModel(Model model) {
this.model = model;
}
public City getCity() {
return this.city;
}
public void setCity(City city) {
this.city = city;
}
public String getVin() {
return this.vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public int getYear() {
return this.year;
}
public void setYear(int year) {
this.year = year;
}
public String getImage() {
return this.image;
}
public void setImage(String image) {
this.image = image;
}
public String getEngine() {
return this.engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
public String getTrans() {
return this.trans;
}
public void setTrans(String trans) {
this.trans = trans;
}
public String getMileage() {
return this.mileage;
}
public void setMileage(String mileage) {
this.mileage = mileage;
}
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public BigDecimal getHwyMpg() {
return this.hwyMpg;
}
public void setHwyMpg(BigDecimal hwyMpg) {
this.hwyMpg = hwyMpg;
}
public BigDecimal getCityMpg() {
return this.cityMpg;
}
public void setCityMpg(BigDecimal cityMpg) {
this.cityMpg = cityMpg;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAccessories() {
return this.accessories;
}
public void setAccessories(String accessories) {
this.accessories = accessories;
}
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Set getBuyers() {
return this.buyers;
}
public void setBuyers(Set buyers) {
this.buyers = buyers;
}
public Set getOwnerships() {
return this.ownerships;
}
public void setOwnerships(Set ownerships) {
this.ownerships = ownerships;
}
public Set getCarSearchLists() {
return this.carSearchLists;
}
public void setCarSearchLists(Set carSearchLists) {
this.carSearchLists = carSearchLists;
}
}
Model:
package com.usedcarsearch.domain;
// Generated Feb 19, 2013 10:31:37 PM by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
/**
* Model generated by hbm2java
*/
public class Model implements java.io.Serializable {
private Integer modId;
private String model;
private Set cars = new HashSet(0);
public Model() {
}
public Model(String model) {
this.model = model;
}
public Model(String model, Set cars) {
this.model = model;
this.cars = cars;
}
public Integer getModId() {
return this.modId;
}
public void setModId(Integer modId) {
this.modId = modId;
}
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
public Set getCars() {
return this.cars;
}
public void setCars(Set cars) {
this.cars = cars;
}
}
Car.hbm
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/
Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net
/hibernate-mapping-3.0.dtd">
<!-- Generated Feb 19, 2013 10:31:37 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping default-lazy="false">
<class name="com.usedcarsearch.domain.Car" table="Car">
<id name="carId" type="java.lang.Integer">
<column name="carId"/>
<generator class="identity"/>
</id>
<many-to-one class="com.usedcarsearch.domain.Make"
fetch="select" name="make">
<column name="fkMakeId" not-null="true"/>
</many-to-one>
<many-to-one class="com.usedcarsearch.domain.State"
fetch="select" name="state">
<column name="fkStateId" not-null="true"/>
</many-to-one>
<many-to-one class="com.usedcarsearch.domain.Model"
fetch="select" name="model">
<column name="fkModelId" not-null="true"/>
</many-to-one>
<many-to-one class="com.usedcarsearch.domain.City"
fetch="select" name="city">
<column name="fkZipCode" not-null="true"/>
</many-to-one>
<property generated="never" lazy="false" name="vin" type="string">
<column length="25" name="vin"/>
</property>
<property generated="never" lazy="false" name="year" type="int">
<column name="year" not-null="true"/>
</property>
<property generated="never" lazy="false" name="image" type="string">
<column length="100" name="image"/>
</property>
<property generated="never" lazy="false" name="engine" type="string">
<column length="45" name="engine" not-null="true"/>
</property>
<property generated="never" lazy="false" name="trans" type="string">
<column length="45" name="trans" not-null="true"/>
</property>
<property generated="never" lazy="false" name="mileage" type="string">
<column length="20" name="mileage" not-null="true"/>
</property>
<property generated="never" lazy="false" name="price" type="big_decimal">
<column name="price" precision="11"/>
</property>
<property generated="never" lazy="false" name="color" type="string">
<column length="20" name="color"/>
</property>
<property generated="never" lazy="false" name="hwyMpg" type="big_decimal">
<column name="hwyMpg" precision="3" scale="1"/>
</property>
<property generated="never" lazy="false" name="cityMpg" type="big_decimal">
<column name="cityMpg" precision="3" scale="1"/>
</property>
<property generated="never" lazy="false" name="address" type="string">
<column length="50" name="address"/>
</property>
<property generated="never" lazy="false" name="accessories" type="string">
<column length="100" name="accessories"/>
</property>
<property generated="never" lazy="false" name="comments" type="string">
<column length="100" name="comments"/>
</property>
<set fetch="select" inverse="true" lazy="false" name="buyers"
sort="unsorted" table="Buyer">
<key>
<column name="fkCarId" not-null="true"/>
</key>
<one-to-many class="com.usedcarsearch.domain.Buyer"/>
</set>
<set fetch="select" inverse="true" lazy="false" name="ownerships"
sort="unsorted" table="Ownership">
<key>
<column name="fkCarId" not-null="true"/>
</key>
<one-to-many class="com.usedcarsearch.domain.Ownership"/>
</set>
<set fetch="select" inverse="true" lazy="false" name="carSearchLists"
sort="unsorted" table="Car_Search_List">
<key>
<column name="fkCarId" not-null="true"/>
</key>
<one-to-many class="com.usedcarsearch.domain.CarSearchList"/>
</set>
</class>
</hibernate-mapping>
JSP code: (I did not include all but only what is necessary)
<spring:bind path="command.model">
<select name='<c:out value="${status.expression}"/>'>
<option value=""></option>
<c:forEach items="${cars}" var="car">
<option value='<c:out value="${car.model.modId}"/>'
<c:if test="${car.model.model == status.value.model}">SELECTED</c:if>>
<c:out value="${car.model.model}" />
</option>
</c:forEach>
</select>
I got it fixed. It seems I had to add the foreign key property in the Car.hbm along with adding the foreign keys variables, getters and setters to Car.
Based on the error message you might want to change line 28 from:
status.value.model
to
status.value