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?
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.
使用表的主键来执行session.get(),如果表的主键不是电子邮件ID,则必须编写查询/ criteria / sql查询以匹配电子邮件密码。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.