Java Code Examples for org.hibernate.Hibernate

The following are top voted examples for showing how to use org.hibernate.Hibernate. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Equella   File: ItemDefinitionServiceImpl.java   View source code 7 votes vote down vote up
@Override
protected ComparisonEntityInitialiser<ItemDefinition> getComparisonInitialiserForStopEdit()
{
	return new ComparisonEntityInitialiser<ItemDefinition>()
	{
		@Override
		public void preUnlink(ItemDefinition t)
		{
			// We suck the big one for misusing hibernate.
			initBundle(t.getName());
			initBundle(t.getDescription());
			t.getItemMetadataRules();
			Hibernate.initialize(t.getWorkflow());
		}
	};
}
 
Example 2
Project: tipi-engine   File: BlobFactory.java   View source code 6 votes vote down vote up
/**
	 * Permet de créer un Blob à partir d'un stream sans indiquer/connaître la taille. Fonctionne uniquement avec jdbc4. Une exception est
	 * lancée si jdbc4 n'est pas présent.
	 * 
	 * @param aInputStream
	 * @return
	 */
	public Blob createBlob(InputStream aInputStream) {

		final LobCreator lobCreator = Hibernate.getLobCreator(session);
//		// JDBC4 -> pas besoin de la taille
//		if (lobCreator instanceof ContextualLobCreator) {
//			// Passage de -1 comme taille: De toutes façons cette valeur n'est pas utilisée en jdbc4
//			return lobCreator.createBlob(aInputStream, -1);
//		}
//		else {
			// Fallback JDBC3
			// On récupère le stream pour connaitre la taille
			final ByteArrayOutputStream bos = new ByteArrayOutputStream();
			try {
				IOUtils.copy(aInputStream, bos);
				return lobCreator.createBlob(new ByteArrayInputStream(bos.toByteArray()), bos.size());
			}
			catch (IOException ioe) {
				throw new RuntimeException(ioe);
			}
//		}
	}
 
Example 3
Project: dhus-core   File: CollectionDao.java   View source code 6 votes vote down vote up
/**
 * Remove a product from a collection. The product should stay in the
 * database.
 *
 * @param cid the collection id where remove product.
 * @param pid the product id to remove.
 * @param user unused parameter.
 */
public void removeProduct (final String cid, final Long pid, User user)
{
   Collection collection = read(cid);
   if (collection == null)
   {
      LOGGER.warn("Unknown collection #" + cid);
      return;
   }
   Product product = productDao.read(pid);
   if (product == null)
   {
      LOGGER.warn("Unknown product #" + pid);
      return;
   }

   Hibernate.initialize (collection.getProducts());
   collection.getProducts().remove(product);
   update(collection);

   fireProductRemoved (new DaoEvent<> (collection), product);
}
 
Example 4
Project: dhus-core   File: TestFileScannerDao.java   View source code 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
Project: dhus-core   File: TestEvictionDao.java   View source code 6 votes vote down vote up
@Override
@Test (dependsOnMethods = { "read", "create" })
public void delete ()
{
   long id = 1;
   Eviction eviction = dao.read (id);
   Set<Product> ps = eviction.getProducts ();
   Hibernate.initialize (ps);

   dao.delete (eviction);
   assertEquals (dao.count (), (howMany () - 1));
   assertNull (dao.read (id));
   for (Product p : ps)
   {
      assertNotNull (pdao.read (p.getId ()));
   }
}
 
Example 6
Project: oscm   File: EJBTestBase.java   View source code 6 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 7
Project: Celebino   File: GenericDao.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public T getById(Long pk) throws SQLException {
	Session session = HibernateUtil.getSessionFactory().openSession();
	T entity = null;

	try {
		session.beginTransaction();
		entity = (T) session.get(getEntityClass(), pk);
		Hibernate.initialize(entity);
		session.getTransaction().commit();

	} catch (HibernateException hibernateException) {
		session.getTransaction().rollback();

		throw new SQLException(hibernateException);

	} finally {
		session.close();
	}

	return entity;
}
 
Example 8
Project: Equella   File: HibernateEscapedString.java   View source code 6 votes vote down vote up
@Override
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException
{
	String dbValue = Hibernate.STRING.nullSafeGet(rs, names[0]);
	if( dbValue != null )
	{
		return unescape(dbValue);
	}
	else
	{
		return null;
	}
}
 
