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;
}
java类org.hibernate.HibernateException的实例源码
HibernateUtil.java 文件源码
项目:lambda-rds-mysql
阅读 39
收藏 0
点赞 0
评论 0
ReservationDaoImpl.java 文件源码
项目:Hotel-Properties-Management-System
阅读 40
收藏 0
点赞 0
评论 0
@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();
}
Base64ByteArrayTypeDescriptor.java 文件源码
项目:hibernate-ogm-redis
阅读 33
收藏 0
点赞 0
评论 0
@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() );
}
ObjectName.java 文件源码
项目:lams
阅读 27
收藏 0
点赞 0
评论 0
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 );
}
}
Loader.java 文件源码
项目:lams
阅读 56
收藏 0
点赞 0
评论 0
/**
* 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;
}
Driver2.java 文件源码
项目:FlashBoard
阅读 28
收藏 0
点赞 0
评论 0
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();
}
}
PersistentElementHolder.java 文件源码
项目:lams
阅读 38
收藏 0
点赞 0
评论 0
@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();
}
DialectFactoryImpl.java 文件源码
项目:lams
阅读 30
收藏 0
点赞 0
评论 0
/**
* 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;
}
SessionImpl.java 文件源码
项目:lams
阅读 33
收藏 0
点赞 0
评论 0
@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;
}
}
}
}
DefaultFlushEntityEventListener.java 文件源码
项目:lams
阅读 28
收藏 0
点赞 0
评论 0
/**
* 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 );
}
}
}
HibernateTemplate.java 文件源码
项目:lams
阅读 28
收藏 0
点赞 0
评论 0
@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();
}
});
}
CreationTimestampGeneration.java 文件源码
项目:lams
阅读 28
收藏 0
点赞 0
评论 0
@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" );
}
}
HibernateUtils.java 文件源码
项目:ipf-flow-manager
阅读 38
收藏 0
点赞 0
评论 0
/**
* 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);
}
}
HibernateTemplate.java 文件源码
项目:lams
阅读 27
收藏 0
点赞 0
评论 0
@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();
}
});
}
Collections.java 文件源码
项目:lams
阅读 29
收藏 0
点赞 0
评论 0
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() );
}
MultiTenantConnectionProviderImpl.java 文件源码
项目:xm-uaa
阅读 29
收藏 0
点赞 0
评论 0
@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;
}
SearchServiceBean.java 文件源码
项目:oscm
阅读 26
收藏 0
点赞 0
评论 0
/**
* 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);
}
}
}
CollectionType.java 文件源码
项目:lams
阅读 27
收藏 0
点赞 0
评论 0
@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;
}
AbstractCollectionPersister.java 文件源码
项目:lams
阅读 33
收藏 0
点赞 0
评论 0
@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;
}
OpenSessionInViewInterceptor.java 文件源码
项目:lams
阅读 30
收藏 0
点赞 0
评论 0
/**
* 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);
}
}
AbstractQueryImpl.java 文件源码
项目:lams
阅读 31
收藏 0
点赞 0
评论 0
protected Type determineType(int paramPosition, Object paramValue) throws HibernateException {
Type type = parameterMetadata.getOrdinalParameterExpectedType( paramPosition + 1 );
if ( type == null ) {
type = guessType( paramValue );
}
return type;
}
SpringSessionSynchronization.java 文件源码
项目:lemon
阅读 29
收藏 0
点赞 0
评论 0
public void flush() {
try {
logger.debug("Flushing Hibernate Session on explicit request");
getCurrentSession().flush();
} catch (HibernateException ex) {
throw SessionFactoryUtils.convertHibernateAccessException(ex);
}
}
EventType.java 文件源码
项目:lams
阅读 28
收藏 0
点赞 0
评论 0
/**
* 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;
}
HibernateTransactionManager.java 文件源码
项目:lams
阅读 34
收藏 0
点赞 0
评论 0
@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;
}
SessionImpl.java 文件源码
项目:lams
阅读 39
收藏 0
点赞 0
评论 0
@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 );
}
StandardQueryCache.java 文件源码
项目:lams
阅读 33
收藏 0
点赞 0
评论 0
@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;
}
CascadingActions.java 文件源码
项目:lams
阅读 30
收藏 0
点赞 0
评论 0
@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 );
}
ComponentType.java 文件源码
项目:lams
阅读 31
收藏 0
点赞 0
评论 0
@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 );
}
QueryLoader.java 文件源码
项目:lams
阅读 29
收藏 0
点赞 0
评论 0
@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
);
}
EmbeddedComponentType.java 文件源码
项目:lams
阅读 29
收藏 0
点赞 0
评论 0
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);
}