如何在hibernate中设置占位符

时间:2013-10-23 12:52:39

标签: java hibernate

嗨,这个我的java代码在这里使用hibernate检查这个电子邮件ID和密码是否存在于db或者没有任何人plz exp我如何将值放到这个占位符。

Session ses = HibernateUtil.getSessionFactory().openSession();
            String query;
            query = "from RegisterPojo where email=? and pwd=? ";
            List<RegBean> list = ses.createQuery(query).list();

            ses.close();

提前致谢

6 个答案:

答案 0 :(得分:3)

试试这个。

 Session ses = HibernateUtil.getSessionFactory().openSession();
      String query = "from RegisterPojo rp where rp.email = :emailAddress and rp.pwd = :password";
      List<RegisterPojo> list = ses.createQuery(query)
      .setParameter("emailAddress", Your email address)
      .setParameter("password", Your password)
      .list();
      ses.close();

答案 1 :(得分:1)

您必须像这样修改您的查询,

 query = "from RegisterPojo where email =:email and pwd =:password ";

 List<RegisterPojo> list = ses.createQuery(query)
 .setParameter("email",emailVal)
 .setParameter("password",emailVal)
 .list();

Read the hql docs here

答案 2 :(得分:1)

您应该使用预准备语句而不是字符串。 example here

  PreparedStatement preparedStatement = con.prepareStatement  ("from RegisterPojo where email=? and pwd=?");
preparedStatement.setString(1, "email");
preparedStatement.setString(2, "password");

答案 3 :(得分:0)

Session ses = HibernateUtil.getSessionFactory().openSession();
            String query;
            query = "from RegisterPojo where email=? and pwd=? ";
            List<RegBean> list = ses.createQuery(query).setParameter(0,emailVal).setParameter(1,emailVal).list();

            ses.close();

答案 4 :(得分:0)

试试这个。

   Session ses = HibernateUtil.getSessionFactory().openSession();
      String query = "from RegisterPojo where email = '" + varEmailAddress + "' and pwd = '" + varPassword + "'";
      List<RegisterPojo> list = ses.createQuery(query).list();
  ses.close();

答案 5 :(得分:0)

对不起,这不是答案,而是另一种情况,在上述情况下,@ Grigoriev Nick建议

 query = "from RegisterPojo where email=? and pwd=? ";
            List<RegBean> list = ses.createQuery(query).setParameter(0,emailVal).setParameter(1,emailVal).list();

但是在这里,脚本直接以 from 子句开头,而如果我想使用下面的sql怎么办

  WITH A (
    /// do some selection from many tables using various union as per my requirement
  ),
   B (
   ///  another set of sqls for different set of data
   )
select XXX from A a join B b on a.XYZ = b.xyz
where 
    /// few more fixed where clause conditions
   AND A.SOME_COLUMN = ?  // Here Instead Of String Concatenation I want to 
//use Query parameters but using hibernate instead of raw Prepares statements