public static SessionFactory getSessionFactory() { if (null != sessionFactory) return sessionFactory; Configuration configuration = new Configuration(); String jdbcUrl = "jdbc:mysql://" + System.getenv("RDS_HOSTNAME") + "/" + System.getenv("RDS_DB_NAME"); configuration.setProperty("hibernate.connection.url", jdbcUrl); configuration.setProperty("hibernate.connection.username", System.getenv("RDS_USERNAME")); configuration.setProperty("hibernate.connection.password", System.getenv("RDS_PASSWORD")); configuration.configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); try { sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (HibernateException e) { System.err.println("Initial SessionFactory creation failed." + e); throw new ExceptionInInitializerError(e); } return sessionFactory; }
@Override public void saveReservation(Reservation reservation) { try { session = dataSourceFactory.getSessionFactory().openSession(); beginTransactionIfAllowed(session); session.save(reservation); session.getTransaction().commit(); logging.setMessage("ReservationDaoImpl -> reservations saved successfully."); } catch (HibernateException e) { session.getTransaction().rollback(); logging.setMessage("ReservationDaoImpl Error -> " + e.getLocalizedMessage()); } session.close(); }
@Override public <X> byte[] wrap(X value, WrapperOptions options) { if ( value == null ) { return null; } if ( Byte[].class.isInstance( value ) ) { return unwrapBytes( (Byte[]) value ); } if ( byte[].class.isInstance( value ) ) { return (byte[]) value; } if ( InputStream.class.isInstance( value ) ) { return DataHelper.extractBytes( (InputStream) value ); } if ( Blob.class.isInstance( value ) || DataHelper.isNClob( value.getClass() ) ) { try { return DataHelper.extractBytes( ( (Blob) value ).getBinaryStream() ); } catch (SQLException e) { throw new HibernateException( "Unable to access lob stream", e ); } } throw unknownWrap( value.getClass() ); }
private static String extractSchema(String qualifiedName) { if ( qualifiedName == null ) { return null; } String[] tokens = qualifiedName.split( SEPARATOR ); if ( tokens.length == 0 || tokens.length == 1 ) { return null; } else if ( tokens.length == 2 ) { // todo - this case needs to be refined w/ help of DatabaseMetaData (HF) return null; } else if ( tokens.length == 3 ) { return tokens[0]; } else { throw new HibernateException( "Unable to parse object name: " + qualifiedName ); } }
/** * Modify the SQL, adding lock hints and comments, if necessary */ protected String preprocessSQL( String sql, QueryParameters parameters, Dialect dialect, List<AfterLoadAction> afterLoadActions) throws HibernateException { sql = applyLocks( sql, parameters, dialect, afterLoadActions ); // Keep this here, rather than moving to Select. Some Dialects may need the hint to be appended to the very // end or beginning of the finalized SQL statement, so wait until everything is processed. if ( parameters.getQueryHints() != null && parameters.getQueryHints().size() > 0 ) { sql = dialect.getQueryHintString( sql, parameters.getQueryHints() ); } return getFactory().getSettings().isCommentsEnabled() ? prependComment( sql, parameters ) : sql; }
public static void testUserCreation() { Session session = HibernateUtil.getSession(); Transaction tx = null; User newUser = new User("jef", "jeff", "jeff", "jeff", "jeff"); //SQLIntegrityConstraintViolationException try { tx = session.beginTransaction(); session.save(newUser); tx.commit(); System.out.println("User: '" + newUser.getUsername() + "' has been successfully created!"); } catch (HibernateException he) { if (tx != null) { tx.rollback(); } System.out.println("User creation failed!"); he.printStackTrace(); } finally { session.close(); } }
@Override @SuppressWarnings({"unchecked", "deprecation"}) public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException { final Type elementType = persister.getElementType(); final ArrayList snapshot = (ArrayList) getSnapshot(); final List elements = element.elements( persister.getElementNodeName() ); final ArrayList result = new ArrayList(); for ( int i=0; i<snapshot.size(); i++ ) { final Object old = snapshot.get( i ); if ( i >= elements.size() ) { result.add( old ); } else { final Element elem = (Element) elements.get( i ); final Object object = elementType.fromXMLNode( elem, persister.getFactory() ); if ( elementType.isDirty( old, object, getSession() ) ) { result.add( old ); } } } return result.iterator(); }
/** * Determine the appropriate Dialect to use given the connection. * * @param resolutionInfoSource Access to DialectResolutionInfo used to resolve the Dialect. * * @return The appropriate dialect instance. * * @throws HibernateException No connection given or no resolver could make * the determination from the given connection. */ private Dialect determineDialect(DialectResolutionInfoSource resolutionInfoSource) { if ( resolutionInfoSource == null ) { throw new HibernateException( "Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set" ); } final DialectResolutionInfo info = resolutionInfoSource.getDialectResolutionInfo(); final Dialect dialect = dialectResolver.resolveDialect( info ); if ( dialect == null ) { throw new HibernateException( "Unable to determine Dialect to use [name=" + info.getDatabaseName() + ", majorVersion=" + info.getDatabaseMajorVersion() + "]; user must register resolver or explicitly set 'hibernate.dialect'" ); } return dialect; }
@Override public EntityPersister getEntityPersister(final String entityName, final Object object) { errorIfClosed(); if (entityName==null) { return factory.getEntityPersister( guessEntityName( object ) ); } else { // try block is a hack around fact that currently tuplizers are not // given the opportunity to resolve a subclass entity name. this // allows the (we assume custom) interceptor the ability to // influence this decision if we were not able to based on the // given entityName try { return factory.getEntityPersister( entityName ).getSubclassEntityPersister( object, getFactory() ); } catch( HibernateException e ) { try { return getEntityPersister( null, object ); } catch( HibernateException e2 ) { throw e; } } } }
/** * Performs all necessary checking to determine if an entity needs an SQL update * to synchronize its state to the database. Modifies the event by side-effect! * Note: this method is quite slow, avoid calling if possible! */ protected final boolean isUpdateNecessary(FlushEntityEvent event) throws HibernateException { EntityPersister persister = event.getEntityEntry().getPersister(); Status status = event.getEntityEntry().getStatus(); if ( !event.isDirtyCheckPossible() ) { return true; } else { int[] dirtyProperties = event.getDirtyProperties(); if ( dirtyProperties != null && dirtyProperties.length != 0 ) { return true; //TODO: suck into event class } else { return hasDirtyCollections( event, persister, status ); } } }
@Override public Iterator<?> iterate(final String queryString, final Object... values) throws DataAccessException { return executeWithNativeSession(new HibernateCallback<Iterator<?>>() { @Override @SuppressWarnings("unchecked") public Iterator<?> doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); prepareQuery(queryObject); if (values != null) { for (int i = 0; i < values.length; i++) { queryObject.setParameter(i, values[i]); } } return queryObject.iterate(); } }); }
@Override public void initialize(CreationTimestamp annotation, Class<?> propertyType) { if ( java.sql.Date.class.isAssignableFrom( propertyType ) ) { generator = new TimestampGenerators.CurrentSqlDateGenerator(); } else if ( Time.class.isAssignableFrom( propertyType ) ) { generator = new TimestampGenerators.CurrentSqlTimeGenerator(); } else if ( Timestamp.class.isAssignableFrom( propertyType ) ) { generator = new TimestampGenerators.CurrentSqlTimestampGenerator(); } else if ( Date.class.isAssignableFrom( propertyType ) ) { generator = new TimestampGenerators.CurrentDateGenerator(); } else if ( Calendar.class.isAssignableFrom( propertyType ) ) { generator = new TimestampGenerators.CurrentCalendarGenerator(); } else { throw new HibernateException( "Unsupported property type for generator annotation @CreationTimestamp" ); } }
/** * Reads a byte array from a {@link Blob}. * * @param blob * a {@link Blob} containing data. * @return data from {@link Blob} as byte array. */ public static byte[] toByteArray(Blob blob) { if (blob == null) { return null; } InputStream input = null; try { input = blob.getBinaryStream(); return IOUtils.toByteArray(input); } catch (Exception e) { throw new HibernateException("cannot read from blob", e); } finally { IOUtils.closeQuietly(input); } }
@Override public List<?> find(final String queryString, final Object... values) throws DataAccessException { return executeWithNativeSession(new HibernateCallback<List<?>>() { @Override @SuppressWarnings("unchecked") public List<?> doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); prepareQuery(queryObject); if (values != null) { for (int i = 0; i < values.length; i++) { queryObject.setParameter(i, values[i]); } } return queryObject.list(); } }); }
private static void processNeverReferencedCollection(PersistentCollection coll, SessionImplementor session) throws HibernateException { final PersistenceContext persistenceContext = session.getPersistenceContext(); final CollectionEntry entry = persistenceContext.getCollectionEntry( coll ); if ( LOG.isDebugEnabled() ) { LOG.debugf( "Found collection with unloaded owner: %s", MessageHelper.collectionInfoString( entry.getLoadedPersister(), coll, entry.getLoadedKey(), session ) ); } entry.setCurrentPersister( entry.getLoadedPersister() ); entry.setCurrentKey( entry.getLoadedKey() ); prepareCollectionForUpdate( coll, entry, session.getFactory() ); }
@Override public Connection getConnection(String tenantIdentifier) throws SQLException { final Connection connection = getAnyConnection(); try (Statement statement = connection.createStatement()) { statement.execute(String.format(resolver.getSchemaSwitchCommand(), tenantIdentifier)); } catch (SQLException e) { throw new HibernateException( "Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]", e ); } return connection; }
/** * Performs a search in Lucene and puts the resulting product object ids in * a corresponding map. * * @param query * the Lucene query * @param fts * the Hibernate Search FullTextSession * @param map * the map for the search results * @throws HibernateException */ private void searchViaLucene(org.apache.lucene.search.Query query, FullTextSession fts, LinkedHashMap<Long, VOService> map) throws HibernateException { FullTextQuery ftQuery = fts.createFullTextQuery(query, Product.class); ftQuery.setProjection("key"); List<?> result = ftQuery.list(); if (result != null) { for (Object item : result) { map.put((Long) ((Object[]) item)[0], null); } } }
@Override public Object replace( final Object original, final Object target, final SessionImplementor session, final Object owner, final Map copyCache) throws HibernateException { if ( original == null ) { return null; } if ( !Hibernate.isInitialized( original ) ) { return target; } // for a null target, or a target which is the same as the original, we // need to put the merged elements in a new collection Object result = target == null || target == original ? instantiateResult( original ) : target; //for arrays, replaceElements() may return a different reference, since //the array length might not match result = replaceElements( original, result, owner, copyCache, session ); if ( original == target ) { // get the elements back into the target making sure to handle dirty flag boolean wasClean = PersistentCollection.class.isInstance( target ) && !( ( PersistentCollection ) target ).isDirty(); //TODO: this is a little inefficient, don't need to do a whole // deep replaceElements() call replaceElements( result, target, owner, copyCache, session ); if ( wasClean ) { ( ( PersistentCollection ) target ).clearDirty(); } result = target; } return result; }
@Override public Object readIndex(ResultSet rs, String[] aliases, SessionImplementor session) throws HibernateException, SQLException { Object index = getIndexType().nullSafeGet( rs, aliases, session, null ); if ( index == null ) { throw new HibernateException( "null index column for collection: " + role ); } index = decrementIndexByBase( index ); return index; }
/** * Open a Session for the SessionFactory that this interceptor uses. * <p>The default implementation delegates to the {@link SessionFactory#openSession} * method and sets the {@link Session}'s flush mode to "MANUAL". * @return the Session to use * @throws DataAccessResourceFailureException if the Session could not be created * @see org.hibernate.FlushMode#MANUAL */ protected Session openSession() throws DataAccessResourceFailureException { try { Session session = getSessionFactory().openSession(); session.setFlushMode(FlushMode.MANUAL); return session; } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } }
protected Type determineType(int paramPosition, Object paramValue) throws HibernateException { Type type = parameterMetadata.getOrdinalParameterExpectedType( paramPosition + 1 ); if ( type == null ) { type = guessType( paramValue ); } return type; }
public void flush() { try { logger.debug("Flushing Hibernate Session on explicit request"); getCurrentSession().flush(); } catch (HibernateException ex) { throw SessionFactoryUtils.convertHibernateAccessException(ex); } }
/** * Find an {@link EventType} by its name * * @param eventName The name * * @return The {@link EventType} instance. * * @throws HibernateException If eventName is null, or if eventName does not correlate to any known event type. */ public static EventType resolveEventTypeByName(final String eventName) { if ( eventName == null ) { throw new HibernateException( "event name to resolve cannot be null" ); } final EventType eventType = EVENT_TYPE_BY_NAME_MAP.get( eventName ); if ( eventType == null ) { throw new HibernateException( "Unable to locate proper event type for event name [" + eventName + "]" ); } return eventType; }
@Override protected Object doGetTransaction() { HibernateTransactionObject txObject = new HibernateTransactionObject(); txObject.setSavepointAllowed(isNestedTransactionAllowed()); SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory()); if (sessionHolder != null) { if (logger.isDebugEnabled()) { logger.debug("Found thread-bound Session [" + SessionFactoryUtils.toString(sessionHolder.getSession()) + "] for Hibernate transaction"); } txObject.setSessionHolder(sessionHolder); } else if (this.hibernateManagedSession) { try { Session session = getSessionFactory().getCurrentSession(); if (logger.isDebugEnabled()) { logger.debug("Found Hibernate-managed Session [" + SessionFactoryUtils.toString(session) + "] for Spring-managed transaction"); } txObject.setExistingSession(session); } catch (HibernateException ex) { throw new DataAccessResourceFailureException( "Could not obtain Hibernate-managed Session for Spring-managed transaction", ex); } } if (getDataSource() != null) { ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(getDataSource()); txObject.setConnectionHolder(conHolder); } return txObject; }
@Override public void doWork(final Work work) throws HibernateException { WorkExecutorVisitable<Void> realWork = new WorkExecutorVisitable<Void>() { @Override public Void accept(WorkExecutor<Void> workExecutor, Connection connection) throws SQLException { workExecutor.executeWork( work, connection ); return null; } }; doWork( realWork ); }
@Override @SuppressWarnings({ "unchecked" }) public boolean put( final QueryKey key, final Type[] returnTypes, final List result, final boolean isNaturalKeyLookup, final SessionImplementor session) throws HibernateException { if ( isNaturalKeyLookup && result.isEmpty() ) { return false; } final long ts = cacheRegion.nextTimestamp(); if ( DEBUGGING ) { LOG.debugf( "Caching query results in region: %s; timestamp=%s", cacheRegion.getName(), ts ); } final List cacheable = new ArrayList( result.size() + 1 ); logCachedResultDetails( key, null, returnTypes, cacheable ); cacheable.add( ts ); final boolean isSingleResult = returnTypes.length == 1; for ( Object aResult : result ) { final Serializable cacheItem = isSingleResult ? returnTypes[0].disassemble( aResult, session, null ) : TypeHelper.disassemble( (Object[]) aResult, returnTypes, null, session, null ); cacheable.add( cacheItem ); logCachedResultRowDetails( returnTypes, aResult ); } try { session.getEventListenerManager().cachePutStart(); cacheRegion.put( key, cacheable ); } finally { session.getEventListenerManager().cachePutEnd(); } return true; }
@Override public void cascade( EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { LOG.tracev( "Cascading to save or update: {0}", entityName ); session.saveOrUpdate( entityName, child ); }
@Override public Object semiResolve(Object value, SessionImplementor session, Object owner) throws HibernateException { //note that this implementation is kinda broken //for components with many-to-one associations return resolve( value, session, owner ); }
@Override protected Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session) throws SQLException, HibernateException { Object[] resultRow = getResultRow( row, rs, session ); boolean hasTransform = hasSelectNew() || transformer!=null; return ( ! hasTransform && resultRow.length == 1 ? resultRow[ 0 ] : resultRow ); }
public Object instantiate(Object parent, SessionImplementor session) throws HibernateException { final boolean useParent = parent!=null && //TODO: Yuck! This is not quite good enough, it's a quick //hack around the problem of having a to-one association //that refers to an embedded component: super.getReturnedClass().isInstance(parent); return useParent ? parent : super.instantiate(parent, session); }
public Object get(ResultSet rs, String name) throws HibernateException, SQLException { if ( Environment.useStreamsForBinary() ) { InputStream inputStream = rs.getBinaryStream(name); if (inputStream==null) return toExternalFormat( null ); // is this really necessary? ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2048); byte[] buffer = new byte[2048]; try { while (true) { int amountRead = inputStream.read(buffer); if (amountRead == -1) { break; } outputStream.write(buffer, 0, amountRead); } inputStream.close(); outputStream.close(); } catch (IOException ioe) { throw new HibernateException( "IOException occurred reading a binary value", ioe ); } return toExternalFormat( outputStream.toByteArray() ); } else { return toExternalFormat( rs.getBytes(name) ); } }
public Object[] getPropertyValues(Object component) throws HibernateException { if ( component == BackrefPropertyAccessor.UNKNOWN ) { return new Object[propertySpan]; } else if ( optimizer != null && optimizer.getAccessOptimizer() != null ) { return optimizer.getAccessOptimizer().getPropertyValues( component ); } else { return super.getPropertyValues( component ); } }
public String toString(Type[] types, Object[] values) throws HibernateException { StringBuilder buffer = new StringBuilder(); for ( int i=0; i<types.length; i++ ) { if ( types[i]!=null ) { buffer.append( types[i].toLoggableString( values[i], factory ) ).append( ", " ); } } return buffer.toString(); }
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { if ( value != null ) { String string = (String) value; StringReader reader = new StringReader( string ); st.setCharacterStream( index, reader, string.length() ); } else { st.setNull( index, sqlTypes()[0] ); } }
@Override public List<Comment> getQuizComments(int quizId) { List<Comment> comments = new ArrayList<>(); Session session = HibernateUtil.getSession(); Criteria criteria = null; Quiz q = null; Query query = null; StudyGuide sg = null; String hql = "FROM StudyGuide WHERE studyGuideId = :id"; try { criteria = session.createCriteria(Quiz.class); q = (Quiz)criteria.add(Restrictions.like("quizId", quizId)).uniqueResult(); comments = q.getComments(); } catch(HibernateException he) { he.printStackTrace(); } if(comments.isEmpty()) { return null; } return comments; }
@Override public void cascade( EventSource session, Object child, String entityName, Object anything, boolean isCascadeDeleteEnabled) throws HibernateException { LOG.tracev( "Cascading to replicate: {0}", entityName ); session.replicate( entityName, child, (ReplicationMode) anything ); }
@Override public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { final StringBuilder buf = new StringBuilder( toLeftSqlString( criteria, criteriaQuery ) ); if ( op != null ) { buf.append( ' ' ).append( op ).append( ' ' ); } if ( quantifier != null ) { buf.append( quantifier ).append( ' ' ); } final SessionFactoryImplementor factory = criteriaQuery.getFactory(); final OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister( criteriaImpl.getEntityOrClassName() ); createAndSetInnerQuery( criteriaQuery, factory ); criteriaImpl.setSession( deriveRootSession( criteria ) ); final CriteriaJoinWalker walker = new CriteriaJoinWalker( persister, innerQuery, factory, criteriaImpl, criteriaImpl.getEntityOrClassName(), criteriaImpl.getSession().getLoadQueryInfluencers(), innerQuery.getRootSQLALias() ); return buf.append( '(' ).append( walker.getSQLString() ).append( ')' ).toString(); }
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { Reader reader = rs.getCharacterStream( names[0] ); if ( reader == null ) return null; StringBuilder result = new StringBuilder( 4096 ); try { char[] charbuf = new char[4096]; for ( int i = reader.read( charbuf ); i > 0 ; i = reader.read( charbuf ) ) { result.append( charbuf, 0, i ); } } catch (IOException e) { throw new SQLException( e.getMessage() ); } return result.toString(); }
/** * Return the query results as an iterator */ @Override public Iterator iterate(QueryParameters queryParameters, EventSource session) throws HibernateException { // Delegate to the QueryLoader... errorIfDML(); return queryLoader.iterate( queryParameters, session ); }
public void validateSchema(Dialect dialect, DatabaseMetadata databaseMetadata)throws HibernateException { secondPassCompile(); String defaultCatalog = properties.getProperty( Environment.DEFAULT_CATALOG ); String defaultSchema = properties.getProperty( Environment.DEFAULT_SCHEMA ); Iterator iter = getTableMappings(); while ( iter.hasNext() ) { Table table = (Table) iter.next(); if ( table.isPhysicalTable() ) { TableMetadata tableInfo = databaseMetadata.getTableMetadata( table.getName(), ( table.getSchema() == null ) ? defaultSchema : table.getSchema(), ( table.getCatalog() == null ) ? defaultCatalog : table.getCatalog(), table.isQuoted()); if ( tableInfo == null ) { throw new HibernateException( "Missing table: " + table.getName() ); } else { table.validateColumns( dialect, mapping, tableInfo ); } } } iter = iterateGenerators( dialect ); while ( iter.hasNext() ) { PersistentIdentifierGenerator generator = (PersistentIdentifierGenerator) iter.next(); Object key = generator.generatorKey(); if (key instanceof String) { key = normalizer.normalizeIdentifierQuoting( (String) key ); } if ( !databaseMetadata.isSequence( key ) && !databaseMetadata.isTable( key ) ) { throw new HibernateException( "Missing sequence or table: " + key ); } } }