Example 9
Project: Equella   File: MimeTypeServiceImpl.java   View source code 6 votes vote down vote up
private EntryCache createMappings(List<MimeEntry> entries)
{
	Map<String, MimeEntry> mappedEntries = new HashMap<String, MimeEntry>();
	Map<String, MimeEntry> mimeEntries = new HashMap<String, MimeEntry>();
	for( MimeEntry mimeEntry : entries )
	{
		Collection<String> extensions = mimeEntry.getExtensions();
		// Load it all up
		Hibernate.initialize(mimeEntry.getAttributes());
		for( String ext : extensions )
		{
			mappedEntries.put(ext, mimeEntry);
		}
		mimeEntries.put(mimeEntry.getType(), mimeEntry);
	}
	return new EntryCache(mappedEntries, mimeEntries);
}
 
Example 10
Project: lams   File: StatefulPersistenceContext.java   View source code 6 votes vote down vote up
@Override
public boolean reassociateIfUninitializedProxy(Object value) throws MappingException {
	if ( value instanceof ElementWrapper ) {
		value = ( (ElementWrapper) value ).getElement();
	}

	if ( !Hibernate.isInitialized( value ) ) {
		final HibernateProxy proxy = (HibernateProxy) value;
		final LazyInitializer li = proxy.getHibernateLazyInitializer();
		reassociateProxy( li, proxy );
		return true;
	}
	else {
		return false;
	}
}
 
Example 11
Project: lams   File: ByteArrayBlobType.java   View source code 6 votes vote down vote up
protected void set(PreparedStatement st, Object value, int index, SessionImplementor session) throws SQLException {
	if ( value == null ) {
		st.setNull( index, sqlTypes( null )[0] );
	}
	else {
		byte[] toSet = unWrap( value );
		final boolean useInputStream = session.getFactory().getDialect().useInputStreamToInsertBlob();

		if ( useInputStream ) {
			st.setBinaryStream( index, new ByteArrayInputStream( toSet ), toSet.length );
		}
		else {
			st.setBlob( index, Hibernate.getLobCreator( session ).createBlob( toSet ) );
		}
	}
}
 
Example 12
Project: lams   File: AbstractStandardBasicType.java   View source code 6 votes vote down vote up
private WrapperOptions getOptions(final SessionImplementor session) {
	return new WrapperOptions() {
		public boolean useStreamForLobBinding() {
			return Environment.useStreamsForBinary()
					|| session.getFactory().getDialect().useInputStreamToInsertBlob();
		}

		public LobCreator getLobCreator() {
			return Hibernate.getLobCreator( session );
		}

		public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
			final SqlTypeDescriptor remapped = sqlTypeDescriptor.canBeRemapped()
					? session.getFactory().getDialect().remapSqlTypeDescriptor( sqlTypeDescriptor )
					: sqlTypeDescriptor;
			return remapped == null ? sqlTypeDescriptor : remapped;
		}
	};
}
 
Example 13
Project: ctsms   File: ECRFFieldStatusEntryDaoImpl.java   View source code 6 votes vote down vote up
private static DetachedCriteria createEcrfFieldStatusEntryDetachedCriteriaMaxId(org.hibernate.Criteria ecrfFieldStatusEntryCriteria, org.hibernate.Criteria ecrfFieldCriteria,
		org.hibernate.Criteria probandListEntryCriteria,
		ECRFFieldStatusQueue queue, Long probandListEntryId, Long ecrfFieldId) {
	DetachedCriteria subQuery = createEcrfFieldStatusEntryDetachedCriteria(ecrfFieldStatusEntryCriteria, ecrfFieldCriteria, probandListEntryCriteria, probandListEntryId,
			ecrfFieldId);
	if (queue != null) {
		subQuery.add(Restrictions.eq("queue", queue));
		subQuery.setProjection(Projections.max("id"));
	} else {
		ProjectionList proj = Projections.projectionList();
		proj.add(Projections.sqlGroupProjection(
				"max({alias}.id) as maxId",
				"{alias}.queue",
				new String[] { "maxId" },
				new org.hibernate.type.Type[] { Hibernate.LONG }));
		subQuery.setProjection(proj);
	}

	return subQuery;
}
 
