使用休眠编写名为 sql 查询的问题

Issue with writing named sql query with hibernate

我正在尝试使用带 Hibernate 的命名 SQL 查询来访问数据库 FK,我的想法是查询包含名称和公司 ID 等的客户 table。 CompanyId 是公司 table 的 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)

我目前遇到的问题如下:

Exception in thread "main" org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters. Remember that ordinal parameters are 1-based! Position: 2 at org.hibernate.engine.query.spi.ParameterMetadata.getOrdinalParameterDescriptor(ParameterMetadata.java:89) at org.hibernate.engine.query.spi.ParameterMetadata.getOrdinalParameterExpectedType(ParameterMetadata.java:109) at org.hibernate.internal.AbstractQueryImpl.determineType(AbstractQueryImpl.java:507) at org.hibernate.internal.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:479) at com.comresource.scrapmetalapp.DAOImpl.CustomerDAOImpl.searchCustomer(CustomerDAOImpl.java:61) at com.comresource.scrapmetalapp.ServiceImpl.CustomerServiceImpl.searchCustomer(CustomerServiceImpl.java:39) at 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();
 }

这里有什么问题?

为此,我需要了解您如何关联模型中的映射 class,但查询应该是这样的。

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();
}

所以,试试看,如果有任何问题,请告诉我