Search code examples
springhibernatenamed-query

Issue with writing named sql query with hibernate


I am trying to access database FK using named SQL query with Hibernate, the idea is to query a customer table which contains name, and companyId,etc. CompanyId is the FK for a commpany table. The query I wrote is as follows:

@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)

The issue I am currently having as follow:

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)

My DAO implementation is like this:

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

What is the issue here?


Solution

  • For this, I would need to see how you are associating the mapping in your model class, but the query should go like this.

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

    So, try it out, let me know if there is any problem