Example 14
Project: oma-riista-web   File: Person.java   View source code 6 votes vote down vote up
@Nonnull
public LocalisedString getHomeMunicipalityName() {
    if (this.homeMunicipality != null) {
        if (!Hibernate.isInitialized(this.homeMunicipality)) {
            try {
                // Referenced row might not exist
                return this.homeMunicipality.getNameLocalisation();
            } catch (UnresolvableObjectException | EntityNotFoundException o) {
                this.homeMunicipality = null;
            }
        } else {
            return this.homeMunicipality.getNameLocalisation();
        }
    }
    return LocalisedString.EMPTY;
}
 
Example 15
Project: OSCAR-ConCert   File: ProviderDao.java   View source code 6 votes vote down vote up
public List getShelterIds(String provider_no)
{
	
	String sql ="select distinct c.id as shelter_id from lst_shelter c, lst_orgcd a, secUserRole b  where instr('RO',substr(b.orgcd,1,1)) = 0 and a.codecsv like '%' || b.orgcd || ',%'" +
			" and b.provider_no=? and a.codecsv like '%S' || c.id  || ',%'";
	Session session = getSession();
	
	Query query = session.createSQLQuery(sql);
   	((SQLQuery) query).addScalar("shelter_id", Hibernate.INTEGER);
   	query.setString(0, provider_no);
   	List lst = new ArrayList();
   	try {
   		lst=query.list();
   	}finally {
   		this.releaseSession(session);
   	}
       return lst;

}
 
Example 16
Project: facepalm   File: JPAImageRepository.java   View source code 6 votes vote down vote up
@Override
public void addImagePost(final Title title, final byte[] data) {
    final Session session = entityManager.unwrap(Session.class);
    final Blob blob = Hibernate.getLobCreator(session).createBlob(data);

    final StoredImage storedImage = new StoredImage();
    storedImage.setData(blob);

    final ImagePost imagePost = ImagePost.builder()
            .withPoints(0L)
            .withNumComments(0L)
            .withTitle(title)
            .withStoredImage(storedImage)
            .build();

    entityManager.persist(imagePost);
}
 
Example 17
Project: bisis-v4   File: GetUsersForArchiveCommand.java   View source code 6 votes vote down vote up
@Override
public void execute() {
	try{
		Transaction tx = session.beginTransaction();

		String query = "SELECT distinct(u.user_id) FROM users u,signing s where u.sys_id=s.sys_id and :date > all(select s1.until_date from signing s1 where u.sys_id=s1.sys_id) and not exists (select l.sys_id from lending l where l.sys_id = u.sys_id and return_date is null)";
		Query q = session.createSQLQuery(query);
		q.setParameter("date",date, Hibernate.DATE);
		list = q.list();
		query = "SELECT u.user_id FROM users u where not exists(select s.sys_id from signing s where u.sys_id=s.sys_id) and not exists (select l.sys_id from lending l where l.sys_id = u.sys_id and return_date is null)";
		q = session.createSQLQuery(query);
		list.addAll(q.list());
		tx.commit();
	}catch (Exception e){
		log.error(e);
	}
}
 
Example 18
Project: bisis-v4   File: GetChargedUserCommand.java   View source code 6 votes vote down vote up
@Override
public void execute() {
	try{
		Transaction tx = session.beginTransaction();
		SQLQuery q = session.createSQLQuery("select sys_id from lending l where l.return_date is null and l.ctlg_no = :ctlgno");
		q.setString("ctlgno", ctlgno);
		Iterator it = q.list().iterator();
		if (it.hasNext()){
			Integer sysid = (Integer)it.next();
			q = session.createSQLQuery("select user_id, first_name, last_name from users u where u.sys_id = :sysid")
			.addScalar("user_id", Hibernate.STRING).addScalar("first_name", Hibernate.STRING).addScalar("last_name", Hibernate.STRING);
			q.setInteger("sysid", sysid);
			it = q.list().iterator();
			if (it.hasNext()){
				user = (Object[])it.next();
			}
		}
		tx.commit();
	}catch (Exception e){
		log.error("loading chargde user failed");
		log.error(e);
	}
}
 
