Java Code Examples for org.hibernate.Hibernate#initialize()

The following examples show how to use org.hibernate.Hibernate#initialize() . 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: CollectionResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<CollectionDTO> getAllCrisisWithModelFamilies() throws PropertyNotSetException {
	List<CollectionDTO> dtoList = new ArrayList<CollectionDTO>();
	List<Collection> crisisList = getAll();
	if (crisisList != null && !crisisList.isEmpty()) {
		for (Collection crisis : crisisList) {
			try {
				Hibernate.initialize(crisis.getModelFamilies());		// fetching lazily loaded data
				CollectionDTO dto = new CollectionDTO(crisis);
				dtoList.add(dto);
			} catch (HibernateException e) {
				logger.error("Hibernate initialization error for lazy objects in : " + crisis.getCrisisId());
			}
		}
	} 
	return dtoList;
}
 
Example 2
Source File: Ejb.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 6 votes vote down vote up
public A getInitializedWithHibernate(long id){

        A a = em.find(A.class, id);
        if(a == null){
            return null;
        }

        //If you are using Hibernate, you can also use the following
        Hibernate.initialize(a.getList());

        return a;
    }
 
Example 3
Source File: CollectionResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public CollectionDTO getWithModelFamilyNominalAttributeByCrisisID(Long crisisID) throws PropertyNotSetException {
	Collection crisis = getById(crisisID);
	if (crisis != null) {
		try {
			Hibernate.initialize(crisis.getModelFamilies());
			for (ModelFamily mf : crisis.getModelFamilies()) {
				if(mf.hasNominalAttribute()){
					Hibernate.initialize(mf.getNominalAttribute().getNominalLabels());
				}
			}
			return new CollectionDTO(crisis);
		} catch (HibernateException e) {
			logger.error("Hibernate initialization error for lazy objects in : " + crisis.getCrisisId());
		}
	}
	return null;
}
 
Example 4
Source File: TestFileScannerDao.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void delete ()
{
   Long id = 1L;
   FileScanner element = dao.read (id);
   Set<Collection> collections = element.getCollections ();
   Hibernate.initialize (collections);
   dao.delete (element);

   assertEquals (dao.count (), (howMany () - 1));
   assertNull (dao.read (id));
   for (Collection collection : collections)
   {
      assertNotNull (cdao.read (collection.getUUID ()));
   }
}
 
Example 5
Source File: ProductServiceImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public ProductSku getSkuById(final Long skuId, final boolean withAttributes) {
    final ProductSku sku =  productSkuService.getGenericDao().findById(skuId);
    if (sku != null && withAttributes) {
        Hibernate.initialize(sku.getAttributes());
    }
    return sku;
}
 
Example 6
Source File: CategoryServiceImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc} Just to cache
 */
@Override
public Category getById(final long pk) {
    final Category cat = getGenericDao().findById(pk);
    Hibernate.initialize(cat);
    return cat;
}
 
Example 7
Source File: CollectionService.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addProductInCollection (Collection collection, Product product)
{
   Hibernate.initialize(collection.getProducts());
   if (!collection.getProducts().contains(product))
   {
      collection.getProducts().add(product);
      collectionDao.update (collection);
   }
}
 
Example 8
Source File: HibernateUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Eager fetch all its collections
 *
 * @param proxy Object to check and unwrap
 * @return fully initialized object
 */
public static <T> T initializeProxy( T proxy )
{
    if ( !Hibernate.isInitialized( proxy ) )
    {
        Hibernate.initialize( proxy );
    }

    Field[] fields = proxy.getClass().getDeclaredFields();

    Arrays.stream( fields )
        .filter( f -> Collection.class.isAssignableFrom( f.getType() ) )
        .forEach( f ->
        {
            try
            {
                PropertyDescriptor pd = new PropertyDescriptor( f.getName(), proxy.getClass() );

                Object persistentObject = pd.getReadMethod().invoke( proxy );

                if ( PersistentCollection.class.isAssignableFrom( persistentObject.getClass() ) )
                {
                    Hibernate.initialize( persistentObject );
                }
            }
            catch ( IllegalAccessException | IntrospectionException | InvocationTargetException e )
            {
                DebugUtils.getStackTrace( e );
            }
        });

    return proxy;
}
 
Example 9
Source File: EJBTestBase.java    From development with Apache License 2.0 5 votes vote down vote up
protected <T> T unproxyEntity(T template) {
    if (template instanceof HibernateProxy) {
        Hibernate.initialize(template);
        template = (T) ((HibernateProxy) template)
                .getHibernateLazyInitializer()
                .getImplementation();
    }
    return template;
}
 
