I have a problem in my project. I am trying to create a search function to search users from the user table, but at the meantime, I also want to retrieve the corresponding “url” of user’s avatar from another Avatar table. I do want to create a hard mapping between these two tables. How can I do it flexibly using Hibernate Criteria? Both tables are using primary key of “loginID“.
I have two classes:
public class User{
private String loginID;
private String screenname;
......
}
public class Avatar{
private Integer id;
private String loginID;
private String url;
.......
}
What I have written:
public List<Users> searchLogin(String keywords, int startFrom) {
List<Users> userList = new ArrayList<Users>();
try {
Session session = HibernateUtil.beginTransaction();
Criteria criteria = session.createCriteria(Users.class,"users");
criteria.add(Restrictions.ilike("loginID", keywords, MatchMode.ANYWHERE));
userList = criteria.list();
if (session.isOpen()) {
session.close();
}
return userList;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Thanks guys!!
Use HQL
This will return a list of [User,Avatar] arrays.