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
Related
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
I want to fetch data from two tables using inner joins in HQL in hibernate but its not working don't know why??
The Pojo classes and their mapping files are given:
public class Org implements java.io.Serializable {
private String quarter;
private Orgtype orgtype;
private String parent;
private Set regions = new HashSet(0);
private Set cfgOrgObjects = new HashSet(0);
public Org() {
}
public Org(String quarter, Orgtype orgtype, String parent) {
this.quarter = quarter;
this.orgtype = orgtype;
this.parent = parent;
}
public Org(String quarter, Orgtype orgtype, String parent, Set regions, Set cfgOrgObjects) {
this.quarter = quarter;
this.orgtype = orgtype;
this.parent = parent;
this.regions = regions;
this.cfgOrgObjects = cfgOrgObjects;
}
public String getQuarter() {
return this.quarter;
}
public void setQuarter(String quarter) {
this.quarter = quarter;
}
public Orgtype getOrgtype() {
return this.orgtype;
}
public void setOrgtype(Orgtype orgtype) {
this.orgtype = orgtype;
}
public String getParent() {
return this.parent;
}
public void setParent(String parent) {
this.parent = parent;
}
}
Orgtype pojo class:
<?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 4, 2015 2:30:35 AM by Hibernate Tools 3.6.0 -->
<hibernate-mapping>
<class name="pojo.Org" table="ORG" schema="myschema">
<id name="quarter" type="string">
<column name="QUARTER" length="600" />
<generator class="assigned" />
</id>
<many-to-one name="orgtype" class="pojo.Orgtype" fetch="select">
<column name="TYPE" length="30" not-null="true" />
</many-to-one>
<property name="parent" type="string">
<column name="PARENT" length="30" not-null="true" />
</property>
</class>
</hibernate-mapping>
Mapping file for Orgtype table
public class Orgtype implements java.io.Serializable {
private String type;
private String description;
// private Set orgs = new HashSet(0);
private Set<Org> orgs = new HashSet<Org>();
public Orgtype() {
}
public Orgtype(String type, String description) {
this.type = type;
this.description = description;
}
public Orgtype(String type, String description, Set orgs) {
this.type = type;
this.description = description;
this.orgs = orgs;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Set getOrgs() {
return this.orgs;
}
public void setOrgs(Set orgs) {
this.orgs = orgs;
}
}
Orgtype mapping file:
<?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 4, 2015 2:30:35 AM by Hibernate Tools 3.6.0 -->
<hibernate-mapping>
<class name="pojo.Orgtype" table="ORGTYPE" schema="myschema">
<id name="type" type="string">
<column name="TYPE" length="30" />
<generator class="assigned" />
</id>
<property name="description" type="string">
<column name="DESCRIPTION" length="600" not-null="true" />
</property>
<set name="orgs" table="ORG" inverse="true" lazy="true" fetch="select">
<key>
<column name="TYPE" length="30" not-null="true" />
</key>
<one-to-many class="pojo.Org" />
</set>
</class>
</hibernate-mapping>
and query i am using is :
Query q = sess.createQuery("SELECT og.quarter,og.parent,ogt.type,ogt.description FROM Org og INNER JOIN Orgtype ogt ogt.type = og.Orgtype" );
Error:
ERROR: line 1:94: unexpected token: ogt
ERROR: line 1:94: unexpected token: ogt
line 1:94: unexpected token: ogt
at org.hibernate.hql.internal.antlr.HqlBaseParser.fromJoin(HqlBaseParser.java:1694)
at org.hibernate.hql.internal.antlr.HqlBaseParser.fromClause(HqlBaseParser.java:1349)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectFrom(HqlBaseParser.java:1055)
at org.hibernate.hql.internal.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:701)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectStatement(HqlBaseParser.java:294)
at org.hibernate.hql.internal.antlr.HqlBaseParser.statement(HqlBaseParser.java:157)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:268)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:138)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1778)
at managedBean.ManagedBean.insertf(ManagedBean.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.el.parser.AstValue.invoke(AstValue.java:275)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:818)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Try this
Query q = sess.createQuery("SELECT og.quarter,og.parent,ogt.type,ogt.description FROM Org og INNER JOIN og.orgtype ogt");
Orgtype is like a property of the class pojo.Org you should mention that in the query somehow.
Try this:
Query q = sess.createQuery("SELECT og.quarter,og.parent,ogt.type,ogt.description FROM Org og INNER JOIN og.orgtype as ogt where ogt.type = og.orgtype" );
try this
code
Query q = sess.createQuery("SELECT og.quarter,og.parent,ogt.type,ogt.description FROM Org og,Orgtype ogt where ogt.type = og.orgtype");
As I run my main class (Runner) program I get the following exception :
org.hibernate.id.IdentifierGenerationException: attempted to assign id
from null one-to-one property: country
I don't know the reason, why am I getting this exception.
The mapping xml :
<hibernate-mapping>
<class name="pojo.Country" table="country">
<id name="countryID" column="c_id">
<generator class="increment" />
</id>
<property name="countryName" column="c_name" />
<one-to-one class="pojo.PM" name="pm" cascade="all" />
</class>
<class name="pojo.PM" table="pm">
<id name="countryID" column="c_id">
<generator class="foreign">
<param name="property">country</param>
</generator>
</id>
<property name="pmName" column="pm_name" />
<one-to-one class="pojo.Country" name="country" constrained="true" />
</class>
</hibernate-mapping>
POJO Classes :
Country
public class Country {
private int countryID;
private String countryName;
private PM pm;
public PM getPm() {
return pm;
}
public void setPm(PM pm) {
this.pm = pm;
}
public int getCountryID() {
return countryID;
}
public void setCountryID(int countryID) {
this.countryID = countryID;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
PM
public class PM {
private int countryID;
private String pmName;
private Country country;
public int getCountryID() {
return countryID;
}
public void setCountryID(int countryID) {
this.countryID = countryID;
}
public String getPmName() {
return pmName;
}
public void setPmName(String pmName) {
this.pmName = pmName;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
}
and this is the class that tries to commit the transaction :
public class Runner {
public static void main(String args[]) {System.out.println("dfdf");
Configuration config = new Configuration().configure();
SessionFactory sessFact = config.buildSessionFactory();
Session session = sessFact.openSession();
Transaction trans = session.beginTransaction();
Country c = new Country();
PM pm = new PM();
pm.setPmName("Manmohan Singh");
c.setCountryName("India");
c.setPm(pm);
session.save(c);
trans.commit();
}
}
SQL that created table :
CREATE TABLE country(c_id INTEGER,c_name TEXT,PRIMARY KEY(c_id));
CREATE TABLE pm(c_id INTEGER,pm_name TEXT);
The problem is the country variable. You should initialize all the attirbutes before trying to do some transactions.
EDIT: In your Hibernate file, you want to generate the PM ID from the ID of the country property. However, this property has never been initialized.
<class name="pojo.PM" table="pm">
<id name="countryID" column="c_id">
<generator class="foreign">
<param name="property">country</param>
</generator>
</id>
<property name="pmName" column="pm_name" />
<one-to-one class="pojo.Country" name="country" constrained="true" />
</class>
So, add pm.setCountry(c); to your code.
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
This post is an continuation of this post
I have DlUser Class each object of this class may have DLFaceBook class and each object of DlFaceBook can have Friends which are mapped as myFriends.
I'm trying to map relation of the same class as many to many relation using bag mapping,composite primary key and static inner class. my code is the following:
public class DlUser{
public DlUser(){}
Long Id;
String FirstName;
String LastName;
....
DlFaceBook fbuser;
//// all requred
getters and setters...
}
The Facebook user class looks like this as you can see I have the collection of objectes with the class MyFriends:
public class DlFaceBook {
private long dlpId;
private String FbId;
private Collection<MyFriends> Friends;
public DlFaceBook(){}
public void setFbId(String FbId)
{
this.FbId = FbId;
}
public void setFriends(Collection<MyFriends> friends)
{
this.Friends = friends;
}
public Collection<MyFriends> getFriends()
{
return this.Friends;
}
public void setdlpId(long id)
{
this.dlpId = id;
}
public long getdlpId()
{
return this.dlpId;
}
public String getFbId()
{
return this.FbId;
}
}
MyFriends class looks like this:
public class MyFriends {
private MyFriendsId myFriendId;
private DlFaceBook me;
private DlFaceBook myFriend;
public MyFriendsId getmyFriendId(){
return this.myFriendId;
}
public void setmyFriendId(MyFriendsId fid){
this.myFriendId = fid;
}
public void setme(DlFaceBook me){
this.me = me;
}
public void setmyFriend(DlFaceBook friend){
this.myFriend = friend;
}
public DlFaceBook getme(){
return this.me ;
}
public DlFaceBook getmyFriend(){
return this.myFriend ;
}
public MyFriends(DlFaceBook me, DlFaceBook user){
this.me = me ;
this.myFriend = user;
this.myFriendId = new MyFriendsId(me.getdlpId(),user.getdlpId());
}
public static class MyFriendsId implements Serializable {
private long meId;
private long myFrId;
// getter's and setter's
public MyFriendsId() {}
public MyFriendsId(long meId, long myFriendId) {
this.meId = meId;
this.myFrId = myFriendId;
}
// getter's and setter's
public long getmeId(){
return this.meId;
}
public void setmeId(Integer id){
this.meId = id;
}
public long getmyFrId(){
return this.myFrId;
}
public void setmyFrId(long id){
this.myFrId = id;
}
}
}
Now the Mapping:
DlUser.hbm.xml is the following and it's simple:
<hibernate-mapping>
<class name="DlUser" table="Users">
<id name="Id" column="id" >
<generator class="sequence">
<param name="sequence">userseq</param>
</generator>
</id>
<property name="firstName">
<column name="FirstName" />
</property>
<property name="lastName">
<column name="LastName"/>
</property>
<many-to-one
name="FaceBook"
class="DlFaceBook"
cascade="all"
column="dlpId"
unique="true"
/>
</class>
</hibernate-mapping>
DlFacebook.hbm.xml looks like this:
<hibernate-mapping>
<class name="DlFaceBook" table="dlfacebook">
<id name="dlpId" type="java.lang.Long" column="dlpId">
<generator class="increment" />
</id>
<property name="fbId">
<column name="fbId" />
</property>
<bag name="Friends">
<key column="me_Id" />
<one-to-many class="MyFriends"/>
</bag>
</class>
</hibernate-mapping>
Then MyFriends.hbm.xml looks like this:
<hibernate-mapping>
<class name="MyFriends">
<composite-id name="myFriendId" class="MyFriends$MyFriendsId">
<key-property name="meId"/>
<key-property name="myFrId"/>
</composite-id>
<many-to-one name="me" class="DlFaceBook" insert="false" update="false"/>
<many-to-one name="myFriend" class="DlFaceBook" insert="false" update="false"/>
</class>
</hibernate-mapping>
When I'm executing my query I got the following error:
Hibernate: insert into dlfacebook (fbId, dlpId) values (?, ?)
Hibernate: insert into Users (FirstName, LastName, email, twitter, birthday, dlpId, id) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: update MyFriends set me_Id=? where meId=? and myFrId=?
Hibernate: update MyFriends set me_Id=? where meId=? and myFrId=?
Oct 2, 2010 1:21:18 PM org.hibernate.jdbc.BatchingBatcher doExecuteBatch
SEVERE: Exception executing batch:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:183)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
at Test.main(Test.java:54)
Oct 2, 2010 1:21:18 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:183)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
at Test.main(Test.java:54)
Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
I see that this error happens when we trying to update not existing row, but how can I make this code work?
Just Facebook and MyFriends
Facebook Notice add convenience method and MutableLong (later, i tell you why to use MutableLong)
public class Facebook {
private MutableLong id = new MutableLong();
public Long getId() { return id.longValue(); }
public void setId(Long id) { this.id.setValue(id); }
public MutableLong getIdAsMutableLong() {
return id;
}
private Collection<MyFriends> myFriends = new ArrayList<MyFriends>();
public Collection<MyFriends> getMyFriends() { return myFriends; }
public void setMyFriends(Collection<MyFriends> myFriends) { this.myFriends = myFriends; }
/**
* add convenience method
*/
public void addFriend(Facebook myFriendFacebook) {
myFriends.add(new MyFriends(this, myFriendFacebook));
}
}
MyFriends
public class MyFriends {
private MyFriendsId myFriendId;
public MyFriendsId getmyFriendId(){ return this.myFriendId; }
public void setmyFriendId(MyFriendsId myFriendId){ this.myFriendId = myFriendId; }
private Facebook me;
public Facebook getme() { return this.me; }
public void setme(Facebook me){ this.me = me; }
private Facebook myFriend;
public Facebook getmyFriend() { return this.myFriend; }
public void setmyFriend(Facebook friend) { this.myFriend = friend; }
public MyFriends() {}
public MyFriends(Facebook meFacebook, Facebook myFriendFacebook){
this.me = meFacebook ;
this.myFriend = myFriendFacebook;
this.myFriendId = new MyFriendsId(meFacebook.getIdAsMutableLong(), myFriendFacebook.getIdAsMutableLong());
}
public static class MyFriendsId implements Serializable {
private MutableLong meId = new MutableLong();
public Long getMeId() { return this.meId.longValue(); }
public void setMeId(Long id) { this.meId.setValue(id); }
private MutableLong myFriendId = new MutableLong();
public Long getMyFriendId(){ return this.myFriendId.longValue(); }
public void setMyFriendId(Long id) { this.myFriendId.setValue(id); }
public MyFriendsId() {}
public MyFriendsId(MutableLong meId, MutableLong myFriendId) {
this.meId = meId;
this.myFriendId = myFriendId;
}
#Override
public boolean equals(Object o) {
if (!(o instanceof MyFriendsId))
return false;
MyFriendsId other = (MyFriendsId) o;
return new EqualsBuilder()
.append(getMeId(), other.getMeId())
.append(getMyFriendId(), getMyFriendId())
.isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder()
.append(getMeId())
.append(getMyFriendId())
.hashCode();
}
}
}
Mapping
<hibernate-mapping package="br.com._3845772.model.domain">
<class name="User">
<id name="id">
<generator class="native"/>
</id>
<many-to-one cascade="all" class="Facebook" name="facebook"/>
</class>
<class name="Facebook">
<id name="id">
<generator class="native"/>
</id>
<bag cascade="all" name="myFriends">
<key column="ME_FACEBOOK_ID" update="false"/>
<one-to-many class="MyFriends"/>
</bag>
</class>
<class name="MyFriends">
<composite-id class="MyFriends$MyFriendsId" name="myFriendId">
<key-property column="ME_FACEBOOK_ID" name="meId"/>
<key-property column="MY_FRIEND_FACEBOOK_ID" name="myFriendId"/>
</composite-id>
<many-to-one class="Facebook" column="ME_FACEBOOK_ID" insert="false" name="me" update="false"/>
<many-to-one class="Facebook" column="MY_FRIEND_FACEBOOK_ID" insert="false" name="myFriend" update="false"/>
</class>
</hibernate-mapping>
And this sample
Facebook meFacebook = new Facebook();
Facebook myFriendFacebook = new Facebook();
meFacebook.addFriend(myFriendFacebook);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(myFriendFacebook);
session.save(meFacebook);
session.getTransaction().commit();
session.close();
Which gives me
Hibernate: insert into Facebook values ( )
Hibernate: insert into Facebook values ( )
Hibernate: select myfriends_.ME_FACEBOOK_ID, myfriends_.MY_FRIEND_FACEBOOK_ID from MyFriends myfriends_ where myfriends_.ME_FACEBOOK_ID=? and myfriends_.MY_FRIEND_FACEBOOK_ID=?
Hibernate: insert into MyFriends (ME_FACEBOOK_ID, MY_FRIEND_FACEBOOK_ID) values (?, ?)
A couple of notes
Hibernate does not support automatic generation of composite primary key. You must set up its value before saving
Your database must support the target generator strategy (If you does not know which generator strategy your database support, prefer to use a native strategy)
Each entity must supply a no-arg constructor
Now why MutableLong (encapsulated by a Long property) instead of Long ?
Number and its subclasses (Long is a Number) are immutable. So if you want Facebook.id (configured by database) and its counterpart MyFriend$MyFriendId.meId share the same value, you must use MutableLong. When the database set up Facebook.id, MyFriend$MyFriendId.meId automatically get its newest value. But it just occurs if you use a MutableLong.