org.hibernate.Hibernate Java Examples

The following examples show how to use org.hibernate.Hibernate. 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: CourseManagementAdministrationHibernateImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private MembershipCmImpl getMembership(final String userId, final AbstractMembershipContainerCmImpl container) {
	final String lcUserId = StringUtils.lowerCase(userId);
	// This may be a dynamic proxy.  In that case, make sure we're using the class
	// that hibernate understands.
	final String className = Hibernate.getClass(container).getName();

	final StringBuilder sb = new StringBuilder("select mbr from MembershipCmImpl as mbr, ");
	sb.append(className);
       sb.append(" as container where mbr.memberContainer=container ");
       sb.append("and container.eid=:eid ");
   	sb.append("and mbr.userId=:userId");
   	
	HibernateCallback hc = new HibernateCallback() {
		public Object doInHibernate(Session session) throws HibernateException {
			Query q = session.createQuery(sb.toString());
			q.setParameter("eid", container.getEid());
			q.setParameter("userId", lcUserId);
			return q.uniqueResult();
		}
	};
	return (MembershipCmImpl)getHibernateTemplate().execute(hc);
}
 
Example #2
Source File: UnconstrainedTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testUnconstrained() {
	Session session = openSession();
	Transaction tx = session.beginTransaction();
	Person p = new Person("gavin");
	p.setEmployeeId("123456");
	session.persist(p);
	tx.commit();
	session.close();
	
	session = openSession();
	tx = session.beginTransaction();
	p = (Person) session.get(Person.class, "gavin");
	assertNull( p.getEmployee() );
	p.setEmployee( new Employee("123456") );
	tx.commit();
	session.close();

	session = openSession();
	tx = session.beginTransaction();
	p = (Person) session.get(Person.class, "gavin");
	assertTrue( Hibernate.isInitialized( p.getEmployee() ) );
	assertNotNull( p.getEmployee() );
	session.delete(p);
	tx.commit();
	session.close();
}
 
Example #3
Source File: ECRFFieldStatusEntryDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 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 #4
Source File: UserRatingsDaoImpl.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
*/
  @Override
  public int deleteAllRatings(OLATResourceable olatResourceable, String resourceableSubPath) {
      String query;
      Object[] values;
      Type[] types;
      // special query when sub path is null
      if (resourceableSubPath == null) {
          query = "from UserRatingImpl where resName=? AND resId=? AND resSubPath is NULL";
          values = new Object[] { olatResourceable.getResourceableTypeName(), olatResourceable.getResourceableId() };
          types = new Type[] { Hibernate.STRING, Hibernate.LONG };
      } else {
          query = "from UserRatingImpl where resName=? AND resId=? AND resSubPath=?";
          values = new Object[] { olatResourceable.getResourceableTypeName(), olatResourceable.getResourceableId(), resourceableSubPath };
          types = new Type[] { Hibernate.STRING, Hibernate.LONG, Hibernate.STRING };
      }
      return database.delete(query, values, types);
  }
 
Example #5
Source File: TaskPropertyColumn.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
protected TaskDO getTask(final IModel<T> rowModel)
{
  final Object obj = BeanHelper.getNestedProperty(rowModel.getObject(), getPropertyExpression());
  TaskDO task = null;
  if (obj != null) {
    if (obj instanceof TaskDO) {
      task = (TaskDO) obj;
      if (Hibernate.isInitialized(task) == false) {
        task = Registry.instance().getTaskTree().getTaskById(task.getId());
      }
    } else if (obj instanceof Integer) {
      Validate.notNull(taskTree);
      final Integer taskId = (Integer) obj;
      task = taskTree.getTaskById(taskId);
    } else {
      throw new IllegalStateException("Unsupported column type: " + obj);
    }
  }
  return task;
}
 
