java—有人能告诉我应该如何更改查询,以便将数据库中的值与字符串进行比较吗

ubof19bj  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(220)

因此,我试图从数据库中找到一个用户名和密码字段与作为参数给出的n和p字符串相同的用户。这是我的findby函数:

public User findBy(String n, String p){
            try(Session session = sessionFactory.openSession()) {
                Transaction tx = null;
                try {
                    tx = session.beginTransaction();
                    User uss = new User(n,p,TipUser.ANGAJAT);
                    User us =
                            session.createQuery("from User as u where u.name = " + uss.getName() + " and u.passwd = " + uss.getPasswd(), User.class)
                                    .uniqueResult();
                    System.out.println(us + " was found!");
                    tx.commit();
    //                return us;
                } catch (RuntimeException ex) {
                    if (tx != null)
                        tx.rollback();
                }
            }
            return null;
        }

我用这样的主函数调用它:

public static void main(String[] args) {
        try {
            initialize();

            UserRepoORM test = new UserRepoORM();
            test.findBy("Luca","luca");
        }catch (Exception e){
            System.err.println("Exception "+e);
            e.printStackTrace();
        }finally {
            close();
        }
    }

问题是我遇到了这样一个例外:

22 Apr 2021 19:16:25,995 DEBUG org.hibernate.engine.jdbc.spi.SqlExceptionHelper 126 logExceptions - could not prepare statement [select user0_.id as id1_1_, user0_.Name as name2_1_, user0_.Passwd as passwd3_1_, user0_.Tip as tip4_1_, user0_.LogIn as login5_1_ from User user0_ where user0_.Name=Luca and user0_.Passwd=luca]
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such column: Luca)
ldioqlga

ldioqlga1#

当查询有某些参数时,必须使用 Query#setParameter 不是通过字符串连接

Query<User> query = session.createQuery("from User as u where u.name=:name and u.passwd=:passwd", User.class);
query.setParameter("name", uss.getName());
query.setParameter("passwd", uss.getPasswd());
User user = query.uniqueResult();

相关问题