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

The following examples show how to use org.hibernate.Hibernate#initialize() . These examples are extracted from open source projects. 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
@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
@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 3
@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 Project: yes-cart   File: ProductServiceImpl.java    License: 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 5
private void addProductInCollection (Collection collection, Product product)
{
   Hibernate.initialize(collection.getProducts());
   if (!collection.getProducts().contains(product))
   {
      collection.getProducts().add(product);
      collectionDao.update (collection);
   }
}
 
Example 6
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 7
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 8
Source Project: jhipster-online   File: UserService.java    License: 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 9
Source Project: yes-cart   File: CustomerServiceImpl.java    License: 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 10
Source Project: development   File: EJBTestBase.java    License: 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 11
/**
 * 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 12
Source Project: yes-cart   File: CategoryServiceImpl.java    License: 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 13
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
/**
    * 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 15
@Override
protected void initializeInstance(SituationTrigger instance) {
    Hibernate.initialize(instance.getInputs());
    Hibernate.initialize(instance.getSituations());
    Hibernate.initialize(instance.getSituationTriggerInstances());
}
 
Example 16
@Override
public NominalAttributeDTO getAttributeByID(Long attributeID) throws PropertyNotSetException {
	NominalAttribute nominalAttribute = getById(attributeID);
	Hibernate.initialize(nominalAttribute.getNominalLabels()); //loading labels too
	return new NominalAttributeDTO(nominalAttribute);
}
 
Example 17
/** {@inheritDoc} */
@Override
protected T unproxyEntity(final T entity) {
    Hibernate.initialize(entity);
    return entity;
}
 
Example 18
/**
 * 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 Project: lemon   File: HibernateBasicDao.java    License: 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 Project: dubai   File: Hibernates.java    License: 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);
}