Подтвердить что ты не робот

Как исправить запрос Hibernate с предупреждениями об отказе?

Кто-нибудь знает, как избежать следующего ПРЕДУПРЕЖДЕНИЯ для следующего кода?

org.hibernate.hql.internal.ast.HqlSqlWalker [HqlSqlWalker.java:929] [DEPRECATION] Encountered positional parameter near line 1, column 56.  Positional parameter are considered deprecated; use named parameters or JPA-style positional parameters instead.
Hibernate: select user0_.ID_USER as ID1_0_, user0_.USERNAME as USERNAME0_, user0_.PASSWORD as PASSWORD0_ from USER user0_ where user0_.USERNAME=?
Hibernate: select authoritie0_.ID_USER as ID1_0_1_, authoritie0_.ID_ROLE as ID2_1_, role1_.ID_ROLE as ID1_2_0_, role1_.NOMBRE as NOMBRE2_0_, role1_.DESCRIPCION as DESCRIPC3_2_0_ from USER_ROLE authoritie0_ inner join ROLE role1_ on authoritie0_.ID_ROLE=role1_.ID_ROLE where authoritie0_.ID_USER=?

Query query = sessionFactory.getCurrentSession().createQuery("from User where username=?");
query.setString(0, username);   
List<User> users = query.list();
4b9b3361

Ответ 1

Как говорится в сообщении, используйте именованные параметры.

List users = sessionFactory.getCurrentSession()
        .createQuery( "from User where username = :username" )
        .setString( "username", username )
        .list();

Ответ 2

Или вы можете использовать позиционные параметры в стиле JPA:

createQuery("from User where username=?1");

Вам также нужно изменить NamedQueries.

Ответ 3

Вот пример кода, который сканирует все файлы запросов hbm и изменяет их на позиционные параметры в стиле jpa.

@Test
public void replaceQuestionMark() throws IOException {

    org.springframework.core.io.Resource[] resources = new org.springframework.core.io.Resource[0];
    String queryFilesLocation = "persistence/hibernate/hbm/queries";
    resources = (new PathMatchingResourcePatternResolver()).getResources("classpath*:" + queryFilesLocation+ "/**");

    for (org.springframework.core.io.Resource resource : resources) {

        //remove xml description tag because it has also question mark and it can disturb the question mark scanning.
        // I will put it back at the end
        String queryFile = new String(IOUtils.toByteArray(resource.getInputStream())).replace("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", "");

        //split the queries file by "</named-query>" ending tag
        Iterable<String> queriesInFile = Splitter.on("</named-query>").split(queryFile);


        //initialize new list for new fixed queries string
        List<String> fixedQueryInFile = Lists.newArrayList();

        for (String queryString : queriesInFile) {

            Integer questionIndex = 0;
            char[] queryChars = queryString.toCharArray();
            StringBuffer fixedQueryString = new StringBuffer();
             //scan each char in a single query
            for (int i = 0; i < queryChars.length; i++) {

                char character = queryChars[i];
                //copy the char to the new fixed query
                fixedQueryString.append(character);
                if (character == '?') {
                    //add the question mark order number after the question mark
                    fixedQueryString.append(questionIndex);
                    //increase the order for the next question mark in this single query
                    questionIndex++;
                }

            }
            //add the fixed  query string to the list
            fixedQueryInFile.add(fixedQueryString.toString());
        }

        //add the xml description tag that we removed before + the fixed queries.
        String fixedFile = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + Joiner.on("</named-query>").join(fixedQueryInFile);
        File file = null;
        try {
            file = resource.getFile();
            //find the query file in the sources
            FileOutputStream fileOutputStream = new FileOutputStream(new File(file.getPath().replace("target\\classes", "src\\main\\resources")));
            //overwrite the file with the new fixed queries 
            fileOutputStream.write(fixedFile.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    if (resources == null) {
        throw new RuntimeException("resource not found");
    }
}