org.hibernate.engine.SessionFactoryImplementor Java Examples

The following examples show how to use org.hibernate.engine.SessionFactoryImplementor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ComponentType.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String toLoggableString(Object value, SessionFactoryImplementor factory)
		throws HibernateException {
	if ( value == null ) {
		return "null";
	}
	Map result = new HashMap();
	EntityMode entityMode = tuplizerMapping.guessEntityMode( value );
	if ( entityMode == null ) {
		throw new ClassCastException( value.getClass().getName() );
	}
	Object[] values = getPropertyValues( value, entityMode );
	for ( int i = 0; i < propertyTypes.length; i++ ) {
		result.put( propertyNames[i], propertyTypes[i].toLoggableString( values[i], factory ) );
	}
	return StringHelper.unqualify( getName() ) + result.toString();
}
 
Example #2
Source File: BatchingEntityLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static UniqueEntityLoader createBatchingEntityLoader(
	final OuterJoinLoadable persister,
	final int maxBatchSize,
	final LockMode lockMode,
	final SessionFactoryImplementor factory,
	final Map enabledFilters)
throws MappingException {

	if ( maxBatchSize>1 ) {
		int[] batchSizesToCreate = ArrayHelper.getBatchSizes(maxBatchSize);
		Loader[] loadersToCreate = new Loader[ batchSizesToCreate.length ];
		for ( int i=0; i<batchSizesToCreate.length; i++ ) {
			loadersToCreate[i] = new EntityLoader(persister, batchSizesToCreate[i], lockMode, factory, enabledFilters);
		}
		return new BatchingEntityLoader(persister, batchSizesToCreate, loadersToCreate);
	}
	else {
		return new EntityLoader(persister, lockMode, factory, enabledFilters);
	}
}
 
Example #3
Source File: OneToManyLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public OneToManyLoader(
		QueryableCollection oneToManyPersister, 
		int batchSize, 
		String subquery, 
		SessionFactoryImplementor factory, 
		Map enabledFilters)
throws MappingException {

	super(oneToManyPersister, factory, enabledFilters);
	
	JoinWalker walker = new OneToManyJoinWalker(
			oneToManyPersister, 
			batchSize, 
			subquery, 
			factory, 
			enabledFilters
		);
	initFromWalker( walker );

	postInstantiate();

	log.debug( "Static select for one-to-many " + oneToManyPersister.getRole() + ": " + getSQLString() );
}
 
Example #4
Source File: PositionSubstringFunction.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String render(List args, SessionFactoryImplementor factory) throws QueryException {
	boolean threeArgs = args.size() > 2;
	Object pattern = args.get(0);
	Object string = args.get(1);
	Object start = threeArgs ? args.get(2) : null;

	StringBuffer buf = new StringBuffer();
	if (threeArgs) buf.append('(');
	buf.append("position(").append( pattern ).append(" in ");
	if (threeArgs) buf.append( "substring(");
	buf.append( string );
	if (threeArgs) buf.append( ", " ).append( start ).append(')');
	buf.append(')');
	if (threeArgs) buf.append('+').append( start ).append("-1)");
	return buf.toString();
}
 
Example #5
Source File: EntityLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public EntityLoader(
		OuterJoinLoadable persister, 
		int batchSize, 
		LockMode lockMode,
		SessionFactoryImplementor factory, 
		Map enabledFilters) 
throws MappingException {
	this( 
			persister, 
			persister.getIdentifierColumnNames(), 
			persister.getIdentifierType(), 
			batchSize,
			lockMode,
			factory, 
			enabledFilters 
		);
}
 
Example #6
Source File: SubselectOneToManyLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public SubselectOneToManyLoader(
		QueryableCollection persister, 
		String subquery,
		Collection entityKeys,
		QueryParameters queryParameters,
		Map namedParameterLocMap,
		SessionFactoryImplementor factory, 
		Map enabledFilters)
throws MappingException {
	
	super(persister, 1, subquery, factory, enabledFilters);

	keys = new Serializable[ entityKeys.size() ];
	Iterator iter = entityKeys.iterator();
	int i=0;
	while ( iter.hasNext() ) {
		keys[i++] = ( (EntityKey) iter.next() ).getIdentifier();
	}
	
	this.namedParameters = queryParameters.getNamedParameters();
	this.types = queryParameters.getFilteredPositionalParameterTypes();
	this.values = queryParameters.getFilteredPositionalParameterValues();
	this.namedParameterLocMap = namedParameterLocMap;
	
}
 
