下面列出了怎么用org.hibernate.criterion.Expression的API类实例代码及写法,或者点击链接到github查看源代码。
public List<SiteActivity> getSiteActivity(final String siteId, final List<String> events, final Date iDate, final Date fDate) {
if(siteId == null){
throw new IllegalArgumentException("Null siteId");
}else{
HibernateCallback<List<SiteActivity>> hcb = session -> {
Criteria c = session.createCriteria(SiteActivityImpl.class)
.add(Expression.eq("siteId", siteId))
.add(Expression.in("eventId", events));
if(iDate != null)
c.add(Expression.ge("date", iDate));
if(fDate != null){
// adjust final date
Calendar ca = Calendar.getInstance();
ca.setTime(fDate);
ca.add(Calendar.DAY_OF_YEAR, 1);
Date fDate2 = ca.getTime();
c.add(Expression.lt("date", fDate2));
}
return c.list();
};
return getHibernateTemplate().execute(hcb);
}
}
public List<SiteVisits> getSiteVisits(final String siteId, final Date iDate, final Date fDate) {
if(siteId == null){
throw new IllegalArgumentException("Null siteId");
}else{
HibernateCallback<List<SiteVisits>> hcb = session -> {
Criteria c = session.createCriteria(SiteVisitsImpl.class)
.add(Expression.eq("siteId", siteId));
if(iDate != null)
c.add(Expression.ge("date", iDate));
if(fDate != null){
// adjust final date
Calendar ca = Calendar.getInstance();
ca.setTime(fDate);
ca.add(Calendar.DAY_OF_YEAR, 1);
Date fDate2 = ca.getTime();
c.add(Expression.lt("date", fDate2));
}
return c.list();
};
return getHibernateTemplate().execute(hcb);
}
}
public SortedSet getStudentGradesForGradebook(final Gradebook gradebook)
throws IllegalArgumentException {
if (gradebook == null) {
throw new IllegalArgumentException("Null Argument");
} else {
HibernateCallback hcb = session -> {
// get syllabi in an eager fetch mode
Criteria crit = session.createCriteria(Gradebook.class).add(
Expression.eq(ID, gradebook.getId())).setFetchMode(STUDENTS,
FetchMode.EAGER);
Gradebook grades = (Gradebook) crit.uniqueResult();
if (grades != null) {
return grades.getStudents();
}
return new TreeSet();
};
return (SortedSet) getHibernateTemplate().execute(hcb);
}
}
/**
* Load source by name.
*
* @param session
* the session
*
* @param name
* the source name
*
* @return the meta source
*
* @throws EMFUserError
* the EMF user error
*
* @see it.eng.spagobi.metadata.dao.ISbiMetaBcDAOHibImpl#loadBcByName(session, string)
*/
@Override
public SbiMetaBc loadBcByName(Session session, String name) throws EMFUserError {
logger.debug("IN");
SbiMetaBc toReturn = null;
try {
Criterion labelCriterrion = Expression.eq("name", name);
Criteria criteria = session.createCriteria(SbiMetaBc.class);
criteria.add(labelCriterrion);
toReturn = (SbiMetaBc) criteria.uniqueResult();
} catch (HibernateException he) {
logException(he);
throw new HibernateException(he);
} finally {
logger.debug("OUT");
}
return toReturn;
}
/**
* Load source by the unique name.
*
* @param session
* the session
*
* @param name
* the unique name
*
* @return the meta bc
*
* @throws EMFUserError
* the EMF user error
*
* @see it.eng.spagobi.metadata.dao.ISbiMetaBcDAOHibImpl#loadBcByUniqueName(session, string)
*/
@Override
public SbiMetaBc loadBcByUniqueName(Session session, String uniqueName) throws EMFUserError {
logger.debug("IN");
SbiMetaBc toReturn = null;
try {
Criterion labelCriterrion = Expression.eq("uniqueName", uniqueName);
Criteria criteria = session.createCriteria(SbiMetaBc.class);
criteria.add(labelCriterrion);
toReturn = (SbiMetaBc) criteria.uniqueResult();
} catch (HibernateException he) {
logException(he);
throw new HibernateException(he);
} finally {
logger.debug("OUT");
}
return toReturn;
}
public void testCriteria() throws Exception {
Session s = openSession();
Transaction t = s.beginTransaction();
Lower l = new Lower();
s.save(l);
assertTrue( l==s.createCriteria(Top.class).uniqueResult() );
s.delete(l);
s.flush();
Criteria c = s.createCriteria(Lower.class);
c.createCriteria("yetanother")
.add( Expression.isNotNull("id") )
.createCriteria("another");
c.createCriteria("another").add( Expression.isNotNull("id") );
c.list();
t.commit();
s.close();
}
public Set getSyllabusAttachmentsForSyllabusData(final SyllabusData syllabusData)
{
if (syllabusData == null)
{
throw new IllegalArgumentException("Null Argument");
}
else
{
HibernateCallback<Set<SyllabusAttachment>> hcb = session -> {
Criteria crit = session.createCriteria(SyllabusDataImpl.class)
.add(Expression.eq(SYLLABUS_DATA_ID, syllabusData.getSyllabusId()))
.setFetchMode(ATTACHMENTS, FetchMode.EAGER);
SyllabusData syllabusData1 = (SyllabusData) crit.uniqueResult();
if (syllabusData1 != null){
return syllabusData1.getAttachments();
}
return new TreeSet();
};
return getHibernateTemplate().execute(hcb);
}
}
public StudentGrades getStudentByGBAndUsername(final Gradebook gradebook, final String username) {
if (gradebook == null || username == null) {
throw new IllegalArgumentException("Null gradebookId or username passed to getStudentByGBIdAndUsername");
}
HibernateCallback hcb = session -> {
gradebook.setStudents(null);
Criteria crit = session.createCriteria(StudentGradesImpl.class).add(
Expression.eq("gradebook", gradebook)).add(Expression.eq("username", username).ignoreCase());
StudentGrades student = (StudentGrades)crit.uniqueResult();
return student;
};
return (StudentGrades) getHibernateTemplate().execute(hcb);
}
public RWikiCurrentObject getRWikiCurrentObject(final RWikiObject reference) {
long start = System.currentTimeMillis();
try {
HibernateCallback<List> callback = session -> session.createCriteria(RWikiCurrentObject.class)
.add(Expression.eq("id", reference.getRwikiobjectid()))
.list();
List found = getHibernateTemplate().execute(callback);
if (found.size() == 0) {
log.debug("Found {} objects with id {}", found.size(), reference.getRwikiobjectid());
return null;
}
log.debug("Found {} objects with id {} returning most recent one.", found.size(), reference.getRwikiobjectid());
return (RWikiCurrentObject) proxyObject(found.get(0));
}
finally {
long finish = System.currentTimeMillis();
TimeLogger.printTimer("RWikiCurrentObjectDaoImpl.getRWikiCurrentObject: " + reference.getName(), start, finish);
}
}
public RWikiCurrentObject findByGlobalName(final String name) {
long start = System.currentTimeMillis();
try {
// there is no point in sorting by version, since there is only one
// version in
// this table.
// also using like is much slower than eq
HibernateCallback<List> callback = session -> session
.createCriteria(RWikiCurrentObject.class)
.add(Expression.eq("name", name))
.list();
List found = getHibernateTemplate().execute(callback);
if (found.size() == 0)
{
log.debug("Found {} objects with name {}", found.size(), name);
return null;
}
log.debug("Found {} objects with name {} returning most recent one.", found.size(), name);
return (RWikiCurrentObject) proxyObject(found.get(0));
} finally {
long finish = System.currentTimeMillis();
TimeLogger.printTimer("RWikiObjectDaoImpl.findByGlobalName: " + name, start, finish);
}
}
@Override
public SbiMetaJob loadJobByName(Session session, String name) throws EMFUserError {
logger.debug("IN");
SbiMetaJob toReturn = null;
Session tmpSession = session;
try {
Criterion labelCriterrion = Expression.eq("name", name);
Criteria criteria = tmpSession.createCriteria(SbiMetaJob.class);
criteria.add(labelCriterrion);
toReturn = (SbiMetaJob) criteria.uniqueResult();
if (toReturn == null)
return null;
} catch (HibernateException he) {
logException(he);
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
} finally {
logger.debug("OUT");
}
return toReturn;
}
@Override
public SbiMetaTableColumn loadTableColumnByName(Session session, String name) throws EMFUserError {
logger.debug("IN");
SbiMetaTableColumn toReturn = null;
Session tmpSession = session;
try {
Criterion labelCriterrion = Expression.eq("name", name);
Criteria criteria = tmpSession.createCriteria(SbiMetaTableColumn.class);
criteria.add(labelCriterrion);
toReturn = (SbiMetaTableColumn) criteria.uniqueResult();
if (toReturn == null)
return null;
} catch (HibernateException he) {
logException(he);
throw new HibernateException(he);
} finally {
logger.debug("OUT");
}
return toReturn;
}
/**
* getSyllabiForSyllabusItem returns the collection of syllabi
* @param syllabusItem
*/
public Set getSyllabiForSyllabusItem(final SyllabusItem syllabusItem)
{
if (syllabusItem == null)
{
throw new IllegalArgumentException("Null Argument");
}
else
{
HibernateCallback<Set> hcb = session -> {
// get syllabi in an eager fetch mode
Criteria crit = session.createCriteria(SyllabusItemImpl.class)
.add(Expression.eq(SURROGATE_KEY, syllabusItem.getSurrogateKey()))
.setFetchMode(SYLLABI, FetchMode.EAGER);
SyllabusItem syllabusItem1 = (SyllabusItem) crit.uniqueResult();
if (syllabusItem1 != null){
return syllabusItem1.getSyllabi();
}
return new TreeSet();
};
return getHibernateTemplate().execute(hcb);
}
}
/**
* getSyllabiForSyllabusItem returns the collection of syllabi
* @param syllabusItem
*/
public Set getSyllabiForSyllabusItem(final SyllabusItem syllabusItem)
{
if (syllabusItem == null)
{
throw new IllegalArgumentException("Null Argument");
}
else
{
HibernateCallback<Set> hcb = session -> {
// get syllabi in an eager fetch mode
Criteria crit = session.createCriteria(SyllabusItemImpl.class)
.add(Expression.eq(SURROGATE_KEY, syllabusItem.getSurrogateKey()))
.setFetchMode(SYLLABI, FetchMode.EAGER);
SyllabusItem syllabusItem1 = (SyllabusItem) crit.uniqueResult();
if (syllabusItem1 != null){
return syllabusItem1.getSyllabi();
}
return new TreeSet();
};
return getHibernateTemplate().execute(hcb);
}
}
public List<SiteActivity> getSiteActivity(final String siteId, final List<String> events, final Date iDate, final Date fDate) {
if(siteId == null){
throw new IllegalArgumentException("Null siteId");
}else{
HibernateCallback<List<SiteActivity>> hcb = session -> {
Criteria c = session.createCriteria(SiteActivityImpl.class)
.add(Expression.eq("siteId", siteId))
.add(Expression.in("eventId", events));
if(iDate != null)
c.add(Expression.ge("date", iDate));
if(fDate != null){
// adjust final date
Calendar ca = Calendar.getInstance();
ca.setTime(fDate);
ca.add(Calendar.DAY_OF_YEAR, 1);
Date fDate2 = ca.getTime();
c.add(Expression.lt("date", fDate2));
}
return c.list();
};
return getHibernateTemplate().execute(hcb);
}
}
public void testManyToManyFilterOnCriteria() {
TestData testData = new TestData();
testData.prepare();
Session session = openSession();
session.enableFilter( "effectiveDate" ).setParameter( "asOfDate", new Date() );
Product prod = ( Product ) session.createCriteria( Product.class )
.setResultTransformer( new DistinctRootEntityResultTransformer() )
.add( Expression.eq( "id", testData.prod1Id ) )
.uniqueResult();
assertNotNull( prod );
assertEquals( "Incorrect Product.categories count for filter", 1, prod.getCategories().size() );
session.close();
testData.release();
}
public int getChannelMessagesCount(ChatChannel channel, String context, Date date) {
if (channel == null) {
// default to the first one
List<ChatChannel> channels = getContextChannels(context, true);
if (channels != null && channels.size() > 0) {
channel = channels.iterator().next();
}
}
int count = 0;
if (channel != null) {
Criteria c = this.getSessionFactory().getCurrentSession().createCriteria(ChatMessage.class);
c.add(Expression.eq("chatChannel", channel));
if (date != null) {
c.add(Expression.ge("messageDate", date));
}
c.setProjection(Projections.rowCount());
count = ((Long) c.uniqueResult()).intValue();
}
return count;
}
public Set getSyllabusAttachmentsForSyllabusData(final SyllabusData syllabusData)
{
if (syllabusData == null)
{
throw new IllegalArgumentException("Null Argument");
}
else
{
HibernateCallback<Set<SyllabusAttachment>> hcb = session -> {
Criteria crit = session.createCriteria(SyllabusDataImpl.class)
.add(Expression.eq(SYLLABUS_DATA_ID, syllabusData.getSyllabusId()))
.setFetchMode(ATTACHMENTS, FetchMode.EAGER);
SyllabusData syllabusData1 = (SyllabusData) crit.uniqueResult();
if (syllabusData1 != null){
return syllabusData1.getAttachments();
}
return new TreeSet();
};
return getHibernateTemplate().execute(hcb);
}
}
public List isFerpaEnabled(final Collection agentUuids)
{
if (log.isDebugEnabled())
{
log.debug("isFerpaEnabled(Set {})", agentUuids);
}
if (agentUuids == null || agentUuids.isEmpty())
{
throw new IllegalArgumentException("Illegal Set agentUuids argument!");
}
final HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException
{
final Criteria c = session.createCriteria(SakaiPersonImpl.class);
c.add(Expression.in(AGENT_UUID, agentUuids));
c.add(Expression.eq(FERPA_ENABLED, Boolean.TRUE));
return c.list();
}
};
return (List) getHibernateTemplate().execute(hcb);
}
public RWikiCurrentObject findByGlobalName(final String name) {
long start = System.currentTimeMillis();
try {
// there is no point in sorting by version, since there is only one
// version in
// this table.
// also using like is much slower than eq
HibernateCallback<List> callback = session -> session
.createCriteria(RWikiCurrentObject.class)
.add(Expression.eq("name", name))
.list();
List found = getHibernateTemplate().execute(callback);
if (found.size() == 0)
{
log.debug("Found {} objects with name {}", found.size(), name);
return null;
}
log.debug("Found {} objects with name {} returning most recent one.", found.size(), name);
return (RWikiCurrentObject) proxyObject(found.get(0));
} finally {
long finish = System.currentTimeMillis();
TimeLogger.printTimer("RWikiObjectDaoImpl.findByGlobalName: " + name, start, finish);
}
}
public Gradebook getGradebookByTitleAndContext(final String title,
final String context) {
if (title == null || context == null) {
throw new IllegalArgumentException("Null Argument");
} else {
HibernateCallback hcb = session -> {
Criteria crit = session.createCriteria(GradebookImpl.class).add(
Expression.eq(TITLE, title)).add(Expression.eq(CONTEXT, context))
.setFetchMode(STUDENTS, FetchMode.EAGER);
Gradebook gradebook = (Gradebook) crit.uniqueResult();
return gradebook;
};
return (Gradebook) getHibernateTemplate().execute(hcb);
}
}
public void testCriteriaCollection() throws Exception {
Session s = openSession();
Fum fum = new Fum( fumKey("fum") );
fum.setFum("a value");
fum.getMapComponent().getFummap().put("self", fum);
fum.getMapComponent().getStringmap().put("string", "a staring");
fum.getMapComponent().getStringmap().put("string2", "a notha staring");
fum.getMapComponent().setCount(1);
s.save(fum);
s.flush();
s.connection().commit();
s.close();
s = openSession();
Fum b = (Fum) s.createCriteria(Fum.class).add(
Expression.in("fum", new String[] { "a value", "no value" } )
)
.uniqueResult();
//assertTrue( Hibernate.isInitialized( b.getMapComponent().getFummap() ) );
assertTrue( Hibernate.isInitialized( b.getMapComponent().getStringmap() ) );
assertTrue( b.getMapComponent().getFummap().size()==1 );
assertTrue( b.getMapComponent().getStringmap().size()==2 );
s.delete(b);
s.flush();
s.connection().commit();
s.close();
}
@Override
public SbiTenant loadTenantByName(String name) throws EMFUserError {
logger.debug("IN");
SbiTenant tenant = null;
Session tmpSession = null;
Transaction tx = null;
try {
tmpSession = getSession();
tx = tmpSession.beginTransaction();
Criterion labelCriterrion = Expression.eq("name", name);
Criteria criteria = tmpSession.createCriteria(SbiTenant.class);
criteria.add(labelCriterrion);
tenant = (SbiTenant) criteria.uniqueResult();
tx.commit();
} catch (HibernateException he) {
logger.error("Error while loading the tenant with name " + name, he);
if (tx != null)
tx.rollback();
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
} finally {
if (tmpSession != null) {
if (tmpSession.isOpen())
tmpSession.close();
}
}
logger.debug("OUT");
return tenant;
}
public List findByUser(final String user, final String context,
final String type)
{
long start = System.currentTimeMillis();
try
{
// there is no point in sorting by version, since there is only one
// version in
// this table.
// also using like is much slower than eq
HibernateCallback callback = new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException
{
String prefcontext = context + "%";
return session.createCriteria(Preference.class).add(
Expression.eq("userid", user)).add(
Expression.eq("preftype", type)).add(
Expression.like("prefcontext", prefcontext)).list();
}
};
return (List) getHibernateTemplate().execute(callback);
}
finally
{
long finish = System.currentTimeMillis();
TimeLogger.printTimer("PreferenceDaoImpl.findByUser: " + user,
start, finish);
}
}
public List findByUser(final String user)
{
long start = System.currentTimeMillis();
try
{
// there is no point in sorting by version, since there is only one
// version in
// this table.
// also using like is much slower than eq
HibernateCallback callback = new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException
{
return session.createCriteria(Trigger.class).add(
Expression.eq("user", user)).list();
}
};
return (List) getHibernateTemplate().execute(callback);
}
finally
{
long finish = System.currentTimeMillis();
TimeLogger.printTimer("PagePresenceDaoImpl.findByUser: " + user,
start, finish);
}
}
public List findByPage(final String pageSpace, final String pageName)
{
long start = System.currentTimeMillis();
try
{
// there is no point in sorting by version, since there is only one
// version in
// this table.
// also using like is much slower than eq
HibernateCallback callback = new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException
{
return session.createCriteria(Message.class).add(
Expression.eq("pagespace", pageSpace)).add(
Expression.eq("pagename", pageName)).list();
}
};
return (List) getHibernateTemplate().execute(callback);
}
finally
{
long finish = System.currentTimeMillis();
TimeLogger.printTimer("PagePresenceDaoImpl.findByPage: "
+ pageSpace + ":" + pageName, start, finish);
}
}
/**
* Load domain by code and value.
*
* @param codeDomain
* the code domain
* @param codeValue
* the code value
*
* @return the domain
*
* @throws EMFUserError
* the EMF user error
*
* @see it.eng.spagobi.commons.dao.IDomainDAO#loadDomainByCodeAndValue(java.lang.String, java.lang.String)
*/
@Override
public SbiDomains loadSbiDomainByCodeAndValue(String codeDomain, String codeValue) throws EMFUserError {
/*
* <STATEMENT name="SELECT_DOMAIN_FROM_CODE_VALUE" query="SELECT D.VALUE_NM AS VALUE_NAME, D.VALUE_ID AS VALUE_ID, D.VALUE_CD AS VALUE_CD FROM
* SBI_DOMAINS D WHERE DOMAIN_CD = ? AND VALUE_CD = ? "/>
*/
SbiDomains aSbiDomains = null;
Session aSession = null;
Transaction tx = null;
try {
aSession = getSession();
tx = aSession.beginTransaction();
Criterion aCriterion = Expression.and(Expression.eq("domainCd", codeDomain), Expression.eq("valueCd", codeValue));
Criteria criteria = aSession.createCriteria(SbiDomains.class);
criteria.add(aCriterion);
aSbiDomains = (SbiDomains) criteria.uniqueResult();
if (aSbiDomains == null)
return null;
tx.commit();
} catch (HibernateException he) {
logException(he);
if (tx != null)
tx.rollback();
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
} finally {
if (aSession != null) {
if (aSession.isOpen())
aSession.close();
}
}
return aSbiDomains;
}
/**
* Delete domain by id.
*
* @param id
* the id
*
* @return void
*
* @throws EMFUserError
* the EMF user error
*
*/
@Override
public void delete(Integer idDomain) throws EMFUserError {
logger.debug("IN");
Session sess = null;
Transaction tx = null;
try {
sess = getSession();
tx = sess.beginTransaction();
Criterion aCriterion = Expression.eq("valueId", idDomain);
Criteria criteria = sess.createCriteria(SbiDomains.class);
criteria.add(aCriterion);
SbiDomains aSbiDomains = (SbiDomains) criteria.uniqueResult();
if (aSbiDomains != null)
sess.delete(aSbiDomains);
tx.commit();
} catch (HibernateException he) {
logException(he);
if (tx != null)
tx.rollback();
throw new RuntimeException("Impossible to delete domain [" + idDomain + "]", he);
} finally {
if (sess != null) {
if (sess.isOpen())
sess.close();
}
}
}
@Deprecated public List<EventStat> getEventStats(final String siteId, final List<String> events,
final String searchKey, final Date iDate, final Date fDate) {
if(siteId == null){
throw new IllegalArgumentException("Null siteId");
}else{
final List<String> userIdList = searchUsers(searchKey, siteId);
/* return if no users matched */
if(userIdList != null && userIdList.size() == 0)
return new ArrayList<EventStat>();
HibernateCallback<List<EventStat>> hcb = session -> {
Criteria c = session.createCriteria(EventStatImpl.class)
.add(Expression.eq("siteId", siteId))
.add(Expression.in("eventId", events));
if(!showAnonymousAccessEvents)
c.add(Expression.ne("userId", EventTrackingService.UNKNOWN_USER));
if(userIdList != null && userIdList.size() > 0)
c.add(Expression.in("userId", userIdList));
if(iDate != null)
c.add(Expression.ge("date", iDate));
if(fDate != null){
// adjust final date
Calendar ca = Calendar.getInstance();
ca.setTime(fDate);
ca.add(Calendar.DAY_OF_YEAR, 1);
Date fDate2 = ca.getTime();
c.add(Expression.lt("date", fDate2));
}
return c.list();
};
return getHibernateTemplate().execute(hcb);
}
}
/**
* Load configuration by complete label.
*
* @param label the configuration label
*
* @return the config object
*
* @throws EMFUserError the EMF user error
*
* @see it.eng.spagobi.common.bo.dao.ISbiConfigDAO#loadConfigParametersById(string)
*/
@Override
public Config loadConfigParametersByLabel(String label) throws Exception {
logger.debug("IN");
Config toReturn = null;
Session tmpSession = null;
Transaction tx = null;
try {
tmpSession = getSession();
tx = tmpSession.beginTransaction();
Criterion labelCriterrion = Expression.eq("label", label);
Criteria criteria = tmpSession.createCriteria(SbiConfig.class);
criteria.add(labelCriterrion);
SbiConfig hibConfig = (SbiConfig) criteria.uniqueResult();
if (hibConfig == null)
return null;
toReturn = hibConfig.toConfig();
tx.commit();
} catch (HibernateException he) {
logException(he);
if (tx != null)
tx.rollback();
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
} finally {
if (tmpSession != null) {
if (tmpSession.isOpen())
tmpSession.close();
}
logger.debug("OUT");
}
return toReturn;
}