hibernate的三种查询

项目中的方便查阅

1)Criteria查询接口

public UserModel getUserByLoginName(String loginName) {

        Criteria criteria = this.getSession().createCriteria(UserModel.class);

        criteria.add(Restrictions.eq("userName",StringUtil

                .toString(loginName)));

        //criteria.addOrder(Order.desc("userName"));排序

        List list = criteria.list();

 

        if (list != null && list.size()> 0) {

            return (UserModel)list.get(0);

        }else{

            return null;

        }

    }


2)hql语句查询

public List<RoleModel> getPersonalRoleById(Integer id)

    {

        String hql = "from RoleUserModel a where a.userId="+id;

        Query query = this.getSession().createQuery(hql);

        List<RoleUserModel> roleuserList = query.list();

        List<RoleModel> returnList = new ArrayList<RoleModel>();

        for(RoleUserModel a:roleuserList){

            String hql1 = "from RoleModel a where a.roleId="+ a.getRoleId();

            Query query1 = this.getSession().createQuery(hql1);

            returnList.add((RoleModel)query1.list().get(0));

        }

        return returnList;

    }


3)原生SQL查询


public DeptModel getDeptByUserid(int userid) {

       String sql = "select DEPTNO, DEPTCODE, DEPTNAME, STATUS, ORDERNO, PARENTNO from dept  t " +

              "where t.deptnoin (select du.deptno from deptuser du where du.user_id="+userid+")";

       List<Map<String, Object>> list = this.findObjectListMapBySql(sql);

       DeptModel dept = null;

       if(list != null && list.size() > 0){

           dept = new DeptModel();

           Map<String, Object> deptMap = (Map<String,Object>) list.get(0);

           dept.setDeptNo(NumberUtil.toInt((BigDecimal)deptMap.get("DEPTNO")));

           dept.setDeptCode(deptMap.get("DEPTCODE").toString());

           dept.setDeptName(deptMap.get("DEPTNAME").toString());

           return dept;

       }else{

           return dept;

       }

    }


public List<Map<String, Object>> findObjectListMapBySql(String sql){

       SQLQuery sqlQuery=(SQLQuery) getSession().createSQLQuery(sql.toUpperCase()).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

       return sqlQuery.list();

    }






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值