R
R
Romanov19812020-10-09 15:22:17
MySQL
Romanov1981, 2020-10-09 15:22:17

Criteria API How to get and return a user by name?

Greetings dear forum users.

Can you please tell me how to return the user with data?
I did the best I could))) but this is clearly not correct. Please tell me how?

public final User getUserByEmail(final String email){


        EntityManager entityManager = sessionFactory.createEntityManager();

        entityManager.getTransaction().begin();

        CriteriaBuilder builder = entityManager.getCriteriaBuilder();

        CriteriaQuery<Object[]> criteria = builder.createQuery( Object[].class );
        Root<User> root = criteria.from( User.class );

        Path<String> authEmailId = root.get( "email" );
        Path<String> authPasswordId = root.get( "password" );
        Path<String> authEnabledId = root.get( "enabled" );

        criteria.multiselect( authEmailId, authPasswordId, authEnabledId );

        criteria.where( builder.equal( root.get( "email" ), email ) );

        List<Object[]> authLoginId = entityManager.createQuery( criteria ).getResultList();

        entityManager.close();

        // Далее начинается моя самодеятельность.
        Object[] objects = authLoginId.get(0);

        User user = new User();

        user.setEmail(objects[0].toString());
        user.setPassword(objects[1].toString());
        user.setEnabled((Boolean) objects[2]);

        return user;
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question