Question

I am just getting started with Hibernate. And I'm building a sample application where I'm signing up users by their email address.

And when they log in, they use that email address and password. Now, how do I get/retrieve a record/result while querying with their email ids?

My code looks like this:

    Configuration config = new Configuration();
    SessionFactory sessionFactory = config.configure().buildSessionFactory();
    Session session = sessionFactory.openSession();

    try{
        Transaction tx = session.beginTransaction();
        LoginBean L = (LoginBean)session.get(LoginBean.class,loginBean.getEmail());

    }catch(HibernateException HE){
        System.out.println(HE.getMessage());
    }

Of course the email field is a String. And Session.get() takes class,integer as its arguments. I do have a primary key of type Integer but I'd like to do a search/get using the email field.

How do I go about it?

Was it helpful?

Solution

Session.get() finds an entity by its primary key. To find entities via other means, you need to execute queries:

LoginBean user = (LoginBean)
    session.createQuery("select lb from LoginBean lb where lb.email = :email")
           .setString("email", email)
           .uniqueResult();

Queries and JPQL are explained in the reference documentation. Read it.

OTHER TIPS

U use primary key of the table to do a session.get(), if the primary key of the table is not email id then you have to write a query/criteria/sql query to match the email password.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top