Example #6
Source File: TaggingDaoImpl.java    From olat with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteTags(OLATResourceable ores, String subPath, String businessPath) {
    List<Object> values = new ArrayList<Object>();
    List<Type> types = new ArrayList<Type>();
    StringBuilder sb = new StringBuilder();
    sb.append("from ").append(TagImpl.class.getName()).append(" where resId=? and resName=?");
    values.add(ores.getResourceableId());
    types.add(Hibernate.LONG);
    values.add(ores.getResourceableTypeName());
    types.add(Hibernate.STRING);
    if (subPath != null) {
        sb.append(" and resSubPath=?");
        values.add(subPath);
        types.add(Hibernate.STRING);
    }
    if (businessPath != null) {
        sb.append(" and businessPath=?");
        values.add(businessPath);
        types.add(Hibernate.STRING);
    }

    int tagsDeleted = database.delete(sb.toString(), values.toArray(new Object[values.size()]), types.toArray(new Type[types.size()]));
    log.info("Audit:Deleted " + tagsDeleted + " tags of resource: " + ores.getResourceableTypeName() + " :: " + ores.getResourceableId());
}
 
Example #7
Source File: CourseManagementAdministrationHibernateImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private MembershipCmImpl getMembership(final String userId, final AbstractMembershipContainerCmImpl container) {
	final String lcUserId = StringUtils.lowerCase(userId);
	// This may be a dynamic proxy.  In that case, make sure we're using the class
	// that hibernate understands.
	final String className = Hibernate.getClass(container).getName();

	final StringBuilder sb = new StringBuilder("select mbr from MembershipCmImpl as mbr, ");
	sb.append(className);
       sb.append(" as container where mbr.memberContainer=container ");
       sb.append("and container.eid=:eid ");
   	sb.append("and mbr.userId=:userId");
   	
	HibernateCallback hc = new HibernateCallback() {
		public Object doInHibernate(Session session) throws HibernateException {
			Query q = session.createQuery(sb.toString());
			q.setParameter("eid", container.getEid());
			q.setParameter("userId", lcUserId);
			return q.uniqueResult();
		}
	};
	return (MembershipCmImpl)getHibernateTemplate().execute(hc);
}
 
Example #8
Source File: UserCommentsDaoImpl.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
*/
  public int deleteAllComments(OLATResourceable olatResourceable, String resourceableSubPath) {
      String query;
      Object[] values;
      Type[] types;
      // special query when sub path is null
      if (resourceableSubPath == null) {
          query = "from UserCommentImpl where resName=? AND resId=? AND resSubPath is NULL";
          values = new Object[] { olatResourceable.getResourceableTypeName(), olatResourceable.getResourceableId() };
          types = new Type[] { Hibernate.STRING, Hibernate.LONG };
      } else {
          query = "from UserCommentImpl where resName=? AND resId=? AND resSubPath=?";
          values = new Object[] { olatResourceable.getResourceableTypeName(), olatResourceable.getResourceableId(), resourceableSubPath };
          types = new Type[] { Hibernate.STRING, Hibernate.LONG, Hibernate.STRING };
      }
      return db.delete(query, values, types);
  }
 
Example #9
Source File: BaseSecurityManager.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
*/
  @Override
  public Authentication findAuthentication(final Identity identity, final String provider) {
      if (identity == null) {
          throw new IllegalArgumentException("identity must not be null");
      }
      final List results = database.find("select auth from org.olat.data.basesecurity.AuthenticationImpl as auth where auth.identity.key = ? and auth.provider = ?",
              new Object[] { identity.getKey(), provider }, new Type[] { Hibernate.LONG, Hibernate.STRING });
      if (results == null || results.size() == 0) {
          return null;
      }
      if (results.size() > 1) {
          throw new AssertException("Found more than one Authentication for a given subject and a given provider.");
      }
      return (Authentication) results.get(0);
  }
 
Example #10
Source File: ArrayType.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String toLoggableString(Object value, SessionFactoryImplementor factory) throws HibernateException {
	if ( value == null ) {
		return "null";
	}
	int length = Array.getLength(value);
	List list = new ArrayList(length);
	Type elemType = getElementType(factory);
	for ( int i=0; i<length; i++ ) {
		Object element = Array.get(value, i);
		if ( element == LazyPropertyInitializer.UNFETCHED_PROPERTY || !Hibernate.isInitialized( element ) ) {
			list.add( "<uninitialized>" );
		}
		else {
			list.add( elemType.toLoggableString( element, factory ) );
		}
	}
	return list.toString();
}
 
Example #11
Source File: EntityGraphJpaRepositoryTest.java    From spring-data-jpa-entity-graph with MIT License 5 votes vote down vote up
@Transactional
@Test
public void
    given_default_eg_when_findByBarcode_with_eg_annotation_on_brand_eg_then_brand_should_be_loaded() {
  Product product = productRepository.findByBarcode("1111");
  assertThat(product).isNotNull();
  assertThat(Hibernate.isInitialized(product.getBrand())).isTrue();
}
 
