使用hibernate

时间:2015-07-23 14:13:40

标签: spring hibernate named-query

我正在尝试使用带有Hibernate的命名SQL查询来访问数据库FK,其目的是查询包含name和companyId等的customer表。 CompanyId是commpany表的FK。我写的查询如下:

@NamedNativeQuery(name="getcustomer", query="Select CUSTOMER.* from CUSTOMER,COMPANY where CUSTOMER_FIRST_NAME = (?1) and CUSTOMER_LAST_NAME= (?2) and CUSTOMER_COMPANY_ID_FK = (?3) ",resultClass=Customer.class)

我目前遇到的问题如下:

  

线程“main”中的异常org.hibernate.QueryParameterException:   位置超出声明的序数参数的数量。记住这一点   序数参数是基于1的!位置:2点   org.hibernate.engine.query.spi.ParameterMetadata.getOrdinalParameterDescriptor(ParameterMetadata.java:89)   在   org.hibernate.engine.query.spi.ParameterMetadata.getOrdinalParameterExpectedType(ParameterMetadata.java:109)   在   org.hibernate.internal.AbstractQueryImpl.determineType(AbstractQueryImpl.java:507)   在   org.hibernate.internal.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:479)   在   com.comresource.scrapmetalapp.DAOImpl.CustomerDAOImpl.searchCustomer(CustomerDAOImpl.java:61)   在   com.comresource.scrapmetalapp.ServiceImpl.CustomerServiceImpl.searchCustomer(CustomerServiceImpl.java:39)   在com.comresource.scrapmetalapp.Config.Run.main(Run.java:57)

我的DAO实现是这样的:

@Override
   public Customer searchCustomer(String fName, String lName, Integer company) {

   Session session = sessionFactory.openSession();
   return (Customer) session.getNamedQuery("getcustomer").setParameter(1, fName)
           .setParameter(2, lName)
           .setParameter(3, company)
           .uniqueResult();
 }

这里有什么问题?

1 个答案:

答案 0 :(得分:0)

为此,我需要看看你如何关联模型类中的映射,但查询应该是这样的。

public Customer getMeThatCustomer(String param1, String param2, int foreignkey){
session = getCurrentSession();
org.hibernate.Query query = session.createQuery("From Customer as c where c.name=:param1 and c.lastname=:param2 and c.company.companyid=:foreignkey");
//Note the last parameter, where I have mentioned c.company, in place of 
company, there should be the foregin key association and then the primary key in java class.
query.setParameter("param1",param1);
query.setP...er("param2",param2);
quer.....("companyid",companyid);
return (Customer) query.uniqueResult();
}

所以,试一试,让我知道是否有任何问题