Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Implementing a UserDetailsService

György Varga
György Varga
19,198 Points

How we do the UserDao in the "old" way?

Hi!

In the "Spring with Hibernate" course we done the Daos a little different. Like this:

@Override
    public User findByUsername(String username) {
        Session session = sessionFactory.openSession();
        User user = session.get(User.class, username);
        session.close();
        return user;
    }

But it's not working because the session.get method needs the id instead of the username. How could we done this properly? Can you help me?

1 Answer

Daniel Vargas
Daniel Vargas
29,184 Points

Hi,

I'm sure there must be a better way, however this is a posiblity:

import org.hibernate.SQLQuery;
public User findByUserName (String username) {
        String slq = "SELECT * FROM user WHERE username = '" + username + "';";
        SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(slq).addEntity(User.class);
        return (User) query.list().get(0);
    }

Please let me know if this works you or if you find a better way since I would like to know too.

György Varga
György Varga
19,198 Points

Hi!

Here is what I used

@Override
    public User findByUsername(String username) {
        Session session = sessionFactory.openSession();
        Query query = session.createQuery("from User where username = :username ");
        query.setParameter("username", username);
        User user = (User) query.getSingleResult();
        session.close();
        return user;
    }

It's working but need to catch the exception... Hope this helps!