Example #12
Source File: BinaryArithmeticOperatorNode.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Type resolveDataType() {
	// TODO : we may also want to check that the types here map to exactly one column/JDBC-type
	//      can't think of a situation where arithmetic expression between multi-column mappings
	//      makes any sense.
	Node lhs = getLeftHandOperand();
	Node rhs = getRightHandOperand();
	Type lhType = ( lhs instanceof SqlNode ) ? ( ( SqlNode ) lhs ).getDataType() : null;
	Type rhType = ( rhs instanceof SqlNode ) ? ( ( SqlNode ) rhs ).getDataType() : null;
	if ( isDateTimeType( lhType ) || isDateTimeType( rhType ) ) {
		return resolveDateTimeArithmeticResultType( lhType, rhType );
	}
	else {
		if ( lhType == null ) {
			if ( rhType == null ) {
				// we do not know either type
				return Hibernate.DOUBLE; //BLIND GUESS!
			}
			else {
				// we know only the rhs-hand type, so use that
				return rhType;
			}
		}
		else {
			if ( rhType == null ) {
				// we know only the lhs-hand type, so use that
				return lhType;
			}
			else {
				if ( lhType==Hibernate.DOUBLE || rhType==Hibernate.DOUBLE ) return Hibernate.DOUBLE;
				if ( lhType==Hibernate.FLOAT || rhType==Hibernate.FLOAT ) return Hibernate.FLOAT;
				if ( lhType==Hibernate.BIG_DECIMAL || rhType==Hibernate.BIG_DECIMAL ) return Hibernate.BIG_DECIMAL;
				if ( lhType==Hibernate.BIG_INTEGER || rhType==Hibernate.BIG_INTEGER ) return Hibernate.BIG_INTEGER;
				if ( lhType==Hibernate.LONG || rhType==Hibernate.LONG ) return Hibernate.LONG;
				if ( lhType==Hibernate.INTEGER || rhType==Hibernate.INTEGER ) return Hibernate.INTEGER;
				return lhType;
			}
		}
	}
}
 
Example #13
Source File: BackrefCompositeMapKeyTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testOrphanDelete() {
	Session session = openSession();
	Transaction t = session.beginTransaction();
	Product prod = new Product( "Widget" );
	Part part = new Part( "Widge", "part if a Widget" );
	MapKey mapKey = new MapKey( "Top" );
	prod.getParts().put( mapKey, part );
	Part part2 = new Part( "Get", "another part if a Widget" );
	prod.getParts().put( new MapKey( "Bottom" ), part2 );
	session.persist( prod );
	t.commit();
	session.close();

	getSessions().evict(Product.class);
	getSessions().evict(Part.class);

	session = openSession();
	t = session.beginTransaction();
	prod = (Product) session.get(Product.class, "Widget");
	assertTrue( Hibernate.isInitialized( prod.getParts() ) );
	part = (Part) session.get(Part.class, "Widge");
	prod.getParts().remove(mapKey);
	t.commit();
	session.close();

	getSessions().evict(Product.class);
	getSessions().evict(Part.class);

	session = openSession();
	t = session.beginTransaction();
	prod = (Product) session.get(Product.class, "Widget");
	assertTrue( Hibernate.isInitialized( prod.getParts() ) );
	assertNull( prod.getParts().get(new MapKey("Top")));
	assertNotNull( session.get(Part.class, "Get") );
	session.delete( session.get(Product.class, "Widget") );
	t.commit();
	session.close();
}
 
Example #14
Source File: AbstractGeneratedPropertyTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public final void testGeneratedProperty() {
	GeneratedPropertyEntity entity = new GeneratedPropertyEntity();
	entity.setName( "entity-1" );
	Session s = openSession();
	Transaction t = s.beginTransaction();
	s.save( entity );
	s.flush();
	assertNotNull( "no timestamp retrieved", entity.getLastModified() );
	t.commit();
	s.close();

	byte[] bytes = entity.getLastModified();

	s = openSession();
	t = s.beginTransaction();
	entity = ( GeneratedPropertyEntity ) s.get( GeneratedPropertyEntity.class, entity.getId() );
	assertTrue( Hibernate.BINARY.isEqual( bytes, entity.getLastModified() ) );
	t.commit();
	s.close();

	assertTrue( Hibernate.BINARY.isEqual( bytes, entity.getLastModified() ) );

	s = openSession();
	t = s.beginTransaction();
	s.delete( entity );
	t.commit();
	s.close();
}
 
