Search code examples
javahibernatecriteriahibernate-criteria

Trying to make method for hibernate criteria search


I am trying to make method for hibernate criteria search for user login.In this case I can not understand how to set the

 add(Restrictions.eq(propertyName, value)); 

for the method. I know propertyName should be the column name. but how can I get this and are there any mistake in code.

This is my servlet

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String email=req.getParameter("email");
            String password=req.getParameter("password");
            
            String [] arr = {email,password};
                creatreCriteria(Account.class);
            for (int i = 0; i < arr.length; i++) {
                addeqResrictions("colum name", arr.length);
            }
        } catch (Exception e) {
        }
    }

this is my session class.

 public static Criteria creatreCriteria(Class PC){
        getSession().createCriteria(PC);
        return criteria;
   }
    public static  SimpleExpression addeqResrictions(String p, Object v){
        criteria.add(Restrictions.eq(p, v));
        return simpleExpression;
    }
  } 

Solution

  • I think the best way is to parse a Map containing the values. Your method should look like this.

    public static void addeqRestrictions(HashMap<String, Object> r) {
        for (Map.Entry<String, Object> entry : r.entrySet()) {
            criteria.add(Restrictions.eq(entry.getKey(), entry.getValue()));
        }
    }
    

    Usage,

    HashMap<String, Object> map = new HashMap();
    map.put("ColName", object1);
    map.put("ColName", object2);
    map.put("ColName", object3);
    
    addeqRestrictions(map);