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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #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_brand_eg_when_performing_custom_paged_query_then_brand_should_be_loaded() {
  Brand brand = brandRepository.findById(1L).orElseThrow(RuntimeException::new);
  entityManager.flush();
  entityManager.clear();

  Page<Product> productPage =
      productRepository.findPageByBrand(
          brand, PageRequest.of(0, 1), EntityGraphs.named(Product.BRAND_EG));
  assertThat(productPage.getContent()).isNotEmpty();
  for (Product product : productPage.getContent()) {
    assertThat(Hibernate.isInitialized(product.getBrand())).isTrue();
  }
}
 
Example #12
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 #13
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 #14
Source File: BasicQueryTestBase.java    From katharsis-framework with Apache License 2.0 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 #15
Source File: OnyxResultManager.java    From olat with Apache License 2.0 5 votes vote down vote up
private static List<QTIResultSet> getResultSetByAssassmentId(final Long assessmentID) {
	final DB db = DBFactory.getInstance();

	final StringBuilder slct = new StringBuilder();
	slct.append("select rset from ");
	slct.append("org.olat.ims.qti.QTIResultSet rset ");
	slct.append("where ");
	slct.append("rset.assessmentID=? ");

	return db.find(slct.toString(), new Object[] { assessmentID }, new Type[] { Hibernate.LONG });
}
 
Example #16
Source File: StatefulPersistenceContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean reassociateIfUninitializedProxy(Object value) throws MappingException {
	if ( !Hibernate.isInitialized( value ) ) {
		final HibernateProxy proxy = (HibernateProxy) value;
		final LazyInitializer li = proxy.getHibernateLazyInitializer();
		reassociateProxy( li, proxy );
		return true;
	}
	else {
		return false;
	}
}
 
Example #17
Source File: AutomationDAO.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Force initialization of a proxy
 */
private void initialize(AutomationValidation aValidation) {
	if (aValidation != null) {
		Hibernate.initialize(aValidation);
		Hibernate.initialize(aValidation.getParams());
	}
}
 
Example #18
Source File: BookmarkDaoImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * @param identity
 * @param res
 * @return true if resourceable is bookmarked
 */
@Override
public boolean isResourceableBookmarked(final Identity identity, final OLATResourceable res) {
    final String query = "from org.olat.data.bookmark.BookmarkImpl as b where b.olatrestype = ? and b.olatreskey = ? and b.owner.key = ?";

    final List results = db.find(query, new Object[] { res.getResourceableTypeName(), res.getResourceableId(), identity.getKey() }, new Type[] { Hibernate.STRING,
            Hibernate.LONG, Hibernate.LONG });
    return results.size() != 0;
}
 
Example #19
Source File: HibernateUnproxifier.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public T unproxy(T entity) {

    if (entity == null) {
        throw new NullPointerException("Entity passed for initialization is null");
    }

    Hibernate.initialize(entity);
    if (entity instanceof HibernateProxy) {
        entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer().getImplementation();
    }

    return entity;
}
 
Example #20
Source File: RegistrationDaoImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * returns an existing list of TemporaryKey by a given action or null if none found
 * 
 * @param action
 * @return the found temporary key or null if none is found
 */
@Override
public List<TemporaryKey> loadTemporaryKeyByAction(final String action) {
    final List<TemporaryKey> tks = database.find("from r in class org.olat.data.registration.TemporaryKeyImpl where r.regAction = ?", action, Hibernate.STRING);
    if (tks.size() > 0) {
        return tks;
    } else {
        return null;
    }
}
 
Example #21
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 #22
Source File: RepositoryTest.java    From spring-data-jpa-entity-graph with MIT License 5 votes vote down vote up
@Transactional
@Test
public void given_country_eg_when_finding_makers_then_country_should_be_initialized() {
  List<Maker> makers =
      makerRepository.findByName("Maker 1", EntityGraphs.named(Maker.COUNTRY_EG));
  assertThat(makers).isNotEmpty();
  for (Maker maker : makers) {
    assertThat(Hibernate.isInitialized(maker.getCountry())).isTrue();
  }
}
 
Example #23
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 #24
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 #25
Source File: HibernateTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void initialize(Object proxy) throws DataAccessException {
	try {
		Hibernate.initialize(proxy);
	}
	catch (HibernateException ex) {
		throw SessionFactoryUtils.convertHibernateAccessException(ex);
	}
}
 
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: 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;
}
 
Example #28
Source File: FetchingTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testHibernateFetchingLazy() throws Exception {
	Session s;
	Transaction tx;
	s = openSession();
	tx = s.beginTransaction();
	Person p = new Person( "Gavin", "King", "JBoss Inc" );
	Stay stay = new Stay( null, new Date(), new Date(), "A380", "Blah", "Blah" );
	Stay stay2 = new Stay( null, new Date(), new Date(), "A320", "Blah", "Blah" );
	Stay stay3 = new Stay( null, new Date(), new Date(), "A340", "Blah", "Blah" );
	stay.setOldPerson( p );
	stay2.setVeryOldPerson( p );
	stay3.setVeryOldPerson( p );
	p.addOldStay( stay );
	p.addVeryOldStay( stay2 );
	p.addVeryOldStay( stay3 );
	s.persist( p );
	tx.commit();
	s.clear();
	tx = s.beginTransaction();
	p = (Person) s.createQuery( "select p from Person p where p.firstName = :name" )
			.setParameter( "name", "Gavin" ).uniqueResult();
	assertFalse( Hibernate.isInitialized( p.getOldStays() ) );
	assertEquals( 1, p.getOldStays().size() );
	assertFalse( "lazy extra is failing", Hibernate.isInitialized( p.getOldStays() ) );
	s.clear();
	stay = (Stay) s.get( Stay.class, stay.getId() );
	assertTrue( ! Hibernate.isInitialized( stay.getOldPerson() ) );
	s.clear();
	stay3 = (Stay) s.get( Stay.class, stay3.getId() );
	assertTrue( "FetchMode.JOIN should overrides lazy options", Hibernate.isInitialized( stay3.getVeryOldPerson() ) );
	s.delete( stay3.getVeryOldPerson() );
	tx.commit();
	s.close();
}
 
Example #29
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 #30
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;
}