Example #15
Source File: CollectionResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public CollectionDTO getCrisisWithAllFieldsByID(Long id) throws PropertyNotSetException {
	Collection collection = getById(id);
	if (collection != null) {
		Hibernate.initialize(collection.getModelFamilies());
		Hibernate.initialize(collection.getDocuments());

		CollectionDTO dto = new CollectionDTO(collection);
		return dto;
	} else {
		return null;
	}
}
 
Example #16
Source File: SQLiteDialect.java    From poli-libras with GNU General Public License v3.0 5 votes vote down vote up
public SQLiteDialect() {
	super();
	registerColumnType(Types.BIT, "integer");
	registerColumnType(Types.TINYINT, "tinyint");
	registerColumnType(Types.SMALLINT, "smallint");
	registerColumnType(Types.INTEGER, "integer");
	registerColumnType(Types.BIGINT, "bigint");
	registerColumnType(Types.FLOAT, "float");
	registerColumnType(Types.REAL, "real");
	registerColumnType(Types.DOUBLE, "double");
	registerColumnType(Types.NUMERIC, "numeric");
	registerColumnType(Types.DECIMAL, "decimal");
	registerColumnType(Types.CHAR, "char");
	registerColumnType(Types.VARCHAR, "varchar");
	registerColumnType(Types.LONGVARCHAR, "longvarchar");
	registerColumnType(Types.DATE, "date");
	registerColumnType(Types.TIME, "time");
	registerColumnType(Types.TIMESTAMP, "timestamp");
	registerColumnType(Types.BINARY, "blob");
	registerColumnType(Types.VARBINARY, "blob");
	registerColumnType(Types.LONGVARBINARY, "blob");
	// registerColumnType(Types.NULL, "null");
	registerColumnType(Types.BLOB, "blob");
	registerColumnType(Types.CLOB, "clob");
	registerColumnType(Types.BOOLEAN, "integer");

	 registerFunction( "concat", new VarArgsSQLFunction(Hibernate.STRING, "", "||", "") );
	 registerFunction( "mod", new SQLFunctionTemplate( Hibernate.INTEGER, "?1 % ?2" ) );
	 registerFunction( "substr", new StandardSQLFunction("substr", Hibernate.STRING) );
	 registerFunction( "substring", new StandardSQLFunction( "substr", Hibernate.STRING ) );
}
 
Example #17
Source File: TaskSelectPanel.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public TaskSelectPanel(final FieldsetPanel fieldsetPanel, final IModel<TaskDO> model, final ISelectCallerPage caller,
    final String selectProperty)
{
  super(fieldsetPanel.newChildId(), model, caller, selectProperty);
  this.fieldsetPanel = fieldsetPanel;
  fieldsetPanel.getFieldset().setOutputMarkupId(true).setOutputMarkupPlaceholderTag(true);
  TaskDO task = model.getObject();
  if (Hibernate.isInitialized(task) == false) {
    task = taskTree.getTaskById(task.getId());
    model.setObject(task);
  }
  divContainer = new WebMarkupContainer("div") {
    private static final long serialVersionUID = -8150112323444983335L;

    /**
     * @see org.apache.wicket.Component#isVisible()
     */
    @Override
    public boolean isVisible()
    {
      // display only, if we are not in ajax task select mode
      return ajaxTaskSelectMode == false;
    }
  };
  divContainer.setOutputMarkupId(true);
  divContainer.setOutputMarkupPlaceholderTag(true);
  add(divContainer);
  ajaxTaskSelectMode = false;
}
 
Example #18
Source File: BaseSecurityManager.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * @param sortedByAddDate
 *            true= return list of idenities sorted by added date
 */
