Java Reference
In-Depth Information
From the Session , you can do whatever you want with Hibernate's native
API, including queries by criteria. For example, you can simplify the
findBy ( ) methods: 3
Download email_24/src/stripesbook/dao/impl/stripersist/BaseDaoImpl.java
package stripesbook.dao.impl.stripersist;
import static org.hibernate.criterion.Restrictions. * ;
public abstract class BaseDaoImpl<T,ID extends Serializable>
implements Dao<T,ID>
{
/ * other methods... * /
@SuppressWarnings("unchecked")
public T findBy(String fieldName, Object value) {
Criteria criteria = getSession().createCriteria(entityClass)
.add(eq(fieldName, value));
return getSingleResult(criteria);
}
@SuppressWarnings("unchecked")
public T findBy(String fieldName, Object value, User user) {
Criteria criteria = getSession().createCriteria(entityClass)
.add(and(
eq(fieldName, value),
eq("user", user)
));
return getSingleResult(criteria);
}
@SuppressWarnings("unchecked")
private T getSingleResult(Criteria criteria) {
try {
return (T) criteria.uniqueResult();
}
catch (HibernateException exc) {
return (T) criteria.list().get(0);
}
}
}
It's nice to know that you can work with your JPA implementation's
native classes if you're more comfortable using them. Stripersist will
continue to work as before, but make sure you still use JPA annotations
on your model classes so that Stripersist finds them.
3. Notice the static import of Restrictions.* , which makes it possible to write code such as
and(eq(...), eq(...)) . Of course, you could also choose not to use static imports and write
Restrictions.and(Restrictions.eq(...), Restrictions.eq(...)) instead.
 
 
Search WWH ::




Custom Search