Example 19
Project: bisis-v4   File: Statistic1ReportCommand.java   View source code 6 votes vote down vote up
@Override
public void execute() {
	try{
	 Transaction tx = session.beginTransaction();
	 Query crt;
	 if (!location.equals(" ")) {
			String loc = ((Location) location).getName();
			String query1 = "select count(*)  from Users u inner join u. signings as s where "
					+ " (s.location.name= :loc) and  (s.signDate between :start and :end)";
			crt = session.createQuery(query1).setParameter("start", start,Hibernate.TIMESTAMP).setParameter("end", end,Hibernate.TIMESTAMP).setString("loc", loc);
		} else {
			String query2 = "select count(*)  from Users u inner join u. signings as s where "
					+ " (s.signDate between :start and :end)";
			crt = session.createQuery(query2).setParameter("start", start,Hibernate.TIMESTAMP).setParameter("end", end,Hibernate.TIMESTAMP);
		}
		if (crt != null) {
			list = crt.list();
		}
	  tx.commit();
	  log.info("Statistic1 report");
	}catch (Exception e){
		log.error("Statistic1 report failed");
		log.error(e);
	}
}
 
Example 20
Project: communote-server   File: ConfigurationManagementImpl.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @see com.communote.server.core.ConfigurationManagementBase#handleGetClientLogo()
 */
@Override
protected ImageVO handleGetClientLogo() {
    Configuration configuration = handleGetConfiguration();
    ImageVO result = null;
    ClientConfiguration clientConfig = configuration.getClientConfig();
    if (clientConfig != null) {
        if (!Hibernate.isInitialized(clientConfig.getLogoImage())) {
            Hibernate.initialize(clientConfig.getLogoImage());
        }
        if (clientConfig.getLogoImage() != null) {
            result = new ImageVO();
            result.setImage(configuration.getClientConfig().getLogoImage());
            Timestamp date = configuration.getClientConfig().getLastLogoImageModificationDate();
            // use timestamp 0 if it is not yet set due to migration
            result.setLastModificationDate(date == null ? new Date(0) : date);
        }
    }
    return result;
}
 
Example 21
Project: bisis-v4   File: Statistic8ReportCommand.java   View source code 6 votes vote down vote up
@Override
public void execute() {
	try{
	 Transaction tx = session.beginTransaction();
	 Query crt;
	 if (!location.equals(" ")) {
			String loc = ((Location) location).getName();
			String query1 = "select distinct l.ctlgNo  from Lending l  where "
					+ " (l.location.name= :loc) and (l.resumeDate between :start and :end) ";
			crt = session.createQuery(query1).setParameter("start", start,Hibernate.TIMESTAMP).setParameter("end", end,Hibernate.TIMESTAMP).setString("loc", loc);
		} else {
			String query2 = "select distinct l.ctlgNo  from Lending l  where "
				+ " (l.resumeDate between :start and :end) ";
			crt = session.createQuery(query2).setParameter("start", start,Hibernate.TIMESTAMP).setParameter("end", end,Hibernate.TIMESTAMP);
		}
		if (crt != null) {
			list = crt.list();
		}
	  tx.commit();
	  log.info("Statistic8 report");
	}catch (Exception e){
		log.error("Statistic8 report failed");
		log.error(e);
	}
}
 
Example 22
Project: GitHub   File: ForceLazyLoadingTest.java   View source code 5 votes vote down vote up
public void testGetCustomerJson() throws Exception {

        EntityManager em = emf.createEntityManager();

        // false -> no forcing of lazy loading


        Customer customer = em.find(Customer.class, 103);
        assertFalse(Hibernate.isInitialized(customer.getPayments()));
        String json = JSON.toJSONString(customer);
        System.out.println(json);
        // should force loading...
//            Set<Payment> payments = customer.getPayments();
//            /*
//            System.out.println("--- JSON ---");
//            System.out.println(json);
//            System.out.println("--- /JSON ---");
//            */
//
//            assertTrue(Hibernate.isInitialized(payments));
//            // TODO: verify
//            assertNotNull(json);
//
//            Map<?,?> stuff = mapper.readValue(json, Map.class);
//
//            assertTrue(stuff.containsKey("payments"));
//            assertTrue(stuff.containsKey("orders"));
//            assertNull(stuff.get("orderes"));

    }
 
