下面列出了怎么用org.hibernate.ObjectNotFoundException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Lookup a ConfigFile by its channel's id and config file name's id
* @param channel The file's config channel id
* @param name The file's config file name id
* @return the ConfigFile found or null if not found.
*/
public static ConfigFile lookupConfigFileByChannelAndName(Long channel, Long name) {
Session session = HibernateFactory.getSession();
Query query =
session.getNamedQuery("ConfigFile.findByChannelAndName")
.setLong("channel_id", channel)
.setLong("name_id", name)
.setLong("state_id", ConfigFileState.normal().
getId());
try {
return (ConfigFile) query.uniqueResult();
}
catch (ObjectNotFoundException e) {
return null;
}
}
/**
* Gets an Action Chain by id.
* @param requestor the user whose chain we're looking for
* @param id the id
* @return the Action Chain
* @throws ObjectNotFoundException if there is no such id accessible to the requestor
*/
public static ActionChain getActionChain(User requestor, Long id)
throws ObjectNotFoundException {
log.debug("Looking up Action Chain with id " + id);
if (id == null) {
return null;
}
ActionChain ac = (ActionChain) singleton.lookupObjectByNamedQuery(
"ActionChain.getActionChain",
new HashMap<String, Object>() { {
put("user", requestor);
put("id", id);
} }
);
if (ac == null) {
throw new ObjectNotFoundException(ActionChain.class,
"ActionChain Id " + id + " not found for User " +
requestor.getLogin());
}
return ac;
}
/**
* Gets an Action Chain Entry by id.
* @param requestor the user whose entry we're looking for
* @param id the action chain entry id
* @return the Action Chain Entry
* @throws ObjectNotFoundException if there is no such id accessible to the requestor
*/
public static ActionChainEntry getActionChainEntry(User requestor, Long id)
throws ObjectNotFoundException {
if (id == null) {
return null;
}
ActionChainEntry ace = (ActionChainEntry) getSession()
.load(ActionChainEntry.class, id);
if (ace.getActionChain().getUser().getId().longValue() ==
requestor.getId().longValue()) {
return ace;
}
throw new ObjectNotFoundException(ActionChainEntry.class,
"ActionChainEntry Id " + id + " not found for User " + requestor.getLogin());
}
@Test
public void testLoadWithNotFound() throws HibernateException {
ObjectNotFoundException onfex = new ObjectNotFoundException("id", TestBean.class.getName());
given(session.load(TestBean.class, "id")).willThrow(onfex);
try {
hibernateTemplate.load(TestBean.class, "id");
fail("Should have thrown HibernateObjectRetrievalFailureException");
}
catch (HibernateObjectRetrievalFailureException ex) {
// expected
assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
assertEquals("id", ex.getIdentifier());
assertEquals(onfex, ex.getCause());
}
verify(session).close();
}
public void removeTransientEntries(Map<Long, String> transientMap) {
CalendarEntry entry;
Transaction tx = _persister.getOrBeginTransaction();
for (Long entryID : transientMap.keySet()) {
String status = transientMap.get(entryID);
if (status.equals(TRANSIENT_FLAG)) {
try {
entry = (CalendarEntry) _persister.load(CalendarEntry.class, entryID);
_persister.delete(entry, tx);
}
catch (ObjectNotFoundException onfe) {
// nothing to remove if not found
}
}
else {
entry = (CalendarEntry) _persister.get(CalendarEntry.class, entryID);
if (entry != null) {
entry.setStatus(status);
_persister.update(entry, tx);
}
}
}
}
public Assignment getAssignment(Class_ clazz) {
Long solutionId = getSolutionId(clazz);
if (solutionId==null) return super.getAssignment(clazz);
Iterator i = null;
try {
i = clazz.getAssignments().iterator();
} catch (ObjectNotFoundException e) {
new _RootDAO().getSession().refresh(clazz);
i = clazz.getAssignments().iterator();
}
while (i.hasNext()) {
Assignment a = (Assignment)i.next();
if (solutionId.equals(a.getSolution().getUniqueId())) return a;
}
return null;
}
public String getAuthor() {
try {
// try to handle as identity id
final Identity identity = getBaseSecurity().loadIdentityByKey(Long.valueOf(author));
if (identity == null) {
return author;
}
return identity.getName();
} catch (final NumberFormatException nEx) {
return author;
} catch (final ObjectNotFoundException oEx) {
DBFactory.getInstanceForClosing().rollbackAndCloseSession();
return author;
} catch (final Throwable th) {
DBFactory.getInstanceForClosing().rollbackAndCloseSession();
return author;
}
}
public String getAuthor() {
try {
// try to handle as identity id
final Identity identity = getBaseSecurity().loadIdentityByKey(Long.valueOf(author));
if (identity == null) {
return author;
}
return identity.getName();
} catch (final NumberFormatException nEx) {
return author;
} catch (final ObjectNotFoundException oEx) {
DBFactory.getInstanceForClosing().rollbackAndCloseSession();
return author;
} catch (final Throwable th) {
DBFactory.getInstanceForClosing().rollbackAndCloseSession();
return author;
}
}
/**
* Lookup a ConfigFile by its channel's id and config file name's id
* @param channel The file's config channel id
* @param name The file's config file name id
* @return the ConfigFile found or null if not found.
*/
public static ConfigFile lookupConfigFileByChannelAndName(Long channel, Long name) {
Session session = HibernateFactory.getSession();
Query query =
session.getNamedQuery("ConfigFile.findByChannelAndName")
.setLong("channel_id", channel.longValue())
.setLong("name_id", name.longValue())
.setLong("state_id", ConfigFileState.normal().
getId().longValue())
//Retrieve from cache if there
.setCacheable(true);
try {
return (ConfigFile) query.uniqueResult();
}
catch (ObjectNotFoundException e) {
return null;
}
}
/**
* Gets an Action Chain by id.
* @param requestor the user whose chain we're looking for
* @param id the id
* @return the Action Chain
* @throws ObjectNotFoundException if there is no such id accessible to the requestor
*/
public static ActionChain getActionChain(User requestor, Long id)
throws ObjectNotFoundException {
log.debug("Looking up Action Chain with id " + id);
if (id == null) {
return null;
}
ActionChain ac = (ActionChain) getSession()
.createCriteria(ActionChain.class)
.add(Restrictions.eq("id", id))
.add(Restrictions.eq("user", requestor))
.uniqueResult();
if (ac == null) {
throw new ObjectNotFoundException(ActionChain.class,
"ActionChain Id " + id + " not found for User " +
requestor.getLogin());
}
return ac;
}
/**
* Gets an Action Chain Entry by id.
* @param requestor the user whose entry we're looking for
* @param id the action chain entry id
* @return the Action Chain Entry
* @throws ObjectNotFoundException if there is no such id accessible to the requestor
*/
public static ActionChainEntry getActionChainEntry(User requestor, Long id)
throws ObjectNotFoundException {
if (id == null) {
return null;
}
ActionChainEntry ace = (ActionChainEntry) getSession()
.load(ActionChainEntry.class, id);
if (ace.getActionChain().getUser().getId().longValue() ==
requestor.getId().longValue()) {
return ace;
}
throw new ObjectNotFoundException(ActionChainEntry.class,
"ActionChainEntry Id " + id + " not found for User " + requestor.getLogin());
}
@Test
public void testConsistencyIssuesWhenRemovingChildDirectly() {
LOGGER.info("Removing Child causes inconsistencies");
doInTransaction(session -> {
Commit commit = (Commit) session.get(Commit.class, 1L);
session.delete(commit);
});
try {
doInTransaction(session -> {
Repository repository = (Repository) session.get(Repository.class, 1L);
assertEquals(1, repository.getCommits().size());
});
} catch (ObjectNotFoundException e) {
LOGGER.warn("Object not found", e);
}
}
private ActionChain getActionChain(User user, Long actionChainId) {
try {
return ActionChainFactory.getActionChain(user, actionChainId);
}
catch (ObjectNotFoundException objectNotFoundException) {
LocalizationService ls = LocalizationService.getInstance();
LookupException e = new LookupException("Could not find action chain id: " +
actionChainId);
e.setLocalizedTitle(ls.getMessage("lookup.jsp.title.actionchain"));
e.setLocalizedReason1(ls.getMessage("lookup.jsp.actionchain.reason1"));
throw e;
}
}
/**
* Checks that an Action Chain does not exist anymore.
* @param actionChain the Action Chain to check
*/
public static void assertDeleted(ActionChain actionChain) {
try {
ActionChainFactory.getActionChain(actionChain.getUser(),
actionChain.getId());
fail();
}
catch (ObjectNotFoundException e) {
// correct
}
}
@Override
@SuppressWarnings("unchecked")
public final T load() {
final Serializable entityId = resolveNaturalId( this.naturalIdParameters );
if ( entityId == null ) {
return null;
}
try {
return (T) this.getIdentifierLoadAccess().load( entityId );
}
catch (EntityNotFoundException | ObjectNotFoundException enf) {
// OK
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public T load(Object naturalIdValue) {
final Serializable entityId = resolveNaturalId( getNaturalIdParameters( naturalIdValue ) );
if ( entityId == null ) {
return null;
}
try {
return (T) this.getIdentifierLoadAccess().load( entityId );
}
catch (EntityNotFoundException | ObjectNotFoundException e) {
// OK
}
return null;
}
@Test
public void testLoadWithNotFound() {
ObjectNotFoundException onfex = new ObjectNotFoundException("id", TestBean.class.getName());
given(session.load(TestBean.class, "id")).willThrow(onfex);
try {
hibernateTemplate.load(TestBean.class, "id");
fail("Should have thrown HibernateObjectRetrievalFailureException");
}
catch (HibernateObjectRetrievalFailureException ex) {
// expected
assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
assertEquals("id", ex.getIdentifier());
assertEquals(onfex, ex.getCause());
}
}
@Test(expected=ObjectNotFoundException.class)
public void testDelete() throws DatabaseUnitException, SQLException {
IDataSet ds = createDateSet("t_user");
DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds);
userDao.delete(1);
User tu = userDao.load(1);
System.out.println(tu.getUsername());
}
@Test(expected = ObjectNotFoundException.class)
public void testDelete() throws DatabaseUnitException, SQLException {
IDataSet ds = createDateSet("t_user");
DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
userDao.delete(1);
User tu = userDao.load(1);
System.out.println(tu.getUsername());
}
/**
* Reads a document from the database
*
* @param id the id of the document to read
* @return a YDocument wrapper for the document
* @throws IOException if no document can be found with the id passed
*/
private YDocument getDocument(long id) throws IOException {
try {
return (YDocument) _db.load(YDocument.class, id);
} catch (ObjectNotFoundException onfe) {
throw new IOException("No stored document found with id: " + id);
}
}
/**
* Removes a document from the database
*
* @param id the id of the document to remove
* @return true if successful
*/
private boolean removeDocument(long id) {
try {
YDocument doc = (YDocument) _db.load(YDocument.class, id);
return (doc != null) && _db.exec(doc, HibernateEngine.DB_DELETE, true);
} catch (ObjectNotFoundException onfe) {
return false;
}
}
private String addCaseID(long id, String caseID) throws IOException {
try {
YDocument doc = (YDocument) _db.load(YDocument.class, id);
if (doc != null) {
doc.setCaseId(caseID);
if (_db.exec(doc, HibernateEngine.DB_UPDATE, true)) {
return "Case ID successfully updated";
}
}
throw new IOException("No document found with id: " + id);
} catch (ObjectNotFoundException onfe) {
throw new IOException(onfe.getMessage());
}
}
/**
* @param aClass
* @return
*/
public boolean appliesTo(Class_ aClass) {
if (this.getDistributionObjects()==null) return false;
Iterator it = null;
try {
it = getDistributionObjects().iterator();
} catch (ObjectNotFoundException e) {
Debug.error("Exception "+e.getMessage()+" seen for "+this);
new _RootDAO().getSession().refresh(this);
it = getDistributionObjects().iterator();
}
while (it.hasNext()) {
DistributionObject dObj = (DistributionObject) it.next();
//Class_ check
//no checking whether dObj.getPrefGroup() is Class_ not needed since all PreferenceGroups have unique ids
if (dObj.getPrefGroup().getUniqueId().equals(aClass.getUniqueId())) return true;
//SchedulingSubpart check
SchedulingSubpart ss = null;
if (Hibernate.isInitialized(dObj.getPrefGroup())) {
if (dObj.getPrefGroup() instanceof SchedulingSubpart) {
ss = (SchedulingSubpart) dObj.getPrefGroup();
}
} else {
//dObj.getPrefGroup() is a proxy -> try to load it
PreferenceGroup pg = (new PreferenceGroupDAO()).get(dObj.getPrefGroup().getUniqueId());
if (pg!=null && pg instanceof SchedulingSubpart)
ss = (SchedulingSubpart)pg;
}
if (ss!=null && ss.getClasses()!=null && ss.getClasses().size()>0) {
for (Iterator it2 = ss.getClasses().iterator();it2.hasNext();)
if (((Class_)it2.next()).getUniqueId().equals(aClass.getUniqueId())) return true;
}
}
return false;
}
/** Ordered set of distribution objects */
public Set<DistributionObject> getOrderedSetOfDistributionObjects() {
try {
return new TreeSet<DistributionObject>(getDistributionObjects());
} catch (ObjectNotFoundException ex) {
(new DistributionPrefDAO()).getSession().refresh(this);
return new TreeSet<DistributionObject>(getDistributionObjects());
}
}
public InstructionalOffering getNextInstructionalOffering(SessionContext context, Comparator cmp) {
Long nextId = Navigation.getNext(context, Navigation.sInstructionalOfferingLevel, getUniqueId());
if (nextId!=null) {
if (nextId.longValue()<0) return null;
return (new InstructionalOfferingDAO()).get(nextId);
}
InstructionalOffering next = null;
SubjectArea area = getControllingCourseOffering().getSubjectArea();
Iterator i = null;
try {
i = area.getCourseOfferings().iterator();
}
catch (ObjectNotFoundException e) {
new _RootDAO().getSession().refresh(area);
i = area.getCourseOfferings().iterator();
}
for (;i.hasNext();) {
CourseOffering c = (CourseOffering)i.next();
if (!c.isIsControl().booleanValue()) continue;
InstructionalOffering o = (InstructionalOffering)c.getInstructionalOffering();
if (!o.isNotOffered().equals(isNotOffered())) continue;
if (cmp.compare(this, o)>=0) continue;
if (next==null || cmp.compare(next,o)>0)
next = o;
}
return next;
}
public InstructionalOffering getPreviousInstructionalOffering(SessionContext context, Comparator cmp) {
Long previousId = Navigation.getPrevious(context, Navigation.sInstructionalOfferingLevel, getUniqueId());
if (previousId!=null) {
if (previousId.longValue()<0) return null;
return (new InstructionalOfferingDAO()).get(previousId);
}
InstructionalOffering previous = null;
SubjectArea area = getControllingCourseOffering().getSubjectArea();
Iterator i = null;
try {
i = area.getCourseOfferings().iterator();
}
catch (ObjectNotFoundException e) {
new _RootDAO().getSession().refresh(area);
i = area.getCourseOfferings().iterator();
}
for (;i.hasNext();) {
CourseOffering c = (CourseOffering)i.next();
if (!c.isIsControl().booleanValue()) continue;
InstructionalOffering o = (InstructionalOffering)c.getInstructionalOffering();
if (!o.isNotOffered().equals(isNotOffered())) continue;
if (cmp.compare(this, o)<=0) continue;
if (previous==null || cmp.compare(previous,o)<0)
previous = o;
}
return previous;
}
private ActionChain getActionChain(User user, Long actionChainId) {
try {
return ActionChainFactory.getActionChain(user, actionChainId);
}
catch (ObjectNotFoundException notFoundException) {
LocalizationService ls = LocalizationService.getInstance();
LookupException e = new LookupException("Could not find action chain id: " +
actionChainId);
e.setLocalizedTitle(ls.getMessage("lookup.jsp.title.actionchain"));
e.setLocalizedReason1(ls.getMessage("lookup.jsp.actionchain.reason1"));
throw e;
}
}
/**
* Checks that an Action Chain does not exist anymore.
* @param actionChain the Action Chain to check
*/
public static void assertDeleted(ActionChain actionChain) {
try {
ActionChain ac = ActionChainFactory.getActionChain(actionChain.getUser(),
actionChain.getId());
fail();
}
catch (ObjectNotFoundException e) {
// correct
}
}
@Override
public <T> CompletionStage<T> reactiveFind(
Class<T> entityClass,
Object id,
LockMode lockMode,
Map<String, Object> properties) {
checkOpen();
getLoadQueryInfluencers().getEffectiveEntityGraph().applyConfiguredGraph( properties );
Boolean readOnly = properties == null ? null : (Boolean) properties.get( QueryHints.HINT_READONLY );
getLoadQueryInfluencers().setReadOnly( readOnly );
final ReactiveIdentifierLoadAccessImpl<T> loadAccess =
new ReactiveIdentifierLoadAccessImpl<>(entityClass)
.with( determineAppropriateLocalCacheMode( properties ) );
LockOptions lockOptions;
if ( lockMode != null ) {
// if ( !LockModeType.NONE.equals( lockModeType) ) {
// checkTransactionNeededForUpdateOperation();
// }
lockOptions = buildLockOptions(
LockModeConverter.convertToLockModeType(lockMode),
properties
);
loadAccess.with( lockOptions );
}
else {
lockOptions = null;
}
return loadAccess.load( (Serializable) id )
.handle( (result, e) -> {
if ( e instanceof EntityNotFoundException) {
// DefaultLoadEventListener.returnNarrowedProxy may throw ENFE (see HHH-7861 for details),
// which find() should not throw. Find() should return null if the entity was not found.
// if ( log.isDebugEnabled() ) {
// String entityName = entityClass != null ? entityClass.getName(): null;
// String identifierValue = id != null ? id.toString() : null ;
// log.ignoringEntityNotFound( entityName, identifierValue );
// }
return null;
}
if ( e instanceof ObjectDeletedException) {
//the spec is silent about people doing remove() find() on the same PC
return null;
}
if ( e instanceof ObjectNotFoundException) {
//should not happen on the entity itself with get
throw new IllegalArgumentException( e.getMessage(), e );
}
if ( e instanceof MappingException
|| e instanceof TypeMismatchException
|| e instanceof ClassCastException ) {
throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage(), e ) );
}
if ( e instanceof JDBCException ) {
// if ( accessTransaction().getRollbackOnly() ) {
// // assume this is the similar to the WildFly / IronJacamar "feature" described under HHH-12472
// return null;
// }
throw getExceptionConverter().convert( (JDBCException) e, lockOptions );
}
if ( e instanceof RuntimeException ) {
throw getExceptionConverter().convert( (RuntimeException) e, lockOptions );
}
return result;
} )
.whenComplete( (v, e) -> getLoadQueryInfluencers().getEffectiveEntityGraph().clear() );
}
/**
* Tests that actionchains are only accessible to the user that created them
* @throws Exception if something bad happens
*/
public void testPermissions() throws Exception {
Org otherOrg = UserTestUtils.createNewOrgFull("OtherOrg");
User other = UserTestUtils.createUser("otherAdmin", otherOrg.getId());
// Create the thing
ActionChain ac = ActionChainFactory.getOrCreateActionChain("chain1", user);
assertNotNull(ac);
Long acId = ac.getId();
// Can we find our own thing?
ac = ActionChainFactory.getActionChain(user, "chain1");
assertNotNull(ac);
// Can someone else find our thing by-label?
ac = ActionChainFactory.getActionChain(other, "chain1");
assertNull(ac);
// Can someone else find our thing by-id?
try {
ac = ActionChainFactory.getActionChain(other, acId);
}
catch (ObjectNotFoundException onfe) {
return;
}
catch (Throwable t) {
fail();
}
Action action = ActionFactory.createAction(ActionFactory.TYPE_ERRATA);
action.setOrg(user.getOrg());
Server server = ServerFactoryTest.createTestServer(user);
ac = ActionChainFactory.getActionChain(user, "chain1");
ActionChainEntry entry = ActionChainFactory.queueActionChainEntry(action,
ac, server);
ActionChainEntry ace = ActionChainFactory.getActionChainEntry(user, entry.getId());
assertNotNull(ace);
ace = ActionChainFactory.getActionChainEntry(other, entry.getId());
assertNull(ace);
}