Search code examples
javamysqlhibernatehibernate-criteria

Using Select and where statement in Criteria


I am in the process of replacing jdbc with hibernate in my Web Application. I have learned that i don't have to write any SQL queries in this. Instead of this,criteria queries can help me. These are my SQL queries which i want to convert to hibernate using criteria not HQL.

String getOrgIdQuery = "SELECT * FROM USER_DETAILS WHERE USER_ID= ?";
rsDeptName = stmt.executeQuery("SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID ="+ DeptID + ";");
String insertCreateCdcValuesFirst = ("UPDATE User_Details SET User_Name=?, Organization_ID=?, Department_ID=?, Access_Ctrl = ?, User_Role=? WHERE User_ID = ?;");

Solution

  • First off all you must map your table with POJOS.

    String getOrgIdQuery = "SELECT * FROM USER_DETAILS WHERE USER_ID= ?";
    

    Preceding code in Hibernate look like following.

    Criteria criteria = session.createCriteria(USER_DETAILS.class);
    criteria.add(Restrictions.eq("user_id",yourUserId));
    List<USER_DETAILS> list = criteria.list();
    

    Your second select query is also same as preceding.

    String insertCreateCdcValuesFirst = ("UPDATE User_Details SET User_Name=?, Organization_ID=?, Department_ID=?, Access_Ctrl = ?, User_Role=? WHERE User_ID = ?;");
    

    With Hibernate Criteria update looks like following:

    USER_DETAILS user_details = (USER_DETAILES) session.get(USER_DETAILS.class,yourUserId);
    user_details.setUser_Name(NewUserName);
    user_details.setOrganization_Id(newOrganizationId);
    // some other fields update goes here
    session.update(user_details);
    tx.commit();
    

    I hope this help you.