Example 23
Project: document-management-store-app   File: BlobCreator.java   View source code 5 votes vote down vote up
protected Blob createBlob(MultipartFile file) {
    try {
        Session session = entityManager.unwrap(Session.class);
        return Hibernate.getLobCreator(session).createBlob(file.getInputStream(), file.getSize());
    } catch (Exception e) {
        throw new CantCreateBlobException(e);
    }
}
 
Example 24
Project: BLOG-Microservice   File: HibernateSerializerFactory.java   View source code 5 votes vote down vote up
@Override
public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
    boolean init = Hibernate.isInitialized(obj);

    out.writeObject(init ? obj : null);
    out.flush();
    return;
}
 
Example 25
Project: BLOG-Microservice   File: HibernateSerializerFactory.java   View source code 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
    if (Hibernate.isInitialized(obj)) {
        delegate.writeObject(new ArrayList((Collection) obj), out);
    } else {
        delegate.writeObject(new ArrayList(), out);
    }
}
 
Example 26
Project: BLOG-Microservice   File: HibernateSerializerFactory.java   View source code 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
    if (Hibernate.isInitialized(obj)) {
        delegate.writeObject(new HashMap((Map) obj), out);
    } else {
        delegate.writeObject(new HashMap(), out);
    }
}
 
Example 27
Project: opencron   File: UploadDao.java   View source code 5 votes vote down vote up
public User uploadimg(File file, Long userId) throws IOException {
    Session session = getSession();
    User loginUser =  get(User.class,userId);
    loginUser.setHeaderpic(Hibernate.getLobCreator(session).createBlob(IOUtils.readFileToArray(file)));
    //图像文件的后缀名
    loginUser.setPicExtName(file.getName().substring(file.getName().lastIndexOf(".")));
    session.save(loginUser);
    return loginUser;
}
 
Example 28
Project: FeedbackCollectionAndMgmtSystem   File: StudentDaoImpl.java   View source code 5 votes vote down vote up
@Override
public StudentUser findStudentByEmail(String email) {
    logger.info("email : {}", email);
    Criteria crit = createEntityCriteria();
    crit.add(Restrictions.eq("email", email));
    StudentUser user = (StudentUser) crit.uniqueResult();
    if (user != null) {
        Hibernate.initialize(user.getUserRoles());
    }
    return user;
}
 
Example 29
Project: FeedbackCollectionAndMgmtSystem   File: UserDaoImpl.java   View source code 5 votes vote down vote up
public AdmUser findById(int id) {
    AdmUser user = getByKey(id);
    if (user != null) {
        Hibernate.initialize(user.getUserRoles());
    }
    return user;
}
 
Example 30
Project: FeedbackCollectionAndMgmtSystem   File: UserDaoImpl.java   View source code 5 votes vote down vote up
public AdmUser findBySSO(String email) {
    logger.info("email : {}", email);
    Criteria crit = createEntityCriteria();
    crit.add(Restrictions.eq("email", email));
    AdmUser user = (AdmUser) crit.uniqueResult();
    if (user != null) {
        Hibernate.initialize(user.getUserRoles());
    }
    return user;
}
 
Example 31
Project: dhus-core   File: ProductService.java   View source code 5 votes vote down vote up
@Transactional (readOnly=true, propagation=Propagation.REQUIRED)
@Cacheable (value = {"indexes"}, key = "#product_id")
public List<MetadataIndex> getIndexes(Long product_id)
{
   Product product = productDao.read (product_id);
   if (product == null) return new ArrayList<MetadataIndex> ();
   Hibernate.initialize (product.getIndexes ());
   return product.getIndexes ();
}
 
Example 32
Project: dhus-core   File: ProductService.java   View source code 5 votes vote down vote up
@Transactional (readOnly=true, propagation=Propagation.REQUIRED)
public Product getProductWithIndexes(Long product_id)
{
   Product product = productDao.read (product_id);
   if (product == null) return null;
   Hibernate.initialize (product.getIndexes ());
   return product;
}
 
Example 33
Project: dhus-core   File: ProductCartService.java   View source code 5 votes vote down vote up
/**
 * Get the cart of the related user. If the user has no cart configured, null
 * is returned.
 * @param uuid the related user to retrieve the cart.
 * @return the cart
 * @throws UserNotExistingException when passed user is unknown.
 */
