下面列出了怎么用org.hibernate.HibernateException的API类实例代码及写法,或者点击链接到github查看源代码。
@POST
@Consumes("application/json")
@Produces("application/json")
public MetaModelParview addVisualDependeciesForBusinessModelDriver(@PathParam("id") Integer id, MetaModelParview parameterViewObject) {
logger.debug("IN");
IMetaModelParviewDAO parameterViewDAO;
Integer newId = null;
Assert.assertNotNull(parameterViewObject, "Visual Dependencies can not be null");
try {
parameterViewDAO = DAOFactory.getMetaModelParviewDao();
newId = parameterViewDAO.insertMetaModelParview(parameterViewObject);
parameterViewObject.setId(newId);
} catch (HibernateException e) {
logger.error("Visual Dependencies can not be created", e);
throw new SpagoBIRestServiceException(e.getCause().getLocalizedMessage() + "in Visual Dependencsies", buildLocaleFromSession(), e);
}
logger.debug("OUT");
return parameterViewObject;
}
/**
* Store just a single object into data. This is slower than batching a few
* at a time. Should be used when the batching encounters an exception. This
* way can still store all of the good data from a batch.
*
* @param o
*/
private void processSingleObject(Object objectToBeStored) {
Session session = null;
Transaction tx = null;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
logger.debug("Individually saving object {}", objectToBeStored);
session.save(objectToBeStored);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
try {
tx.rollback();
} catch (HibernateException e2) {
logger.error("Error rolling back transaction in "
+ "processSingleObject(). ", e2);
}
}
} finally {
if (session != null)
session.close();
}
}
protected final Object getIdentifier(Object value, SharedSessionContractImplementor session) throws HibernateException {
if ( isReferenceToPrimaryKey() || uniqueKeyPropertyName == null ) {
return ForeignKeys.getEntityIdentifierIfNotUnsaved(
getAssociatedEntityName(),
value,
session
); //tolerates nulls
}
else if ( value == null ) {
return null;
}
else {
EntityPersister entityPersister = getAssociatedEntityPersister( session.getFactory() );
Object propertyValue = entityPersister.getPropertyValue( value, uniqueKeyPropertyName );
// We now have the value of the property-ref we reference. However,
// we need to dig a little deeper, as that property might also be
// an entity type, in which case we need to resolve its identitifier
Type type = entityPersister.getPropertyType( uniqueKeyPropertyName );
if ( type.isEntityType() ) {
propertyValue = ( (EntityType) type ).getIdentifier( propertyValue, session );
}
return propertyValue;
}
}
/**
* Create
*/
public static long create(WikiPage wkp) throws DatabaseException {
log.debug("create({})", wkp);
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
Long id = (Long) session.save(wkp);
HibernateUtil.commit(tx);
log.debug("create: {}" + id);
return id;
} catch (HibernateException e) {
HibernateUtil.rollback(tx);
throw new DatabaseException(e.getMessage(), e);
} finally {
HibernateUtil.close(session);
}
}
static void identityRemove(
Collection list,
Object object,
String entityName,
SessionImplementor session)
throws HibernateException {
if ( object!=null && ForeignKeys.isNotTransient(entityName, object, null, session) ) {
Type idType = session.getFactory().getEntityPersister(entityName).getIdentifierType();
Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, object, session);
Iterator iter = list.iterator();
while ( iter.hasNext() ) {
Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, iter.next(), session);
if ( idType.isEqual( idOfCurrent, idOfOld, session.getEntityMode(), session.getFactory() ) ) {
iter.remove();
break;
}
}
}
}
private MembershipCmImpl getMembership(final String userId, final AbstractMembershipContainerCmImpl container) {
final String lcUserId = StringUtils.lowerCase(userId);
// This may be a dynamic proxy. In that case, make sure we're using the class
// that hibernate understands.
final String className = Hibernate.getClass(container).getName();
final StringBuilder sb = new StringBuilder("select mbr from MembershipCmImpl as mbr, ");
sb.append(className);
sb.append(" as container where mbr.memberContainer=container ");
sb.append("and container.eid=:eid ");
sb.append("and mbr.userId=:userId");
HibernateCallback hc = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query q = session.createQuery(sb.toString());
q.setParameter("eid", container.getEid());
q.setParameter("userId", lcUserId);
return q.uniqueResult();
}
};
return (MembershipCmImpl)getHibernateTemplate().execute(hc);
}
/**
* Returns List of Route objects for the specified database revision.
* Orders them based on the GTFS route_order extension or the
* route short name if route_order not set.
*
* @param session
* @param configRev
* @return Map of routes keyed on routeId
* @throws HibernateException
*/
@SuppressWarnings("unchecked")
public static List<Route> getRoutes(Session session, int configRev)
throws HibernateException {
// Get list of routes from database
String hql = "FROM Route "
+ " WHERE configRev = :configRev"
+ " ORDER BY routeOrder, shortName";
Query query = session.createQuery(hql);
query.setInteger("configRev", configRev);
List<Route> routesList = query.list();
// Need to set the route order for each route so that can sort
// predictions based on distance from stop and route order. For
// the routes that didn't have route ordered configured in db
// start with 1000 and count on up.
int routeOrderForWhenNotConfigured = 1000;
for (Route route: routesList) {
if (!route.atBeginning() && !route.atEnd()) {
route.setRouteOrder(routeOrderForWhenNotConfigured++);
}
}
// Return the list of routes
return routesList;
}
/**
* Create activity
*/
public static void create(Activity activity) throws DatabaseException {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
session.save(activity);
HibernateUtil.commit(tx);
} catch (HibernateException e) {
HibernateUtil.rollback(tx);
throw new DatabaseException(e.getMessage(), e);
} finally {
HibernateUtil.close(session);
}
}
int delete(String query, Object value, Type type) {
int deleted = 0;
try {
// old: deleted = getSession().delete(query, value, type);
Session si = getSession();
Query qu = si.createQuery(query);
qu.setParameter(0, value, type);
List foundToDel = qu.list();
int deletionCount = foundToDel.size();
for (int i = 0; i < deletionCount; i++) {
si.delete(foundToDel.get(i));
}
// //
getSession().flush();
if (log.isDebugEnabled()) {
logQuery("delete", new Object[] { value }, new Type[] { type }, query);
}
} catch (HibernateException e) {
setError(e);
throw new DBRuntimeException("Delete error. Query" + query + " Object: " + value, e);
}
return deleted;
}
public CacheEntry(
final Object[] state,
final EntityPersister persister,
final boolean unfetched,
final Object version,
final SessionImplementor session,
final Object owner)
throws HibernateException {
//disassembled state gets put in a new array (we write to cache by value!)
this.disassembledState = TypeFactory.disassemble(
state,
persister.getPropertyTypes(),
persister.isLazyPropertiesCacheable() ?
null : persister.getPropertyLaziness(),
session,
owner
);
subclass = persister.getEntityName();
lazyPropertiesAreUnfetched = unfetched || !persister.isLazyPropertiesCacheable();
this.version = version;
}
protected void updateAssignment(final GradebookAssignment assignment) throws ConflictingAssignmentNameException, HibernateException {
// Ensure that we don't have the assignment in the session, since
// we need to compare the existing one in the db to our edited assignment
final Session session = getSessionFactory().getCurrentSession();
session.evict(assignment);
final GradebookAssignment asnFromDb = (GradebookAssignment) session.load(GradebookAssignment.class, assignment.getId());
final Long count = (Long) session.createCriteria(GradableObject.class)
.add(Restrictions.eq("name", assignment.getName()))
.add(Restrictions.eq("gradebook", assignment.getGradebook()))
.add(Restrictions.ne("id", assignment.getId()))
.add(Restrictions.eq("removed", false))
.setProjection(Projections.rowCount())
.uniqueResult();
if(count > 0) {
throw new ConflictingAssignmentNameException("You can not save multiple assignments in a gradebook with the same name");
}
session.evict(asnFromDb);
session.update(assignment);
}
/**
* Tries to load binary content from database for this ObjTemplate instance, given its binary content identifier, if content field is null.
*
* @return The binary content of this instance; if it is null, it tries to load it from database if binary content identifier is available
*
* @throws EMFUserError
* if some errors while reading from db occurs
* @throws EMFInternalError
* if some errors while reading from db occurs
*/
public byte[] getContent() throws HibernateException {
if (content == null) {
if (binId != null) {
// reads from database
try {
content = DAOFactory.getBinContentDAO().getBinContent(binId);
} catch (HibernateException e) {
logger.error("Error while recovering content of template with id = [" + id + "], binary content id = [" + binId + "], " + "name = [" + name
+ "] of biobject with id = [" + biobjId + "]" + e);
throw new HibernateException(e.getLocalizedMessage(), e);
}
} else {
logger.warn("Both content field of this istance and binary identifier are null. Cannot load content from database.");
}
}
return content;
}
@Override
public <T> T get(final Class<T> entityClass, final Serializable id, final LockMode lockMode)
throws DataAccessException {
return executeWithNativeSession(new HibernateCallback<T>() {
@Override
@SuppressWarnings("unchecked")
public T doInHibernate(Session session) throws HibernateException {
if (lockMode != null) {
return (T) session.get(entityClass, id, lockMode);
}
else {
return (T) session.get(entityClass, id);
}
}
});
}
/**
* Hash a constraint name using MD5. Convert the MD5 digest to base 35
* (full alphanumeric), guaranteeing
* that the length of the name will always be smaller than the 30
* character identifier restriction enforced by a few dialects.
*
* @param s
* The name to be hashed.
* @return String The hased name.
*/
public static String hashedName(String s) {
try {
MessageDigest md = MessageDigest.getInstance( "MD5" );
md.reset();
md.update( s.getBytes() );
byte[] digest = md.digest();
BigInteger bigInt = new BigInteger( 1, digest );
// By converting to base 35 (full alphanumeric), we guarantee
// that the length of the name will always be smaller than the 30
// character identifier restriction enforced by a few dialects.
return bigInt.toString( 35 );
}
catch ( NoSuchAlgorithmException e ) {
throw new HibernateException( "Unable to generate a hashed Constraint name!", e );
}
}
public ScrollableResults performScroll(
QueryParameters queryParameters,
SessionImplementor session) throws HibernateException {
if ( log.isTraceEnabled() ) {
log.trace( "iterate: " + getSourceQuery() );
queryParameters.traceParameters( session.getFactory() );
}
if ( translators.length != 1 ) {
throw new QueryException( "implicit polymorphism not supported for scroll() queries" );
}
if ( queryParameters.getRowSelection().definesLimits() && translators[0].containsCollectionFetches() ) {
throw new QueryException( "firstResult/maxResults not supported in conjunction with scroll() of a query containing collection fetches" );
}
return translators[0].scroll( queryParameters, session );
}
public void nullSafeSet(
PreparedStatement st,
Object value,
int index,
SharedSessionContractImplementor session)
throws HibernateException, SQLException {
st.setObject(index, value != null ? ((Enum) value).name() : null, Types.OTHER);
}
@Override
public Serializable save(final String entityName, final Object entity) throws DataAccessException {
return executeWithNativeSession(new HibernateCallback<Serializable>() {
@Override
public Serializable doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
return session.save(entityName, entity);
}
});
}
@Override
public BIObjectParameter loadBiObjParameterByObjIdAndLabel(Integer objId, String label) throws EMFUserError {
BIObjectParameter objPar = null;
Session aSession = null;
Transaction tx = null;
try {
aSession = getSession();
tx = aSession.beginTransaction();
Criterion idCriterrion = Expression.eq("sbiObject.biobjId", objId);
Criterion labelCriterrion = Expression.eq("label", label);
Criteria criteria = aSession.createCriteria(SbiObjPar.class);
criteria.add(idCriterrion);
criteria.add(labelCriterrion);
SbiObjPar hibObjPar = (SbiObjPar) criteria.uniqueResult();
if (hibObjPar != null)
objPar = toBIObjectParameter(hibObjPar);
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 objPar;
}
@Override
public List<Parameter> loadParametersByLovId(Integer lovId) throws EMFUserError {
Session aSession = null;
Transaction tx = null;
List realResult = new ArrayList();
try {
aSession = getSession();
tx = aSession.beginTransaction();
Query hibQuery = aSession.createQuery(("select distinct params from SbiParameters as params " + "inner join params.sbiParuses as paruses "
+ "inner join paruses.sbiLov as lov " + "where lov.lovId = " + lovId));
List hibList = hibQuery.list();
Iterator it = hibList.iterator();
while (it.hasNext()) {
realResult.add(toParameter((SbiParameters) it.next()));
}
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 realResult;
}
public void lock(
Serializable id,
Object version,
Object object,
LockMode lockMode,
SessionImplementor session) throws HibernateException {
getLocker( lockMode ).lock( id, version, object, session );
}
@Override
public boolean needsUpdating(Object entry, int i, Type elemType) throws HibernateException {
final List sn = (List) getSnapshot();
return i < sn.size()
&& sn.get( i ) != null
&& list.get( i ) != null
&& elemType.isDirty( list.get( i ), sn.get( i ), getSession() );
}
@Override
public List loadAllBIObjects() throws EMFUserError {
logger.debug("IN");
Session aSession = null;
Transaction tx = null;
List realResult = new ArrayList();
try {
aSession = getSession();
tx = aSession.beginTransaction();
Query hibQuery = aSession.createQuery(" from SbiObjects s order by s.label");
List hibList = hibQuery.list();
Iterator it = hibList.iterator();
while (it.hasNext()) {
realResult.add(toBIObject((SbiObjects) it.next(), aSession));
}
tx.commit();
} catch (HibernateException he) {
logger.error(he);
if (tx != null)
tx.rollback();
throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
} finally {
if (aSession != null) {
if (aSession.isOpen())
aSession.close();
}
}
logger.debug("OUT");
return realResult;
}
private Object instantiate(String listenerImpl, ClassLoaderService classLoaderService) {
try {
return classLoaderService.classForName( listenerImpl ).newInstance();
}
catch (Exception e) {
throw new HibernateException( "Could not instantiate requested listener [" + listenerImpl + "]", e );
}
}
@Override
public QueryCache getQueryCache(
final String regionName,
final UpdateTimestampsCache updateTimestampsCache,
final Settings settings,
final Properties props) throws HibernateException {
return new IgniteStandardQueryCache(settings, props, updateTimestampsCache, regionName);
}
/**
* @see org.hibernate.ScrollableResults#afterLast()
*/
public void afterLast() throws HibernateException {
try {
getResultSet().afterLast();
}
catch (SQLException sqle) {
throw JDBCExceptionHelper.convert(
getSession().getFactory().getSQLExceptionConverter(),
sqle,
"exception calling afterLast()"
);
}
}
public List findBySpace(final String pageSpace)
{
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)).list();
}
};
return (List) getHibernateTemplate().execute(callback);
}
finally
{
long finish = System.currentTimeMillis();
TimeLogger.printTimer("PagePresenceDaoImpl.findBySpace: "
+ pageSpace, start, finish);
}
}
@Override
public void processQueuedOps(PersistentCollection collection, Serializable key, SharedSessionContractImplementor session)
throws HibernateException {
if ( collection.hasQueuedOperations() ) {
doProcessQueuedOps( collection, key, session );
}
}
/** Updates the current DB-Schema with the schema defined by the hbm.xml files.
*
* @param script Print the DDL to the console.
* @param export
*/
public void updateSchema(Configuration cfg, boolean script, boolean export) {
try {
SchemaUpdate exp = new SchemaUpdate(cfg);
exp.execute(script, export);
} catch (HibernateException ex) {
log.fatal("Cant't update database schema: " + ex.getMessage(), ex);
return;
}
}
public boolean isEqual(Object x, Object y) throws HibernateException {
if ( x == y ) {
return true;
}
if ( x == null || y == null ) {
return false;
}
return x.equals( y ) || Hibernate.BINARY.isEqual( toBytes( x ), toBytes( y ) );
}
private List<GradebookAssignment> getAssignmentsCounted(final Long gradebookId) throws HibernateException {
final HibernateCallback<List<GradebookAssignment>> hc = session -> session
.createQuery(
"from GradebookAssignment as asn where asn.gradebook.id = :gradebookid and asn.removed is false and asn.notCounted is false")
.setLong("gradebookid", gradebookId)
.list();
return getHibernateTemplate().execute(hc);
}