Find an object in Hibernate without id

I'm using Spring. I have a user table.

When a person logins to the system, he sends me his credentials (i.e. username and password).

I stored my users in database with "incremental generated uid" (i.e. userid is primary key).

I also stored the username password etc. in the database. What I need to do is, when the user connects to the Rest connection, I need to check whether the database has this user or not. If he exists, then I need to check if passwords are matching. And I need to do that checking by username, rather than uid

I dont have session or anything at all in my program (Or as far as I know, I didn't write any session or sessionfactory in my code at all)

My repository class:

public interface UserRepository extends JpaRepository<User, Long>{
}

My user DAO

@Service
public class UserDAO {

    @Autowired
    UserRepository userRepository;

    public User findByUsername(String username)
    {
        //what to write here

    }
}

I've looked up this solution but as I stated above, I don't have session.

1 answer

  • answered 2018-11-17 10:05 triplem

    Spring does provide all the necessary Dependencies and functions you do need.

    Coming back to your question. You can easily query for non-id fields in Spring by just providing a Repository and in there method Signatures with a certain Naming convention to provide the appropriate Result.

    You can inject EntityManager, which gives you access to the Session as well, using @PersistenceContext which will inject shared EntityManager managed by Spring

    Furthermore you can use the Naming Convention Thingy by extending your UserRepository from Repository (or any child of it), like you are already doing, and provide a method signature like findBy<FIELDNAME>(String value), eg. findByUsername(String username).

    If you do use the Repository-approach, you do not need to implement a DAO.

    For a detailed description, take a look at the Reference Documentation of Spring.