Example #7
Source File: SimpleExpression.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {

	String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName);
	Type type = criteriaQuery.getTypeUsingProjection(criteria, propertyName);
	StringBuffer fragment = new StringBuffer();
	if (columns.length>1) fragment.append('(');
	SessionFactoryImplementor factory = criteriaQuery.getFactory();
	int[] sqlTypes = type.sqlTypes( factory );
	for ( int i=0; i<columns.length; i++ ) {
		boolean lower = ignoreCase && 
				( sqlTypes[i]==Types.VARCHAR || sqlTypes[i]==Types.CHAR );
		if (lower) {
			fragment.append( factory.getDialect().getLowercaseFunction() )
				.append('(');
		}
		fragment.append( columns[i] );
		if (lower) fragment.append(')');
		fragment.append( getOp() ).append("?");
		if ( i<columns.length-1 ) fragment.append(" and ");
	}
	if (columns.length>1) fragment.append(')');
	return fragment.toString();

}
 
Example #8
Source File: BasicCollectionLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected BasicCollectionLoader(
		QueryableCollection collectionPersister, 
		int batchSize, 
		String subquery, 
		SessionFactoryImplementor factory, 
		Map enabledFilters)
throws MappingException {
	
	super(collectionPersister, factory, enabledFilters);
	
	JoinWalker walker = new BasicCollectionJoinWalker(
			collectionPersister, 
			batchSize, 
			subquery, 
			factory, 
			enabledFilters
		);
	initFromWalker( walker );

	postInstantiate();

	log.debug( "Static select for collection " + collectionPersister.getRole() + ": " + getSQLString() );
}
 
Example #9
Source File: ConditionalParenthesisFunction.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String render(List args, SessionFactoryImplementor factory) {
	final boolean hasArgs = !args.isEmpty();
	StringBuffer buf = new StringBuffer();
	buf.append( getName() );
	if ( hasArgs ) {
		buf.append( "(" );
		for ( int i = 0; i < args.size(); i++ ) {
			buf.append( args.get( i ) );
			if ( i < args.size() - 1 ) {
				buf.append( ", " );
			}
		}
		buf.append( ")" );
	}
	return buf.toString();
}
 
Example #10
Source File: AbstractEntityPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public EntityPersister getSubclassEntityPersister(Object instance, SessionFactoryImplementor factory, EntityMode entityMode) {
	if ( !hasSubclasses() ) {
		return this;
	}
	else {
		// TODO : really need a way to do something like :
		//      getTuplizer(entityMode).determineConcreteSubclassEntityName(instance)
		Class clazz = instance.getClass();
		if ( clazz == getMappedClass( entityMode ) ) {
			return this;
		}
		else {
			String subclassEntityName = getSubclassEntityName( clazz );
			if ( subclassEntityName == null ) {
				throw new HibernateException(
						"instance not of expected entity type: " + clazz.getName() +
						" is not a: " + getEntityName()
					);
			}
			else {
				return factory.getEntityPersister( subclassEntityName );
			}
		}
	}
}
 
Example #11
Source File: EntityType.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public int getHashCode(Object x, EntityMode entityMode, SessionFactoryImplementor factory) {
	EntityPersister persister = factory.getEntityPersister(associatedEntityName);
	if ( !persister.canExtractIdOutOfEntity() ) {
		return super.getHashCode(x, entityMode);
	}

	final Serializable id;
	if (x instanceof HibernateProxy) {
		id = ( (HibernateProxy) x ).getHibernateLazyInitializer().getIdentifier();
	}
	else {
		id = persister.getIdentifier(x, entityMode);
	}
	return persister.getIdentifierType().getHashCode(id, entityMode, factory);
}
 
