hibernate 拼sql防止注入的问题

本文介绍了一种在Java中动态拼接SQL查询的方法,通过使用Hibernate框架结合字符串替换功能来实现安全的参数化查询。这种方法能有效避免SQL注入攻击,并展示了如何根据不同的条件动态构造查询语句。

//对参数拼接sql的时候,
//replaceAll("'","''")即可.即把单引号替换成双单引号
public List<Device> findDeviceUsers(final String devMac,final  String serviceId){
      return getHibernateTemplate().execute(new HibernateCallback<List<Device>>() {
         @Override
         public List<Device> doInHibernate(Session session) throws HibernateException, SQLException {


            List<Device> deviceList = null;
            String HQL = "  from Device d,UsersToDevice ut ";
            String where = " where 1=1";
            if (!serviceId.isEmpty()&&serviceId!=null){
//             String HQL = "  from Device d,Users u,UsersToDevice ut where d.devMac='"+devMac+"' and d.serviceId='"+serviceId+"' and ut.openid='"+openId+"'";
               where +=" and d.serviceId='"+serviceId.replaceAll("'","''")+"'";

            }
            if (!devMac.isEmpty() && devMac!=null){
               where +=" and d.devMac='"+devMac.replaceAll("'","''")+"'";
            }

            

            where+=" and d.id=ut.id";

            HQL+=where;

            Query query = session.createQuery(HQL);
            List<Object[]> resultList = query.list();
            if (resultList!=null && !resultList.isEmpty()){
               deviceList = new ArrayList<Device>(resultList.size());
               for (Object[] objects : resultList) {
                  Device device = (Device)objects[0];
                  deviceList.add(device);
               }
            }
            return deviceList;
         }
      });
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值