@Override
public List getIdentitiesAndDateOfSecurityGroup(final SecurityGroup secGroup, final boolean sortedByAddDate) {
    final StringBuilder queryString = new StringBuilder();
    queryString.append("select ii, sgmsi.lastModified from" + " org.olat.data.basesecurity.IdentityImpl as ii inner join fetch ii.user as iuser, "
            + " org.olat.data.basesecurity.SecurityGroupMembershipImpl as sgmsi " + " where sgmsi.securityGroup = ? and sgmsi.identity = ii");
    if (sortedByAddDate) {
        queryString.append(" order by sgmsi.lastModified");
    }
    final List identAndDate = database.find(queryString.toString(), new Object[] { secGroup.getKey() }, new Type[] { Hibernate.LONG });
    return identAndDate;
}
 
Example #19
Source File: BaseSecurityManager.java    From olat with Apache License 2.0 5 votes vote down vote up
public List<Identity> getIdentitiesOfSecurityGroup(SecurityGroup secGroup, boolean sortedByAddDate) {
    if (secGroup == null) {
        throw new AssertException("getIdentitiesOfSecurityGroup: ERROR secGroup was null !!");
    }
    final StringBuilder queryString = new StringBuilder();
    queryString.append("select ii from" + " org.olat.data.basesecurity.IdentityImpl as ii inner join fetch ii.user as iuser, "
            + " org.olat.data.basesecurity.SecurityGroupMembershipImpl as sgmsi " + " where sgmsi.securityGroup = ? and sgmsi.identity = ii");
    if (sortedByAddDate) {
        queryString.append(" order by sgmsi.lastModified");
    }
    @SuppressWarnings("unchecked")
    final List<Identity> idents = database.find(queryString.toString(), new Object[] { secGroup.getKey() }, new Type[] { Hibernate.LONG });
    return idents;
}
 
Example #20
Source File: FooBarTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testForceOuterJoin() throws Exception {

		if ( isOuterJoinFetchingDisabled() ) return;

		Session s = openSession();
		Glarch g = new Glarch();
		FooComponent fc = new FooComponent();
		fc.setGlarch(g);
		FooProxy f = new Foo();
		FooProxy f2 = new Foo();
		f.setComponent(fc);
		f.setFoo(f2);
		s.save(f2);
		Serializable id = s.save(f);
		Serializable gid = s.getIdentifier( f.getComponent().getGlarch() );
		s.flush();
		s.connection().commit();
		s.close();

		getSessions().evict(Foo.class);

		s = openSession();
		f = (FooProxy) s.load(Foo.class, id);
		assertFalse( Hibernate.isInitialized(f) );
		assertTrue( Hibernate.isInitialized( f.getComponent().getGlarch() ) ); //outer-join="true"
		assertFalse( Hibernate.isInitialized( f.getFoo() ) ); //outer-join="auto"
		assertEquals( s.getIdentifier( f.getComponent().getGlarch() ), gid );
		s.delete(f);
		s.delete( f.getFoo() );
		s.flush();
		s.connection().commit();
		s.close();
	}
 
Example #21
Source File: ClusterLockDao.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * to resolve a cirqular dependency in spring startup (baseSecurity was used in this dao, which need coordinator which was not yet ready...) copied method as private
 * to this dao
 * 
 * @param identityName
 * @return
 */
private Identity findIdentityByName(final String identityName) {
    final List identities = DBFactory.getInstance().find("select ident from org.olat.data.basesecurity.IdentityImpl as ident where ident.name = ?",
            new Object[] { identityName }, new Type[] { Hibernate.STRING });
    final int size = identities.size();
    if (size == 0) {
        return null;
    }
    if (size != 1) {
        throw new AssertException("non unique name in identites: " + identityName);
    }
    final Identity identity = (Identity) identities.get(0);
    return identity;
}
 
Example #22
Source File: HibernateFactory.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convert a byte[] array to a Blob object.  Guards against
 * null arrays and 0 length arrays.
 * @param data array to convert to a Blob
 * @return Blob if data[] is non-null and {@literal length > 0}, null otherwise
 */
public static Blob byteArrayToBlob(byte[] data) {
    if (data == null) {
        return null;
    }
    if (data.length == 0) {
        return null;
    }
    return Hibernate.createBlob(data);

}
 
Example #23
Source File: SaltServerActionService.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private Action unproxy(Action entity) {
    Hibernate.initialize(entity);
    if (entity instanceof HibernateProxy) {
        entity = (Action) ((HibernateProxy) entity).getHibernateLazyInitializer()
                .getImplementation();
    }
    return entity;
}
 