Example #12
Source File: MessageHelper.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Generate an info message string relating to a series of entities.
 *
 * @param persister The persister for the entities
 * @param ids The entity id values
 * @param factory The session factory
 * @return An info string, in the form [FooBar#<1,2,3>]
 */
public static String infoString(
		EntityPersister persister, 
		Serializable[] ids, 
		SessionFactoryImplementor factory) {
	StringBuffer s = new StringBuffer();
	s.append( '[' );
	if( persister == null ) {
		s.append( "<null EntityPersister>" );
	}
	else {
		s.append( persister.getEntityName() );
		s.append( "#<" );
		for ( int i=0; i<ids.length; i++ ) {
			s.append( persister.getIdentifierType().toLoggableString( ids[i], factory ) );
			if ( i < ids.length-1 ) {
				s.append( ", " );
			}
		}
		s.append( '>' );
	}
	s.append( ']' );

	return s.toString();

}
 
Example #13
Source File: BatchingCollectionInitializer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static CollectionInitializer createBatchingOneToManyInitializer(
	final QueryableCollection persister,
	final int maxBatchSize,
	final SessionFactoryImplementor factory,
	final Map enabledFilters)
throws MappingException {

	if ( maxBatchSize>1 ) {
		int[] batchSizesToCreate = ArrayHelper.getBatchSizes(maxBatchSize);
		Loader[] loadersToCreate = new Loader[ batchSizesToCreate.length ];
		for ( int i=0; i<batchSizesToCreate.length; i++ ) {
			loadersToCreate[i] = new OneToManyLoader(persister, batchSizesToCreate[i], factory, enabledFilters);
		}
		return new BatchingCollectionInitializer(persister, batchSizesToCreate, loadersToCreate);
	}
	else {
		return new OneToManyLoader(persister, factory, enabledFilters);
	}
}
 
Example #14
Source File: BasicCollectionJoinWalker.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public BasicCollectionJoinWalker(
		QueryableCollection collectionPersister, 
		int batchSize, 
		String subquery, 
		SessionFactoryImplementor factory, 
		Map enabledFilters)
throws MappingException {

	super(factory, enabledFilters);

	this.collectionPersister = collectionPersister;

	String alias = generateRootAlias( collectionPersister.getRole() );

	walkCollectionTree(collectionPersister, alias);

	List allAssociations = new ArrayList();
	allAssociations.addAll(associations);
	allAssociations.add( new OuterJoinableAssociation( 
			collectionPersister.getCollectionType(),
			null, 
			null, 
			alias, 
			JoinFragment.LEFT_OUTER_JOIN, 
			getFactory(), 
			CollectionHelper.EMPTY_MAP 
		) );

	initPersisters(allAssociations, LockMode.NONE);
	initStatementString(alias, batchSize, subquery);

}
 
Example #15
Source File: Hibernate3Access.java    From snakerflow with Apache License 2.0 5 votes vote down vote up
protected Connection getConnection() throws SQLException {
    if (sessionFactory instanceof SessionFactoryImplementor) {
        ConnectionProvider cp = ((SessionFactoryImplementor) sessionFactory).getConnectionProvider();
        return cp.getConnection();
    }
    return super.getConnection();
}
 
Example #16
Source File: LocalSessionFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute schema creation script, determined by the Configuration object
 * used for creating the SessionFactory. A replacement for Hibernate's
 * SchemaExport class, to be invoked on application setup.
 * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed
 * SessionFactory to be able to invoke this method, e.g. via
 * {@code LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");}.
 * <p>Uses the SessionFactory that this bean generates for accessing a
 * JDBC connection to perform the script.
 * @throws DataAccessException in case of script execution errors
 * @see org.hibernate.cfg.Configuration#generateSchemaCreationScript
 * @see org.hibernate.tool.hbm2ddl.SchemaExport#create
 */
public void createDatabaseSchema() throws DataAccessException {
	logger.info("Creating database schema for Hibernate SessionFactory");
	DataSource dataSource = getDataSource();
	if (dataSource != null) {
		// Make given DataSource available for the schema update.
		configTimeDataSourceHolder.set(dataSource);
	}
	try {
		SessionFactory sessionFactory = getSessionFactory();
		final Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect();
		HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
		hibernateTemplate.execute(
			new HibernateCallback<Object>() {
				@Override
				public Object doInHibernate(Session session) throws HibernateException, SQLException {
					Connection con = session.connection();
					String[] sql = getConfiguration().generateSchemaCreationScript(dialect);
					executeSchemaScript(con, sql);
					return null;
				}
			}
		);
	}
	finally {
		if (dataSource != null) {
			configTimeDataSourceHolder.remove();
		}
	}
}
 
Example #17
Source File: CriteriaJoinWalker.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public CriteriaJoinWalker(
		final OuterJoinLoadable persister, 
		final CriteriaQueryTranslator translator,
		final SessionFactoryImplementor factory, 
		final CriteriaImpl criteria, 
		final String rootEntityName,
		final Map enabledFilters)
throws HibernateException {
	super(persister, factory, enabledFilters);

	this.translator = translator;

	querySpaces = translator.getQuerySpaces();

	if ( translator.hasProjection() ) {
		resultTypes = translator.getProjectedTypes();
		
		initProjection( 
				translator.getSelect(), 
				translator.getWhereCondition(), 
				translator.getOrderBy(),
				translator.getGroupBy(),
				LockMode.NONE 
			);
	}
	else {
		resultTypes = new Type[] { TypeFactory.manyToOne( persister.getEntityName() ) };

		initAll( translator.getWhereCondition(), translator.getOrderBy(), LockMode.NONE );
	}
	
	userAliasList.add( criteria.getAlias() ); //root entity comes *last*
	userAliases = ArrayHelper.toStringArray(userAliasList);

}
 
Example #18
Source File: MessageHelper.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Generate an info message string relating to a series of managed
 * collections.
 *
 * @param persister The persister for the collections
 * @param ids The id values of the owners
 * @param factory The session factory
 * @return An info string, in the form [Foo.bars#<1,2,3>]
 */
public static String collectionInfoString(
		CollectionPersister persister, 
		Serializable[] ids, 
		SessionFactoryImplementor factory) {
	StringBuffer s = new StringBuffer();
	s.append( '[' );
	if ( persister == null ) {
		s.append( "<unreferenced>" );
	}
	else {
		s.append( persister.getRole() );
		s.append( "#<" );
		for ( int i = 0; i < ids.length; i++ ) {
			// Need to use the identifier type of the collection owner
			// since the incoming is value is actually the owner's id.
			// Using the collection's key type causes problems with
			// property-ref keys...
			s.append( persister.getOwnerEntityPersister().getIdentifierType().toLoggableString( ids[i], factory ) );
			if ( i < ids.length-1 ) {
				s.append( ", " );
			}
		}
		s.append( '>' );
	}
	s.append( ']' );
	return s.toString();
}
 
Example #19
Source File: CustomOracleSpatialDialect.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public CustomOracleSpatialDialect() {
	super();

	InlineFunctionRegistrationManager.registerInlineFunctions(this);

	registerFunction("dwithin", new StandardSQLFunction("SDO_WITHIN_DISTANCE", StandardBasicTypes.STRING));
	registerFunction("spatial_contains", new StandardSQLFunction("SDO_CONTAINS", StandardBasicTypes.BOOLEAN));
	registerFunction("intersection", new StandardSQLFunction("SDO_GEOM.SDO_INTERSECTION", GeometryUserType.TYPE));
	registerFunction("spatial_nn", new StandardSQLFunction("SDO_NN", StandardBasicTypes.BIG_DECIMAL));
	registerFunction("length_spa", new StandardSQLFunction("SDO_GEOM.SDO_LENGTH", StandardBasicTypes.BIG_DECIMAL));
	registerFunction("filter", new StandardSQLFunction("SDO_FILTER", StandardBasicTypes.STRING));
	registerFunction("distance", new StandardSQLFunction("SDO_GEOM.SDO_DISTANCE", StandardBasicTypes.BIG_DECIMAL));
	registerFunction("union", new StandardSQLFunction("SDO_GEOM.SDO_UNION", GeometryUserType.TYPE));
	registerFunction("centroid", new StandardSQLFunction("SDO_GEOM.SDO_CENTROID", GeometryUserType.TYPE));
	registerFunction("covers", new StandardSQLFunction("SDO_COVERS", StandardBasicTypes.STRING));
	registerFunction("coveredby", new StandardSQLFunction("SDO_COVEREDBY", StandardBasicTypes.STRING));
	registerFunction("relate", new StandardSQLFunction("SDO_GEOM.RELATE", StandardBasicTypes.STRING));
	registerFunction("inside", new StandardSQLFunction("SDO_INSIDE", StandardBasicTypes.STRING));
	registerFunction("to_km", new SQLFunctionTemplate(StandardBasicTypes.BIG_DECIMAL, "((?1) * 1.852)"));
	registerFunction("to_nm", new SQLFunctionTemplate(StandardBasicTypes.BIG_DECIMAL, "((?1) / 1.852)"));
	registerFunction("extract", new SQLFunctionTemplate(StandardBasicTypes.LONG, "extract (?1 from (?2))"));
	registerFunction("to_timezone", new SQLFunctionTemplate(StandardBasicTypes.TIMESTAMP, "((?1) + ?2/24)") {
		@Override
		public String render(Type argumentType, List args, SessionFactoryImplementor factory) {
			if (args == null || args.size() != 2) {
				throw new QueryException("to_timezone() requires two arguments");
			}
			if (!((String) args.get(1)).matches("\\-?((1?[0-9])|(2[0-3]))")) {
				throw new QueryException("to_timezone()'s second parameter must be a number from -23 to +23");
			}
			return super.render(argumentType, args, factory);
		}
	});
	registerFunction("latitude", new SQLFunctionTemplate(StandardBasicTypes.STRING, "CASE ?1.Get_GType() WHEN 1 THEN to_char(?1.sdo_point.y) ELSE '' END"));
	registerFunction("longitude",
			new SQLFunctionTemplate(StandardBasicTypes.STRING, "CASE ?1.Get_GType() WHEN 1 THEN to_char(?1.sdo_point.x) ELSE '' END"));
}
 
Example #20
Source File: BasicCollectionLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public BasicCollectionLoader(
		QueryableCollection collectionPersister, 
		int batchSize, 
		SessionFactoryImplementor factory, 
		Map enabledFilters)
throws MappingException {
	this(collectionPersister, batchSize, null, factory, enabledFilters);
}
 
Example #21
Source File: LocalSessionFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute schema creation script, determined by the Configuration object
 * used for creating the SessionFactory. A replacement for Hibernate's
 * SchemaValidator class, to be invoked after application startup.
 * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed
 * SessionFactory to be able to invoke this method, e.g. via
 * {@code LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");}.
 * <p>Uses the SessionFactory that this bean generates for accessing a
 * JDBC connection to perform the script.
 * @throws DataAccessException in case of script execution errors
 * @see org.hibernate.cfg.Configuration#validateSchema
 * @see org.hibernate.tool.hbm2ddl.SchemaValidator
 */
public void validateDatabaseSchema() throws DataAccessException {
	logger.info("Validating database schema for Hibernate SessionFactory");
	DataSource dataSource = getDataSource();
	if (dataSource != null) {
		// Make given DataSource available for the schema update.
		configTimeDataSourceHolder.set(dataSource);
	}
	try {
		SessionFactory sessionFactory = getSessionFactory();
		final Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect();
		HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
		hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER);
		hibernateTemplate.execute(
			new HibernateCallback<Object>() {
				@Override
				public Object doInHibernate(Session session) throws HibernateException, SQLException {
					Connection con = session.connection();
					DatabaseMetadata metadata = new DatabaseMetadata(con, dialect, false);
					getConfiguration().validateSchema(dialect, metadata);
					return null;
				}
			}
		);
	}
	finally {
		if (dataSource != null) {
			configTimeDataSourceHolder.remove();
		}
	}
}
 
Example #22
Source File: SessionFactoryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private CurrentSessionContext buildCurrentSessionContext() {
	String impl = properties.getProperty( Environment.CURRENT_SESSION_CONTEXT_CLASS );
	// for backward-compatability
	if ( impl == null && transactionManager != null ) {
		impl = "jta";
	}

	if ( impl == null ) {
		return null;
	}
	else if ( "jta".equals( impl ) ) {
		if ( settings.getTransactionFactory().areCallbacksLocalToHibernateTransactions() ) {
			log.warn( "JTASessionContext being used with JDBCTransactionFactory; auto-flush will not operate correctly with getCurrentSession()" );
		}
		return new JTASessionContext( this );
	}
	else if ( "thread".equals( impl ) ) {
		return new ThreadLocalSessionContext( this );
	}
	else if ( "managed".equals( impl ) ) {
		return new ManagedSessionContext( this );
	}
	else {
		try {
			Class implClass = ReflectHelper.classForName( impl );
			return ( CurrentSessionContext ) implClass
					.getConstructor( new Class[] { SessionFactoryImplementor.class } )
					.newInstance( new Object[] { this } );
		}
		catch( Throwable t ) {
			log.error( "Unable to construct current session context [" + impl + "]", t );
			return null;
		}
	}
}
 
Example #23
Source File: CustomType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String toLoggableString(Object value, SessionFactoryImplementor factory)
throws HibernateException {
	if ( value == null ) {
		return "null";
	}
	else if ( customLogging ) {
		return ( ( LoggableUserType ) userType ).toLoggableString( value, factory );
	}
	else {
		return toXMLString( value, factory );
	}
}
 
Example #24
Source File: HQLTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void compileWithAstQueryTranslator(String hql, boolean scalar) {
	Map replacements = new HashMap();
	QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
	SessionFactoryImplementor factory = getSessionFactoryImplementor();
	QueryTranslator newQueryTranslator = ast.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, factory );
	newQueryTranslator.compile( replacements, scalar );
}
 
Example #25
Source File: MessageHelper.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Generate an info message string relating to a particular managed
 * collection.
 *
 * @param persister The persister for the collection
 * @param id The id value of the owner
 * @param factory The session factory
 * @return An info string, in the form [Foo.bars#1]
 */
public static String collectionInfoString(
		CollectionPersister persister, 
		Serializable id, 
		SessionFactoryImplementor factory) {
	StringBuffer s = new StringBuffer();
	s.append( '[' );
	if ( persister == null ) {
		s.append( "<unreferenced>" );
	}
	else {
		s.append( persister.getRole() );
		s.append( '#' );

		if ( id == null ) {
			s.append( "<null>" );
		}
		else {
			// Need to use the identifier type of the collection owner
			// since the incoming is value is actually the owner's id.
			// Using the collection's key type causes problems with
			// property-ref keys...
			s.append( persister.getOwnerEntityPersister().getIdentifierType().toLoggableString( id, factory ) );
		}
	}
	s.append( ']' );

	return s.toString();
}
 
Example #26
Source File: VarArgsSQLFunction.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String render(List args, SessionFactoryImplementor factory) throws QueryException {
	StringBuffer buf = new StringBuffer().append(begin);
	for ( int i=0; i<args.size(); i++ ) {
		buf.append( args.get(i) );
		if (i<args.size()-1) buf.append(sep);
	}
	return buf.append(end).toString();
}
 
Example #27
Source File: EntityLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public EntityLoader(
		OuterJoinLoadable persister, 
		LockMode lockMode,
		SessionFactoryImplementor factory, 
		Map enabledFilters) 
throws MappingException {
	this(persister, 1, lockMode, factory, enabledFilters);
}
 
Example #28
Source File: EntityType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Load an instance by a unique key that is not the primary key.
 *
 * @param entityName The name of the entity to load
 * @param uniqueKeyPropertyName The name of the property defining the uniqie key.
 * @param key The unique key property value.
 * @param session The originating session.
 * @return The loaded entity
 * @throws HibernateException generally indicates problems performing the load.
 */
public Object loadByUniqueKey(
		String entityName, 
		String uniqueKeyPropertyName, 
		Object key, 
		SessionImplementor session) throws HibernateException {
	final SessionFactoryImplementor factory = session.getFactory();
	UniqueKeyLoadable persister = ( UniqueKeyLoadable ) factory.getEntityPersister( entityName );

	//TODO: implement caching?! proxies?!

	EntityUniqueKey euk = new EntityUniqueKey(
			entityName, 
			uniqueKeyPropertyName, 
			key, 
			getIdentifierOrUniqueKeyType( factory ),
			session.getEntityMode(), 
			session.getFactory()
	);

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	Object result = persistenceContext.getEntity( euk );
	if ( result == null ) {
		result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session );
	}
	return result == null ? null : persistenceContext.proxyFor( result );
}
 
Example #29
Source File: EntityType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean isEqual(Object x, Object y, EntityMode entityMode, SessionFactoryImplementor factory) {
	EntityPersister persister = factory.getEntityPersister(associatedEntityName);
	if ( !persister.canExtractIdOutOfEntity() ) {
		return super.isEqual(x, y, entityMode);
	}

	Serializable xid;
	if (x instanceof HibernateProxy) {
		xid = ( (HibernateProxy) x ).getHibernateLazyInitializer()
				.getIdentifier();
	}
	else {
		xid = persister.getIdentifier(x, entityMode);
	}

	Serializable yid;
	if (y instanceof HibernateProxy) {
		yid = ( (HibernateProxy) y ).getHibernateLazyInitializer()
				.getIdentifier();
	}
	else {
		yid = persister.getIdentifier(y, entityMode);
	}

	return persister.getIdentifierType()
			.isEqual(xid, yid, entityMode, factory);
}
 
Example #30
Source File: QueryLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a new Loader implementation.
 *
 * @param queryTranslator The query translator that is the delegator.
 * @param factory The factory from which this loader is being created.
 * @param selectClause The AST representing the select clause for loading.
 */
public QueryLoader(
		final QueryTranslatorImpl queryTranslator,
        final SessionFactoryImplementor factory,
        final SelectClause selectClause) {
	super( factory );
	this.queryTranslator = queryTranslator;
	initialize( selectClause );
	postInstantiate();
}