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!!
The Hibernate Session interface provides createCriteria() method, which can be used to create a Criteria object that returns instances of the persistence object's class when your application executes a criteria query.
JPQL provides a simple and straightforward way to get all entities from a table. Our Hibernate session's createQuery() method receives a typed query string as the first argument and the entity's type as the second. We execute the query with a call to the getResultList() method which returns the results as a typed List.
Yes, you can map an entity to 2 database tables in 2 simple steps: You need to annotate your entity with JPA's @Table and @SecondaryTable annotations and provide the names of the first and second table as the value of the name parameters.
Late, but it could be useful for others who actually google it and ends up here. No need to map or use HQL.
Here's how:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
Root<EntityA> entityARoot= criteria.from(EntityA.class);
Root<EntityB> entityBRoot = criteria.from(EntityB.class);
//Predicates
List<Predicate> predicates = new ArrayList<>();
//Add the predicates you need
//And predicates
List<Predicate> andPredicates = new ArrayList<>();
andPredicates.add(builder.equal(entityARoot.get("id"), entityBRoot.get("id")));
andPredicates.add(builder.and(predicates.toArray(new Predicate[0])));
criteria.multiselect(entityARoot, entityBRoot);
criteria.where(andPredicates.toArray(new Predicate[0]));
TypedQuery<Tuple> query = em.createQuery(criteria);
List<Tuple> result = query.getResultList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With