@Override public Map<String, Object> getIdMetadata(Class<?> entityClass, HibernateEntityManager entityManager) { Map<String, Object> response = new HashMap<String, Object>(); SessionFactory sessionFactory = entityManager.getSession().getSessionFactory(); ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass); if (metadata == null) { return null; } String idProperty = metadata.getIdentifierPropertyName(); response.put("name", idProperty); Type idType = metadata.getIdentifierType(); response.put("type", idType); return response; }
@Override public Map<String, Object> getIdMetadata(Class<?> entityClass, HibernateEntityManager entityManager) { entityClass = getNonProxyImplementationClassIfNecessary(entityClass); Map<String, Object> response = new HashMap<String, Object>(); SessionFactory sessionFactory = entityManager.getSession().getSessionFactory(); ClassMetadata metadata = sessionFactory.getClassMetadata(entityClass); if (metadata == null) { return null; } String idProperty = metadata.getIdentifierPropertyName(); response.put("name", idProperty); Type idType = metadata.getIdentifierType(); response.put("type", idType); return response; }
private void init(HibernateEntityManager hem) { hem.getSession().doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { String dbName = connection.getMetaData().getDatabaseProductName(); if (dbName.equals(MSSQLDialect.PRODUCT_NAME)) { dialect = new MSSQLDialect(); } else if (dbName.equals(PostgresDialect.PRODUCT_NAME)) { dialect = new PostgresDialect(); } else if (dbName.equals(H2Dialect.PRODUCT_NAME)) { dialect = new H2Dialect(); } else if (dbName.equals(MySQLDialect.PRODUCT_NAME)) { dialect = new MySQLDialect(); } else { dialect = new DefaultDialect(); } } }); }
/** * {@inheritDoc} */ @Override public IndicatorListResult execute(final GetIndicators cmd, final UserExecutionContext context) throws CommandException { final EntityManager entityManager = em(); // Creates a new instance for every call. // Be careful, this must NOT be a singleton because the DAO is stateful. final IndicatorDAO indicatorDAO = new IndicatorHibernateDAO(); if(entityManager instanceof HibernateEntityManager) { findIndicators((HibernateEntityManager)entityManager, indicatorDAO, cmd.getUserDatabaseId()); } else { throw new UnsupportedOperationException("Entity manager type not supported. Required org.hibernate.ejb.HibernateEntityManager, found: " + entityManager.getClass().getName()); } return indicatorDAO.getResult(); }
/** * Saves a business object. * * @see org.kuali.rice.krad.dao.BusinessObjectDao#save(org.kuali.rice.krad.bo.PersistableBusinessObject) */ public PersistableBusinessObject save(PersistableBusinessObject bo) throws DataAccessException { /* KC determined this is not needed for JPA // if collections exist on the BO, create a copy and use to process the // collections to ensure // that removed elements are deleted from the database Set<String> boCollections = getPersistenceStructureService().listCollectionObjectTypes(bo.getClass()).keySet(); PersistableBusinessObject savedBo = null; if (!boCollections.isEmpty()) { // refresh bo to get db copy of collections savedBo = (PersistableBusinessObject) ObjectUtils.deepCopy(bo); for (String boCollection : boCollections) { if (getPersistenceStructureService().isCollectionUpdatable(savedBo.getClass(), boCollection)) { savedBo.refreshReferenceObject(boCollection); } } } */ if (entityManager.contains(bo) && ((HibernateEntityManager)entityManager).getSession().isReadOnly(bo)) { ((HibernateEntityManager)entityManager).getSession().setReadOnly(bo, false); // are we read only? turn that off... } return reattachAndSave(bo); }
@Override public Blob createBlob(MultipartFile uploadedFile) throws IOException { Long size = uploadedFile.getSize(); InputStream inputStream = uploadedFile.getInputStream(); //We'll work with Blob instances and streams so that the uploaded files are never read into memory return ((HibernateEntityManager) em).getSession().getLobHelper().createBlob(inputStream, size); }
@Override @SuppressWarnings("rawtypes") public Object readGenericEntity(Class<?> clazz, Object id) { Map<String, Object> md = daoHelper.getIdMetadata(clazz, (HibernateEntityManager) em); AbstractSingleColumnStandardBasicType type = (AbstractSingleColumnStandardBasicType) md.get("type"); if (type instanceof LongType) { id = Long.parseLong(String.valueOf(id)); } else if (type instanceof IntegerType) { id = Integer.parseInt(String.valueOf(id)); } return em.find(clazz, id); }
@Override public List<String> getPropertyNames(Class<?> entityClass, HibernateEntityManager entityManager) { ClassMetadata metadata = getSessionFactory(entityManager).getClassMetadata(entityClass); List<String> propertyNames = new ArrayList<String>(); Collections.addAll(propertyNames, metadata.getPropertyNames()); return propertyNames; }
@Override public List<Type> getPropertyTypes(Class<?> entityClass, HibernateEntityManager entityManager) { ClassMetadata metadata = getSessionFactory(entityManager).getClassMetadata(entityClass); List<Type> propertyTypes = new ArrayList<Type>(); Collections.addAll(propertyTypes, metadata.getPropertyTypes()); return propertyTypes; }
@Override public List<Offer> readOffersByAutomaticDeliveryType() { //TODO change this to a JPA criteria Criteria criteria = ((HibernateEntityManager) em).getSession().createCriteria(OfferImpl.class); Date myDate = getCurrentDateAfterFactoringInDateResolution(); Calendar c = Calendar.getInstance(); c.setTime(myDate); c.add(Calendar.DATE, +1); criteria.add(Restrictions.lt("startDate", c.getTime())); c = Calendar.getInstance(); c.setTime(myDate); c.add(Calendar.DATE, -1); criteria.add(Restrictions.or(Restrictions.isNull("endDate"), Restrictions.gt("endDate", c.getTime()))); criteria.add(Restrictions.or(Restrictions.eq("archiveStatus.archived", 'N'), Restrictions.isNull("archiveStatus.archived"))); // Automatically Added or (Automatically Added is null and deliveryType is Automatic) criteria.add(Restrictions.or(Restrictions.eq("automaticallyAdded", true), Restrictions.and(Restrictions.isNull("automaticallyAdded"), Restrictions.eq("deliveryType", "AUTOMATIC")))); criteria.setCacheable(true); criteria.setCacheRegion("query.Offer"); return criteria.list(); }
protected String[] getPolymorphicClasses(Class<?> clazz) { DynamicDaoHelperImpl helper = new DynamicDaoHelperImpl(); Class<?>[] classes = helper.getAllPolymorphicEntitiesFromCeiling(clazz, helper.getSessionFactory((HibernateEntityManager) em), true, useCache()); String[] result = new String[classes.length]; for (int i = 0; i < classes.length; i++) { result[i] = classes[i].getName(); } return result; }
@Override public <T> T readGenericEntity(Class<T> clazz, Object id) { clazz = (Class<T>) DynamicDaoHelperImpl.getNonProxyImplementationClassIfNecessary(clazz); Map<String, Object> md = daoHelper.getIdMetadata(clazz, (HibernateEntityManager) em); AbstractSingleColumnStandardBasicType type = (AbstractSingleColumnStandardBasicType) md.get("type"); if (type instanceof LongType) { id = Long.parseLong(String.valueOf(id)); } else if (type instanceof IntegerType) { id = Integer.parseInt(String.valueOf(id)); } return em.find(clazz, id); }
@Override public List<String> getPropertyNames(Class<?> entityClass, HibernateEntityManager entityManager) { entityClass = getNonProxyImplementationClassIfNecessary(entityClass); ClassMetadata metadata = getSessionFactory(entityManager).getClassMetadata(entityClass); List<String> propertyNames = new ArrayList<String>(); Collections.addAll(propertyNames, metadata.getPropertyNames()); return propertyNames; }
@Override public List<Type> getPropertyTypes(Class<?> entityClass, HibernateEntityManager entityManager) { entityClass = getNonProxyImplementationClassIfNecessary(entityClass); ClassMetadata metadata = getSessionFactory(entityManager).getClassMetadata(entityClass); List<Type> propertyTypes = new ArrayList<Type>(); Collections.addAll(propertyTypes, metadata.getPropertyTypes()); return propertyTypes; }
private static void activateSession() { Map<Object, Object> resourceMap = TransactionSynchronizationManager.getResourceMap(); for (Map.Entry<Object, Object> entry : resourceMap.entrySet()) { if (entry.getKey() instanceof EntityManagerFactory && entry.getValue() instanceof EntityManagerHolder) { ((HibernateEntityManager) ((EntityManagerHolder) entry.getValue()).getEntityManager()).getSession(); } } }
/** * Retrieves the EntityManager with the given unit name. * <p> * @param aPersistenceUnit * @return */ public static HibernateEntityManager getEntityManager( String aPersistenceUnit ) { if ( myFactory == null ) { myFactory = Persistence.createEntityManagerFactory( aPersistenceUnit ); } // if myFactory == null EntityManager o = myFactory.createEntityManager(); return (HibernateEntityManager) o; }
/** * */ private void provideNewEntityManager() { HibernateEntityManager em = Whitebox.getInternalState( myClassUnderTest, HibernateEntityManager.class ); if ( em != null ) { em.close(); } // if em != null EntityManager newEm = EntityManagerProvider.getEntityManager( "oxwall" ); Assert.assertNotNull( newEm ); Assert.assertTrue( em != newEm ); Whitebox.setInternalState( myClassUnderTest, "myEntityManager", newEm ); }
/** * */ private void addTestUser() { HibernateEntityManager em = Whitebox.getInternalState( myClassUnderTest, HibernateEntityManager.class ); Assert.assertNotNull( em ); em.getTransaction().begin(); try { OxUser newUser = new OxUser(); newUser.setUsername( "Heri22" ); newUser.setAccountType( "accountType" ); newUser.setActivityStamp( 1396986027L ); newUser.setEmail( USER_EMAIL ); newUser.setJoinIp( 1234L ); newUser.setJoinStamp( 1396980000L ); newUser.setPassword( "asdflkj" ); em.persist( newUser ); myLog.debug( "Persisted user: " + newUser ); em.getTransaction().commit();; } catch ( Throwable t ) { em.getTransaction().rollback(); myLog.error( "Exception caught: ", t ); throw t; } }
protected Session getSession(EntityManager em) { if (em instanceof HibernateEntityManager) { return ((HibernateEntityManager) em).getSession(); } else { Object delegate = em.getDelegate(); if (delegate instanceof Session) { return (Session) delegate; } else { throw new IllegalStateException( "Cannot obtain native Hibernate Session from given JPA EntityManager: " + em.getClass()); } } }
/** * Find the requested indicators in a transaction. * * The transaction is required by IndicatorDAO. * * @param entityManager An Hibernate entity manager. * @param indicatorDAO A new indicator DAO, dedicated for this use. * @param userDatabaseId Identifier of the database to query. * @throws HibernateException */ @Transactional protected void findIndicators(final HibernateEntityManager entityManager, final IndicatorDAO indicatorDAO, final int userDatabaseId) throws HibernateException { entityManager.getSession().doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { indicatorDAO.queryIndicatorGroups(connection, userDatabaseId); indicatorDAO.queryIndicatorsByDatabaseWithCurrentValues(connection, userDatabaseId); } }); }
/** * @see org.kuali.rice.krad.dao.BusinessObjectDao#manageReadOnly(org.kuali.rice.krad.bo.PersistableBusinessObject) */ public PersistableBusinessObject manageReadOnly(PersistableBusinessObject bo) { Session session = ((HibernateEntityManager)entityManager).getSession(); FlushMode currentFlushMode = session.getFlushMode(); session.setFlushMode(FlushMode.MANUAL); // make sure the merge doesn't flush what we're trying to make read only PersistableBusinessObject managedBO = entityManager.merge(bo); session.setReadOnly(managedBO, true); session.setFlushMode(currentFlushMode); return managedBO; }
public void testCanCastSharedEntityManagerProxyToHibernateEntityManager() { assertTrue(sharedEntityManager instanceof HibernateEntityManager); HibernateEntityManager hibernateEntityManager = (HibernateEntityManager) sharedEntityManager; assertNotNull(hibernateEntityManager.getSession()); }
@Override public Criteria createCriteria(Class<?> entityClass) { return ((HibernateEntityManager) getStandardEntityManager()).getSession().createCriteria(entityClass); }
@Override public SessionFactory getSessionFactory() { return dynamicDaoHelper.getSessionFactory((HibernateEntityManager) standardEntityManager); }
@Override public Map<String, Object> getIdMetadata(Class<?> entityClass) { return dynamicDaoHelper.getIdMetadata(entityClass, (HibernateEntityManager) standardEntityManager); }
@Override public List<String> getPropertyNames(Class<?> entityClass) { return dynamicDaoHelper.getPropertyNames(entityClass, (HibernateEntityManager) standardEntityManager); }
@Override public List<Type> getPropertyTypes(Class<?> entityClass) { return dynamicDaoHelper.getPropertyTypes(entityClass, (HibernateEntityManager) standardEntityManager); }
@Override public SessionFactory getSessionFactory(HibernateEntityManager entityManager) { return entityManager.getSession().getSessionFactory(); }
@Override public Map<String, Object> getIdPropertyMetadata(TranslatedEntity entity) { Class<?> implClass = entityConfiguration.lookupEntityClass(entity.getType()); return dynamicDaoHelper.getIdMetadata(implClass, (HibernateEntityManager) em); }