Example 10
Source File: SbiDataSetDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void initialize(SbiDataSet dataset) {
	Hibernate.initialize(dataset.getId());
	Hibernate.initialize(dataset.getCategory());
	Hibernate.initialize(dataset.getTransformer());
	Hibernate.initialize(dataset.getScope());
	Hibernate.initialize(dataset.getFederation());
}
 
Example 11
Source File: CustomerServiceImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Customer getCustomerByToken(final String token) {
    Customer customer = getGenericDao().findSingleByCriteria(" where e.authToken = ?1", token);
    if (customer != null) {
        Hibernate.initialize(customer.getAttributes());
    }
    return customer;
}
 
Example 12
Source File: UserService.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
public Collection<GitCompany> getOrganizations(GitProvider gitProvider) {
    User user = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin().orElse(null)).orElse(null);
    Set<GitCompany> gitCompanies = gitCompanyRepository.findAllByUserAndGitProvider(user, gitProvider.getValue());

    Hibernate.initialize(gitCompanies);
    return gitCompanies;
}
 
Example 13
Source File: DynamicFilterTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testSecondLevelCachedCollectionsFiltering() {
	TestData testData = new TestData();
	testData.prepare();

	Session session = openSession();

	// Force a collection into the second level cache, with its non-filtered elements
	Salesperson sp = ( Salesperson ) session.load( Salesperson.class, testData.steveId );
	Hibernate.initialize( sp.getOrders() );
	CollectionPersister persister = ( ( SessionFactoryImpl ) getSessions() )
	        .getCollectionPersister( Salesperson.class.getName() + ".orders" );
	assertTrue( "No cache for collection", persister.hasCache() );
	CollectionCacheEntry cachedData = ( CollectionCacheEntry ) persister.getCache().getCache()
	        .read( new CacheKey( testData.steveId, persister.getKeyType(), persister.getRole(), EntityMode.POJO, sfi() ) );
	assertNotNull( "collection was not in cache", cachedData );

	session.close();

	session = openSession();
	session.enableFilter( "fulfilledOrders" ).setParameter( "asOfDate", testData.lastMonth.getTime() );
	sp = ( Salesperson ) session.createQuery( "from Salesperson as s where s.id = :id" )
	        .setLong( "id", testData.steveId.longValue() )
	        .uniqueResult();
	assertEquals( "Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size() );

	CollectionCacheEntry cachedData2 = ( CollectionCacheEntry ) persister.getCache().getCache()
	        .read( new CacheKey( testData.steveId, persister.getKeyType(), persister.getRole(), EntityMode.POJO, sfi() ) );
	assertNotNull( "collection no longer in cache!", cachedData2 );
	assertSame( "Different cache values!", cachedData, cachedData2 );

	session.close();

	session = openSession();
	session.enableFilter( "fulfilledOrders" ).setParameter( "asOfDate", testData.lastMonth.getTime() );
	sp = ( Salesperson ) session.load( Salesperson.class, testData.steveId );
	assertEquals( "Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size() );

	session.close();

	// Finally, make sure that the original cached version did not get over-written
	session = openSession();
	sp = ( Salesperson ) session.load( Salesperson.class, testData.steveId );
	assertEquals( "Actual cached version got over-written", 2, sp.getOrders().size() );

	session.close();
	testData.release();
}
 
Example 14
Source File: IndexBuilderLuceneHibernateTxAwareImpl.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected T unproxyEntity(final T entity) {
    Hibernate.initialize(entity);
    return entity;
}
 
Example 15
Source File: NominalAttributeResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public NominalAttributeDTO getAttributeByID(Long attributeID) throws PropertyNotSetException {
	NominalAttribute nominalAttribute = getById(attributeID);
	Hibernate.initialize(nominalAttribute.getNominalLabels()); //loading labels too
	return new NominalAttributeDTO(nominalAttribute);
}
 
Example 16
Source File: SituationTriggerRepository.java    From container with Apache License 2.0 4 votes vote down vote up
@Override
protected void initializeInstance(SituationTrigger instance) {
    Hibernate.initialize(instance.getInputs());
    Hibernate.initialize(instance.getSituations());
    Hibernate.initialize(instance.getSituationTriggerInstances());
}
 
Example 17
Source File: DisplayOptionsActivityController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
    * Gets an options activity from the request (attribute) and forwards to the display JSP.
    */
   @RequestMapping("/DisplayOptionsActivity")
   public String execute(@ModelAttribute OptionsActivityForm form, HttpServletRequest request,
    HttpServletResponse response) {

LearnerProgress learnerProgress = LearningWebUtil.getLearnerProgress(request, learnerService);
var activity = LearningWebUtil.getActivityFromRequest(request, learnerService);
if (!(activity instanceof OptionsActivity)) {
    log.error("activity not OptionsActivity " + activity.getActivityId());
    return "error";
}

OptionsActivity optionsActivity = (OptionsActivity) activity;

form.setActivityID(activity.getActivityId());

List<ActivityURL> activityURLs = new ArrayList<>();
Set<Activity> optionsChildActivities = optionsActivity.getActivities();
Iterator<Activity> i = optionsChildActivities.iterator();
int completedActivitiesCount = 0;
while (i.hasNext()) {
    Activity optionsChildActivity = i.next();
    ActivityURL activityURL = LearningWebUtil.getActivityURL(activityMapping, learnerProgress, optionsChildActivity, false,
	    false);

    if (activityURL.isComplete()) {
	completedActivitiesCount++;

	//create list of activityURLs of all children activities
	if (optionsChildActivity.isSequenceActivity()) {
	    activityURL.setUrl(null);
	    
	    // activity is loaded as proxy due to lazy loading and in order to prevent quering DB we just re-initialize
	    // it here again
	    SequenceActivity optionsChildActivityInit;
	    Hibernate.initialize(activity);
	    if (optionsChildActivity instanceof HibernateProxy) {
		optionsChildActivityInit = (SequenceActivity) ((HibernateProxy) optionsChildActivity).getHibernateLazyInitializer()
			.getImplementation();
	    } else {
		optionsChildActivityInit = (SequenceActivity) optionsChildActivity;
	    }
	    
	    List<ActivityURL> childActivities = new ArrayList<>();
	    for (Activity sequenceChildActivity : optionsChildActivityInit.getActivities()) {
		ActivityURL sequenceActivityURL = LearningWebUtil.getActivityURL(activityMapping,
			learnerProgress, sequenceChildActivity, false, false);
		childActivities.add(sequenceActivityURL);
	    }
	    activityURL.setChildActivities(childActivities);
	}
    }
    activityURLs.add(activityURL);
}
form.setActivityURLs(activityURLs);

if (completedActivitiesCount >= optionsActivity.getMinNumberOfOptionsNotNull().intValue()) {
    form.setMinimumLimitReached(true);
}

if (completedActivitiesCount > 0) {
    form.setHasCompletedActivities(true);
}

if (completedActivitiesCount >= optionsActivity.getMaxNumberOfOptionsNotNull().intValue()) {
    form.setMaxActivitiesReached(true);
}

int minNumberOfOptions = optionsActivity.getMinNumberOfOptions() == null ? 0 : optionsActivity.getMinNumberOfOptions();
form.setMinimum(minNumberOfOptions);
int maxNumberOfOptions = optionsActivity.getMaxNumberOfOptions() == null ? 0 : optionsActivity.getMaxNumberOfOptions();
form.setMaximum(maxNumberOfOptions);
form.setDescription(optionsActivity.getDescription());
form.setTitle(optionsActivity.getTitle());
form.setLessonID(learnerProgress.getLesson().getLessonId());
form.setProgressID(learnerProgress.getLearnerProgressId());

//find activity position within Learning Design and stores it as request attribute.
ActivityPositionDTO positionDTO = learnerService.getActivityPosition(form.getActivityID());
if (positionDTO != null) {
    request.setAttribute(AttributeNames.ATTR_ACTIVITY_POSITION, positionDTO);
}

// lessonId needed for the progress bar
request.setAttribute(AttributeNames.PARAM_LESSON_ID, learnerProgress.getLesson().getLessonId());

return "optionsActivity";
   }
 
Example 18
Source File: CollectionDao.java    From DataHubSystem with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Checks if the collection contains the passed product.
 *
 * @param cid the collection to check.
 * @param pid the product to retrieve in collection.
 * @return true if the product is included in the collection, false
 *         otherwise.
 */
public boolean contains (final String cid, final Long pid)
{
   Collection collection = read(cid);
   Hibernate.initialize (collection.getProducts());
   return collection.getProducts().contains(productDao.read(pid));
}
 
Example 19
Source File: HibernateBasicDao.java    From lemon with Apache License 2.0 2 votes vote down vote up
/**
 * 直接初始化数据,避免出现lazy load错误的一个方法.
 * 
 * @param object
 *            entity
 */
public void initialize(Object object) {
    Assert.notNull(object, "Object cannot be null");
    Hibernate.initialize(object);
}
 
Example 20
Source File: Hibernates.java    From dubai with MIT License 2 votes vote down vote up
/**
 * Initialize the lazy property value.
 * 
 * e.g. Hibernates.initLazyProperty(user.getGroups());
 */
public static void initLazyProperty(Object proxyedPropertyValue) {
	Hibernate.initialize(proxyedPropertyValue);
}