Luke
Luke

Reputation: 7

Can anyone tell me how should I change the query in order to compare the values from my database with strings

So I am trying to find an User from my database who has the name and the password fields identical with the n and p string given as parameters. This is my findBy function:

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;
        }

I am calling it in a main function like this:

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();
        }
    }

The problem is that I encounter is this exception:

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)

Upvotes: 0

Views: 31

Answers (1)

Cedric
Cedric

Reputation: 124

When a query has some parameter, you must set them by using Query#setParameter not by String concatenation

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();

Upvotes: 2

Related Questions