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");
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
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 am using this simple Hibernate Mapping xml to create an entity
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<hibernate-mapping>
<class entity-name="FirstTestType">
<property column="createdOn" name="java.sql.Timestamp" type="java.sql.Timestamp"/>
<id column="id" name="id" type="java.lang.Long">
<generator class="identity"/>
</id>
<property column="modifiedOn" name="java.sql.Timestamp" type="java.sql.Timestamp"/>
<property column="testString" length="100" name="java.lang.String" type="java.lang.String"/>
<property column="testInt" name="int" type="int"/>
<property column="testBoolean" name="boolean" type="boolean"/>
<property column="testLong" name="long" type="long"/>
</class>
</hibernate-mapping>
Though my schema is effectively created when I use SchemaExport
final SchemaExport export = new SchemaExport(getHibernateConfigurationForSchema());
export.create(true, true);
When I try to create a sessionfactory I am getting this exception
org.hibernate.MappingException: Duplicate property mapping of java.sql.Timestamp found in FirstTestType
at org.appops.entityStore.hibernate.session.HibernateSessionFactoryProvider.setupSchemaSessionFactory(HibernateSessionFactoryProvider.java:78)
at org.appops.entityStore.hibernate.session.HibernateSessionFactoryProviderTest.testSessionCreation(HibernateSessionFactoryProviderTest.java:110)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:606)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.MappingException: Duplicate property mapping of java.sql.Timestamp found in FirstTestType
at org.hibernate.mapping.PersistentClass.checkPropertyDuplication(PersistentClass.java:483)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:473)
at org.hibernate.mapping.RootClass.validate(RootClass.java:235)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1362)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1865)
at org.appops.entityStore.hibernate.session.HibernateSessionFactoryProvider.setupSchemaSessionFactory(HibernateSessionFactoryProvider.java:74)
... 11 more
Can you help me figure out whats wrong with the Mapping xml ?
Change names in properties;
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<hibernate-mapping>
<class entity-name="FirstTestType">
<property column="createdOn" name="nameCreatedOn" type="java.sql.Timestamp"/>
<id column="id" name="id" type="java.lang.Long">
<generator class="identity"/>
</id>
<property column="modifiedOn" name="nameModifiedOn" type="java.sql.Timestamp"/>
<property column="testString" length="100" name="nameTestString" type="java.lang.String"/>
<property column="testInt" name="nameTestInt" type="int"/>
<property column="testBoolean" name="nameTestBoolean" type="boolean"/>
<property column="testLong" name="nameTestLong" type="long"/>
</class>
</hibernate-mapping>
Your class look like;
package basari.util;
public class FirstTestType {
private Date nameCreatedOn;
private int nameId;
private String nameModifiedOn;
private String nameTestString;
private int nameTestInt;
private Boolean nameTestBoolean;
private Long nameTestLong;
public FirstTestType(){
}
public Date getNameCreatedOn() {
return nameCreatedOn;
}
public void setNameCreatedOn(Date nameCreatedOn) {
this.nameCreatedOn = nameCreatedOn;
}
public int getNameId() {
return nameId;
}
public void setNameId(int nameId) {
this.nameId = nameId;
}
public String getNameModifiedOn() {
return nameModifiedOn;
}
public void setNameModifiedOn(String nameModifiedOn) {
this.nameModifiedOn = nameModifiedOn;
}
public String getNameTestString() {
return nameTestString;
}
public void setNameTestString(String nameTestString) {
this.nameTestString = nameTestString;
}
public int getNameTestInt() {
return nameTestInt;
}
public void setNameTestInt(int nameTestInt) {
this.nameTestInt = nameTestInt;
}
public Boolean getNameTestBoolean() {
return nameTestBoolean;
}
public void setNameTestBoolean(Boolean nameTestBoolean) {
this.nameTestBoolean = nameTestBoolean;
}
public Long getNameTestLong() {
return nameTestLong;
}
public void setNameTestLong(Long nameTestLong) {
this.nameTestLong = nameTestLong;
}
}
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
i am new in using hibernate and for some reason i am getting a list of null objects when i am using the following code:
public static void main(String args[])
{
Session s = HibernateUtil.currentSession();
ArrayList lst = (ArrayList) s.createQuery("from Users").list();
for(Object obj : lst){
Users user = (Users)obj;
System.Out.println(user.getUserid()); // null
}
}
my hibernate mapping xml looks like this:
<?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 Dec 27, 2012 9:48:45 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="us.Users" table="USERS">
<id name="userid" type="int">
<column name="USERID" precision="9" scale="0" />
<generator class="assigned" />
</id>
<property name="username" type="string">
<column name="USERNAME" length="200" />
</property>
<property name="password" type="string">
<column name="PASSWORD" length="200" />
</property>
<property name="firstName" type="string">
<column name="FIRST_NAME" length="200" />
</property>
<property name="lastName" type="string">
<column name="LAST_NAME" length="200" />
</property>
<property name="dateOfBirth" type="timestamp"> // my guess was that the problem appears with the timestamp property
<column name="DATE_OF_BIRTH" />
</property>
<property name="registrationDate" type="timestamp">
<column name="REGISTRATION_DATE" />
</property>
<one-to-one name="administrators" class="assignment2.Administrators"></one-to-one>
<set name="histories" table="HISTORY" inverse="true" lazy="false" fetch="select">
<key>
<column name="USERID" precision="9" scale="0" not-null="true" />
</key>
<one-to-many class="us.History" />
</set>
<set name="loginlogs" table="LOGINLOG" inverse="true" lazy="false" fetch="select">
<key>
<column name="USERID" precision="9" scale="0" not-null="true" />
</key>
<one-to-many class="us.Loginlog" />
</set>
</class>
here is my hibernate.cfg.xml :
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">abcd</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">SYSTEM</property>
<property name="hibernate.default_schema">SYSTEM</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.search.autoregister_listeners">false</property>
<mapping resource="assignment2/History.hbm.xml" />
<mapping resource="assignment2/Similarity.hbm.xml" />
<mapping resource="assignment2/Loginlog.hbm.xml" />
<mapping resource="assignment2/Users.hbm.xml" />
<mapping resource="assignment2/Administrators.hbm.xml" />
<mapping resource="assignment2/Mediaitems.hbm.xml" />
</session-factory>
and the users class:
/**
* Users generated by hbm2java
*/
public class Users implements java.io.Serializable {
private int userid;
private String username;
private String password;
private String firstName;
private String lastName;
private Date dateOfBirth;
private Date registrationDate;
private Administrators administrators;
private Set<History> histories = new HashSet<History>(0);
private Set<Loginlog> loginlogs = new HashSet<Loginlog>(0);
public Users() {
}
public Users(int userid) {
this.userid = userid;
}
public Users(int userid, String username, String password,
String firstName, String lastName, Serializable dateOfBirth,
Serializable registrationDate, Administrators administrators,
Set<History> histories, Set<Loginlog> loginlogs) {
this.userid = userid;
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.registrationDate = registrationDate;
this.administrators = administrators;
this.histories = histories;
this.loginlogs = loginlogs;
}
public int getUserid() {
return this.userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Date getRegistrationDate() {
return this.registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public Administrators getAdministrators() {
return this.administrators;
}
public void setAdministrators(Administrators administrators) {
this.administrators = administrators;
}
public Set<History> getHistories() {
return this.histories;
}
public void setHistories(Set<History> histories) {
this.histories = histories;
}
public Set<Loginlog> getLoginlogs() {
return this.loginlogs;
}
public void setLoginlogs(Set<Loginlog> loginlogs) {
this.loginlogs = loginlogs;
}
}
thanks alot in advance