Announcement Announcement Module
Collapse
No announcement yet.
Hibernate - Criteria API Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Hibernate - Criteria API

    Hi all,

    I need to understand the usuage of Criteria API for my multiple search operation. I am using Eclipse 3.2 IDE for my development. Where can I get information about using the API. I have written the HibernateUtil.java.
    I am getting some errors like

    Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibern
    ate.cfg.xml not found

    Where am I going wrong here.
    Any help would be appreciated?


    With thanks,
    Amutha

  • #2
    Originally posted by Amutha View Post
    Hi all,

    I need to understand the usuage of Criteria API for my multiple search operation.
    Have a look here.

    Regards,
    Andreas

    Comment


    • #3
      Originally posted by Amutha View Post
      I need to understand the usuage of Criteria API for my multiple search operation. [..] I am getting some errors like

      Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found
      It's not the usage of criteria API that goes wrong, you are not yet at that point. It seems your Hibernate setup itself has to be fixed first.

      For the criteria API you also find many articles on the web, just like this one from devx.

      Jörg

      Comment


      • #4
        Thanks Jorg,

        Comment


        • #5
          I think your problem is simply that Hibernate can't find the file in the specified location. I'd double check if the file is actually there. If you are still having problems post your configuration.

          Comment


          • #6
            Hi all,

            Thanks for your support. I am able to correct that error. I have written the daoimplementation method for search operation. I am using Eclipse IDE. Below is the method implementation

            public List findBySearchCriteria(String companyName,String city,String ctry) {

            Session session = null;
            System.out.println("COMPANY"+companyName);

            SessionFactory sessionFactory = new Configuration().configure()
            .buildSessionFactory();
            session = sessionFactory.openSession();

            Criteria crit = session.createCriteria(Company.class);
            Criteria addrCrit = crit.createCriteria("addresses");
            crit.add(Restrictions.like("companyName", "companyName"));
            addrCrit.add(Restrictions.like("city","city"));

            System.out.println(crit.list());
            List results = crit.list();

            System.out.println("Results----->"+results.size());
            return results;
            }
            When I execute this the results.size returns 0 even if the company exists in the db. The search is carried out based on companyname and city fields in differnet tables. CompanyAddress is associated with Company pojo. How to go about with this case. Expecting valuable suggestions.

            With thanks,
            Amutha

            Comment


            • #7
              You have hard coded the values of company and city, instead of passing in the values from the method. This just fix the problem. I you wrap code in [ code] [ /code] tags, it's sooo much easier to read! Just on a side note, if you use LocalSessionFactoryBean, you can let Spring manage Hibernate for you! The reference manual has more information on this.
              http://www.springframework.org/docs/...#orm-hibernate

              Comment


              • #8
                Hi karldmoore,

                Thankyou for your reply. Day by day I am learning with Spring and hibernate. I am able to solve this issue right now. I have got an issue right now. In my search operation say I have got 5 criterias to be taken care which are optional values. Whichever is entered in the form search process has to be made with that.
                Below is my code snippet

                Code:
                SessionFactory sessionFactory = new Configuration().configure()
                			.buildSessionFactory();
                	session = sessionFactory.openSession();
                
                List crit = session.createCriteria(Company.class)
                	.createCriteria("addresses", "address")
                	.add(Restrictions.like("address.countryCode",ctry))
                             .add(Restrictions.like("address.city",city))
                             .list();
                
                	System.out.println("Results----->"+crit.size());
                			return crit;
                Let us consider that companyName is associated with Company and city,coutnryCode are associated with CompanyAddress.Here CompanyAddress is associated with Company Pojo. The above code works fine with search operation made on either city or countryCode and not both of them. Search happens based upon one Restriction. With this search has to consider the restriction from Company too. Where can I get more information about this.
                Do we have any methods from Criteria API to deal with this situation.
                Able to get my problem???????????


                With thanks,
                Amutha

                Comment


                • #9
                  Ok, are you saying it's doing an AND and you want it to do an OR?

                  Comment


                  • #10
                    Dear Karldmoore,

                    I need my search to be made with an AND. Kindly guide me how to go with this.

                    With thanks,
                    Amutha

                    Comment


                    • #11
                      The criteria as you wrote it above is with AND. For OR you have to add Restrictions.OR: http://www.hibernate.org/hib_docs/v3...eria-narrowing

                      Maybe the data passed to 'Restrictions.like' makes the result return no elements.

                      Comment


                      • #12
                        As Andrei said it will do an AND by default. One useful thing would be to turn up the logging and see what SQL is coming out. You can then execute this against your database and ensure this is correct.
                        http://www.hibernate.org/hib_docs/v3...ration-logging

                        Comment


                        • #13
                          Hi all,

                          Thankyou for all your replies. I found that to be very useful. I am facing a different problem now. The fields in my search operation are not mandatory. The user will enter the sort criteria and the order of sorting.
                          In the below code companyName and companyType belong to Company POJO and city and countryCode belong to CompanyAddress POJO. Now Search is successful only when I choose atleast one values from both of the POJO and fails otherwise. The sort order is also entered by the user. How can I decide the sort order based on the users choice? The search has to be made even with a value from a single POJO?

                          Code:
                          SessionFactory sessionFactory = new Configuration().configure()
                          			.buildSessionFactory();
                          	session = sessionFactory.openSession();
                          		
                          	List crit = session.createCriteria(Company.class).add(Restrictions.or(Restrictions.like("searchName",compname),Restrictions.like("companyType", companyType)))
                          	.addOrder(Order.asc(sortCriteria))
                          	.createCriteria("addresses", "address")
                          	.add(Restrictions.or(Restrictions.like("address.city",city),Restrictions.like("address.countryCode",ctry )))
                          	.list();
                          	session.close();
                          	System.out.println("Results----->"+crit.size());
                          			return crit;
                          Where I am wrong here?. How could we change the defualt and operation to an or operation?

                          With Regards,
                          Amutha

                          Comment


                          • #14
                            I think your query fails in some cases because of lines like this:
                            Code:
                            Restrictions.or(Restrictions.like("searchName",compname),Restrictions.like("companyType", companyType)
                            If the user doesn't inputs company name, nor company type the query above still executes: select * from company where name like '' or type like ''.
                            How do you handle an empty criteria ?

                            Also, I would give karldmoore's sugestion a try, by looking at the actual query generated by Hibernate - this would help you understanding how Hibernate Criteria API works.

                            Comment


                            • #15
                              Hi Stefan,

                              This is the log which gets printed in my console.
                              You can find the actual search criteria with the bold text. Here companyName and companyType belong to Company Pojo and city and countryCode are from CompanyAddress Pojo. I need to change the default and operation too.

                              Code:
                              Hibernate: select this_.COMPANY_ID as COMPANY1_35_1_, this_.STATUS as STATUS35_1
                              _, this_.COMPANY_NAME as COMPANY3_35_1_, this_.SEARCH_NAME as SEARCH4_35_1_, thi
                              s_.SORT_NAME as SORT5_35_1_, this_.PHONE_NUMBER as PHONE6_35_1_, this_.PHONE_EXT
                              ENSION as PHONE7_35_1_, this_.FAX_NUMBER as FAX8_35_1_, this_.FAX_EXTENSION as F
                              AX9_35_1_, this_.LANGUAGE_PREFERENCE as LANGUAGE10_35_1_, this_.SUPPLIER_EXCEPTI
                              ON as SUPPLIER11_35_1_, this_.CAGE_CD as CAGE12_35_1_, this_.DUNS as DUNS35_1_,
                              this_.ENTERED_BY_USER_ID as ENTERED14_35_1_, this_.ENTERED_DATE as ENTERED15_35_
                              1_, this_.UPDATED_BY_USER_ID as UPDATED16_35_1_, this_.UPDATED_DATE as UPDATED17
                              _35_1_, this_.COMPANY_TYPE as COMPANY18_35_1_, address1_.ADDRESS_ID as ADDRESS1_
                              32_0_, address1_.COMPANY_ID as COMPANY2_32_0_, address1_.COUNTRY_CODE as COUNTRY
                              3_32_0_, address1_.MAIL_STOP as MAIL4_32_0_, address1_.PO_BOX as PO5_32_0_, addr
                              ess1_.SUITE_APARTMENT as SUITE6_32_0_, address1_.STREET as STREET32_0_, address1
                              _.CITY as CITY32_0_, address1_.POSTAL_CODE as POSTAL9_32_0_, address1_.ENTERED_B
                              Y_USER_ID as ENTERED10_32_0_, address1_.ENTERED_DATE as ENTERED11_32_0_, address
                              1_.UPDATED_BY_USER_ID as UPDATED12_32_0_, address1_.UPDATED_DATE as UPDATED13_32
                              _0_, address1_.STATE_ID as STATE14_32_0_ from EAN_COMPANY this_, EAN_COMPANY_ADD
                              RESS address1_ where this_.COMPANY_ID=address1_.COMPANY_ID and (this_.SEARCH_NAM
                              E like ? or this_.COMPANY_TYPE like ?) and (address1_.CITY like ? or address1_.C
                              OUNTRY_CODE like ?)Results----->1
                              Kindly guide me to proceed further.

                              With thanks,
                              Amutha

                              Comment

                              Working...
                              X