@PreAuthorize ("hasRole('ROLE_DOWNLOAD')")
@Transactional (readOnly=true, propagation=Propagation.REQUIRED)
public ProductCart getCartOfUser(String uuid) throws UserNotExistingException
{
   User user = getUser (uuid);
   ProductCart pc = productCartDao.getCartOfUser(user);
   if (pc != null)
   {
      Hibernate.initialize(pc.getProducts());
   }
   return pc;
}
 
Example 34
Project: crnk-framework   File: BasicQueryTestBase.java   View source code 5 votes vote down vote up
@Test
public void testWithGraphControlWithoutJoin() {
	JpaQueryExecutor<TestEntity> exec = builder().buildExecutor().fetch(Arrays.asList(TestEntity.ATTR_oneRelatedValue));
	for (TestEntity test : exec.getResultList()) {
		assertTrue(Hibernate.isInitialized(test));

		RelatedEntity relatedValue = test.getOneRelatedValue();
		if (relatedValue != null) {
			assertTrue(Hibernate.isInitialized(relatedValue));
		}
	}
}
 
Example 35
Project: crnk-framework   File: BasicQueryTestBase.java   View source code 5 votes vote down vote up
@Test
public void testWithGraphControlWithJoin() {
	JpaQueryExecutor<TestEntity> exec = builder().addFilter(TestEntity.ATTR_oneRelatedValue, FilterOperator.NEQ, null).buildExecutor().fetch(Arrays.asList(TestEntity.ATTR_oneRelatedValue));
	for (TestEntity test : exec.getResultList()) {
		assertTrue(Hibernate.isInitialized(test));
		assertTrue(Hibernate.isInitialized(test.getOneRelatedValue()));
	}
}
 
Example 36
Project: crnk-framework   File: BasicQueryTestBase.java   View source code 5 votes vote down vote up
@Test
public void testWithoutGraphControl() {
	JpaQueryExecutor<TestEntity> exec = builder().addFilter(TestEntity.ATTR_oneRelatedValue, FilterOperator.NEQ, null).buildExecutor();
	for (TestEntity test : exec.getResultList()) {
		RelatedEntity relatedValue = test.getOneRelatedValue();
		assertTrue(Hibernate.isInitialized(test));
		assertFalse(Hibernate.isInitialized(relatedValue));
	}
}
 
Example 37
Project: crnk-framework   File: JpaEntityRepositoryTestBase.java   View source code 5 votes vote down vote up
@Test
public void testIncludeNoRelations() throws InstantiationException, IllegalAccessException {
	em.clear();
	List<TestEntity> list = repo.findAll(new QuerySpec(TestEntity.class));
	Assert.assertEquals(numTestEntities, list.size());
	for (TestEntity entity : list) {
		RelatedEntity relatedValue = entity.getOneRelatedValue();
		if (relatedValue != null)
			Assert.assertFalse(Hibernate.isInitialized(relatedValue));
	}
}
 
Example 38
Project: chr-krenn-fhj-ws2017-sd17-pse   File: UserDAOImpl.java   View source code 5 votes vote down vote up
private User initializeUser(User u) {
    Hibernate.initialize(u.getLikes());
    Hibernate.initialize(u.getCommunities());
    Hibernate.initialize(u.getRoles());
    Hibernate.initialize(u.getUserContacts());
    Hibernate.initialize(u.getPrivateMessagesReceiver());
    Hibernate.initialize(u.getPrivateMessagesSender());
    return u;
}
 
Example 39
Project: xm-ms-entity   File: AttachmentService.java   View source code 5 votes vote down vote up
/**
 *  Get one attachment by id.
 *
 * @param id the id of the entity
 * @return the entity
 */
@Transactional(readOnly = true)
public Attachment findOneWithContent(Long id) {
    log.debug("Request to get Attachment : {}", id);
    Attachment attachment = attachmentRepository.findOne(id);
    if (attachment != null) {
        Hibernate.initialize(attachment.getContent());
    }
    return attachment;
}
 
Example 40
Project: testing_security_development_enterprise_systems   File: Ejb.java   View source code 5 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;
    }