Hibernate 外键查询怎么查?
public int findAllCount(CommodityClass commodityClass) {// TODO Auto-generated method stub
Session session=HibernateSessionFactory.getSession();
Query query = session.createQuery("from Commodity where commodityClass =:commodityClass");报错
query.setEntity("commodityClass", commodityClass);
return query.list().size();
}
public class Commodity implements java.io.Serializable {
@Id
@GeneratedValue
private Integer commodityId;
@ManyToOne
private CommodityClass commodityClass;
private String commodityName;
private String manufacturer;
private String commodityDepict;
private Double commodityPrice;
private Double fcPrice;
private Integer commodityAmount;
private Integer commodityLeaveNum;
private Date regTime;
private byte[] image;
--------------------编程问答-------------------- 你的查询应该是这样from Commodity c where c.commodityClass.commodityClassId=?
public class CommodityClass implements java.io.Serializable {
@Id
@GeneratedValue
private Integer commodityClassId;
private String commodityClassName;
虽然不知道你要查什么,但是建议不这么查 --------------------编程问答-------------------- 应该是按外键的id去查吧
from Commodity where commodityClass.commodityClassId =:commodityClassId
你直接用对象怎么查。。。。。。 --------------------编程问答--------------------
Session session=HibernateSessionFactory.getSession();
Query query=session.createQuery("from Commodity where commodityClass.commodityClassId =:commodityClassId");
query.setEntity("commodityClassId", commodityClassId);
List list=query.list();
int count=list.size();
HibernateSessionFactory.closeSession();
return count;
还是报错
java.lang.reflect.InvocationTargetException
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
--------------------编程问答-------------------- Query query = session.createQuery("from Commodity c where c.commodityClass.commodityClassId ="+commodityClass.getCommodityClassId());
然后直接执行query
还有个直接用对象查询的我有点忘了等我回去再看看 --------------------编程问答-------------------- Query query = session.createQuery("from Commodity c where c.commodityClass=?");
query.setParameter(0,commodityClass) --------------------编程问答-------------------- 用criteria啊 --------------------编程问答-------------------- 你应该创建一个对象,然后把这个对象赋值给他。 --------------------编程问答-------------------- 用HQL查询
如:
public int findAllCount(CommodityClass commodityClass) {
// TODO Auto-generated method stub
Session session=HibernateSessionFactory.getSession();
Query query = session.createQuery("from Commodity as commodity where commodity.外键ID=:commodityClass");报错
query.setString("外键ID", commodityClass.对应的外键ID字段);
return query.list().size();
}
补充:Java , Web 开发