Example #24
Source File: ApiService.java    From heimdall with Apache License 2.0 5 votes vote down vote up
/**
 * Find plans from {@link Api} by its ID.
 *
 * @param id   The ID of the {@link Api}
 * @return     List of the {@link Plan}
 */
@Transactional(readOnly = true)
public List<Plan> plansByApi(Long id) {

     Api found = apiRepository.findOne(id);
     HeimdallException.checkThrow(Objects.isNull(found), API_NOT_EXIST);

     Hibernate.initialize(found.getPlans());
     return found.getPlans();
}
 
Example #25
Source File: HibernateUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
/** 
 * Initialize Object for use with closed Session. 
 * 
 * @param sessionFactory max depth in recursion
 * @param obj Object to initialize
 * @param initializedObjects list with already initialized Objects
 * @param depth max depth in recursion
 */
private static void initialize(SessionFactory sessionFactory, Object obj, 
		List<Object> initializedObjects, int depth) {
	
	// return on nulls, depth = 0 or already initialized objects
	if (obj == null || depth == 0) { 
		return; 
	}
	
	if (!Hibernate.isInitialized(obj)) {
		// if collection, initialize objects in collection too. Hibernate don't do it.
		if (obj instanceof Collection) {
			initializeCollection(sessionFactory, obj, initializedObjects,
					depth);
			return;
		}
		
		sessionFactory.getCurrentSession().buildLockRequest(LockOptions.NONE).lock(obj);
		Hibernate.initialize(obj);
	}

	// now we can call equals safely. If object are already initializated, return
	if (initializedObjects.contains(obj))
		return;
	
	initializedObjects.add(obj);
	
	// initialize all persistent associaciations.
	ClassMetadata classMetadata = getClassMetadata(sessionFactory, obj);
	
	if (classMetadata == null) {
		return; // Not persistent object
	}
	
	Object[] pvs = classMetadata.getPropertyValues(obj, EntityMode.POJO);
	
	for (Object pv : pvs) {
		initialize(sessionFactory, pv, initializedObjects, depth - 1);
	}
}
 
Example #26
Source File: BaseSecurityManager.java    From olat with Apache License 2.0 5 votes vote down vote up
@Override
public List<SecurityGroup> getSecurityGroupsForIdentity(final Identity identity) {
    final List<SecurityGroup> secGroups = database.find("select sgi from" + " org.olat.data.basesecurity.SecurityGroupImpl as sgi,"
            + " org.olat.data.basesecurity.SecurityGroupMembershipImpl as sgmsi " + " where sgmsi.securityGroup = sgi and sgmsi.identity = ?",
            new Object[] { identity.getKey() }, new Type[] { Hibernate.LONG });
    return secGroups;
}
 
Example #27
Source File: BasicQueryTestBase.java    From crnk-framework with Apache License 2.0 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 #28
Source File: NavigatableAttributesSupportImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Attribute getByAttributeCode(final String attributeCode) {
    final Attribute attribute = attributeDao.findSingleByNamedQuery("ATTRIBUTE.BY.CODE", attributeCode);
    if (attribute != null) {
        Hibernate.initialize(attribute.getEtype());
    }
    return attribute;
}
 
Example #29
Source File: PersistentListElementHolder.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Serializable disassemble(CollectionPersister persister) throws HibernateException {
			
	Type elementType = persister.getElementType();
	final String indexNodeName = getIndexAttributeName(persister);
	List elements =  element.elements( persister.getElementNodeName() );
	int length = elements.size();
	Serializable[] result = new Serializable[length];
	for ( int i=0; i<length; i++ ) {
		Element elem = (Element) elements.get(i);
		Object object = elementType.fromXMLNode( elem, persister.getFactory() );
		Integer index = (Integer) Hibernate.INTEGER.fromStringValue( getIndex(elem, indexNodeName, i) );
		result[ index.intValue() ] = elementType.disassemble( object, getSession(), null );
	}
	return result;
}
 
Example #30
Source File: MultiplicityType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
	throws HibernateException, SQLException {

	Integer c = (Integer) Hibernate.INTEGER.nullSafeGet( rs, names[0] );
	GlarchProxy g = (GlarchProxy) Hibernate.entity(Glarch.class).nullSafeGet(rs, names[1], session, owner);
	Multiplicity m = new Multiplicity();
	m.count = c==null ? 0 : c.intValue();
	m.glarch = g;
	return m;
}