javax.persistence.EntityManager Java Examples

The following examples show how to use javax.persistence.EntityManager. 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 Project: HibernateTips   Author: thjanssen   File: TestStoredProcedureQuery.java    License: MIT License 7 votes vote down vote up
@Test
public void calculate() {
	log.info("... calculate ...");
	EntityManager em = emf.createEntityManager();
       em.getTransaction().begin();
       
	// define the stored procedure
	StoredProcedureQuery query = em.createStoredProcedureQuery("calculate");
	query.registerStoredProcedureParameter("x", Double.class, ParameterMode.IN);
	query.registerStoredProcedureParameter("y", Double.class, ParameterMode.IN);
	query.registerStoredProcedureParameter("sum", Double.class, ParameterMode.OUT);
	
	// set input parameter
	query.setParameter("x", 1.23d);
	query.setParameter("y", 4d);
	
	// call the stored procedure and get the result
	query.execute();
	Double sum = (Double) query.getOutputParameterValue("sum");
	log.info("Calculation result: 1.23 + 4 = " + sum);

       em.getTransaction().commit();
       em.close();
}
 
Example #2
Source Project: deltaspike   Author: apache   File: AggregatedDefaultEntityManagerInjectionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void defaultEntityManagerInjection()
{
    EntityManager injectedEntityManager = entityManagerProducer.getDefaultEntityManager();

    Assert.assertNotNull(injectedEntityManager);
    Assert.assertTrue(injectedEntityManager instanceof TestEntityManager);
    TestEntityTransaction testTransaction = (TestEntityTransaction) (injectedEntityManager).getTransaction();

    Assert.assertEquals(false, ((TestEntityManager) injectedEntityManager).isFlushed());
    Assert.assertEquals(false, testTransaction.isActive());
    Assert.assertEquals(false, testTransaction.isStarted());
    Assert.assertEquals(false, testTransaction.isCommitted());
    Assert.assertEquals(false, testTransaction.isRolledBack());

    transactionalBean.executeInTransaction();

    Assert.assertEquals(true, ((TestEntityManager) injectedEntityManager).isFlushed());
    Assert.assertEquals(false, testTransaction.isActive());
    Assert.assertEquals(true, testTransaction.isStarted());
    Assert.assertEquals(true, testTransaction.isCommitted());
    Assert.assertEquals(false, testTransaction.isRolledBack());

    Assert.assertEquals(false, TransactionBeanStorage.isOpen());
}
 
Example #3
List<String> listEditableWithPortalCategory(Business business, EffectivePerson effectivePerson,
		String portalCategory) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Portal.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<Portal> root = cq.from(Portal.class);
	Predicate p = cb.conjunction();
	if (!business.isPortalManager(effectivePerson)) {
		p = cb.isMember(effectivePerson.getDistinguishedName(), root.get(Portal_.controllerList));
		p = cb.or(p, cb.equal(root.get(Portal_.creatorPerson), effectivePerson.getDistinguishedName()));
	}
	p = cb.and(p, cb.equal(root.get(Portal_.portalCategory), Objects.toString(portalCategory, "")));
	cq.select(root.get(Portal_.id)).where(p).distinct(true);
	List<String> list = em.createQuery(cq.select(root.get(Portal_.id)).where(p)).getResultList();
	return list;
}
 
Example #4
Source Project: bouncr   Author: kawasima   File: UserResource.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Decision(value = CONFLICT, method = "PUT")
public boolean conflict(UserUpdateRequest updateRequest,
                        User user,
                        RestContext context,
                        EntityManager em) {
    UserProfileService userProfileService = new UserProfileService(em);
    Set<Problem.Violation> violations = userProfileService.validateProfileUniqueness(updateRequest.getUserProfiles(), user);
    if (!violations.isEmpty()) {
        Problem problem = builder(Problem.valueOf(409))
                .set(Problem::setType, BouncrProblem.CONFLICT.problemUri())
                .build();
        problem.getViolations().addAll(violations);
        context.setMessage(problem);
    }
    return !violations.isEmpty();
}
 
Example #5
Source Project: joynr   Author: bmwcarit   File: ChannelDatabase.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Channel getChannel(Optional<String> ccid) {

    String channelId;
    if (ccid.isPresent()) {
        channelId = ccid.get();
    } else {
        logger.debug("No channel found for ID NULL");
        return null;
    }
    logger.trace("GetChannel({})", channelId);

    EntityManager em = emf.createEntityManager();
    ChannelEntity channelEntity = em.find(ChannelEntity.class, channelId);
    if (channelEntity == null) {
        logger.debug("No channel found for ID {}", channelId);
        return null;
    }

    return channelEntity.convertToChannel();
}
 
Example #6
Source Project: o2oa   Author: o2oa   File: CrawlWork.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 定时进行轮询保证旧数据能定期进行更新
 */
private List<String> listUpdateWork(Business business) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Work.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<Work> root = cq.from(Work.class);
	Predicate p = cb.conjunction();
	String sequence = Arguments.getCrawlUpdateWork();
	if (StringUtils.isNotEmpty(sequence)) {
		p = cb.and(cb.lessThan(root.get(Work.sequence_FIELDNAME), sequence));
	}
	cq.select(root.get(Work_.id)).where(p).orderBy(cb.desc(root.get(Work_.sequence)));
	Integer count = Config.query().getCrawlWork().getCount() / 2;
	List<String> os = em.createQuery(cq).setMaxResults(count).getResultList();
	if (os.size() == count) {
		Arguments.setCrawlUpdateWork(os.get(os.size() - 1));
	} else {
		Arguments.setCrawlUpdateWork("");
	}
	return os;
}
 
Example #7
Source Project: o2oa   Author: o2oa   File: V2List.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception {
	ActionResult<List<Wo>> result = new ActionResult<>();
	List<Wo> wos = new ArrayList<>();
	Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
	if ((!wi.isEmptyFilter()) || ListTools.isNotEmpty(wi.getJobList()) || ListTools.isNotEmpty(wi.getIdList())) {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			Business business = new Business(emc);
			EntityManager em = emc.get(Read.class);
			CriteriaBuilder cb = em.getCriteriaBuilder();
			CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
			Root<Read> root = cq.from(Read.class);
			Predicate p = this.toFilterPredicate(effectivePerson, business, wi);
			if (ListTools.isNotEmpty(wi.getJobList())) {
				p = cb.and(p, root.get(Read_.job).in(wi.getJobList()));
			}
			if (ListTools.isNotEmpty(wi.getIdList())) {
				p = cb.and(p, root.get(Read_.id).in(wi.getIdList()));
			}
			wos = emc.fetch(Read.class, Wo.copier, p);
			this.relate(business, wos, wi);
		}
	}
	result.setData(wos);
	return result;
}
 
Example #8
Source Project: o2oa   Author: o2oa   File: V2Count.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private List<NameValueCountPair> groupByApplication(Business business, Predicate predicate) throws Exception {
	EntityManager em = business.entityManagerContainer().get(TaskCompleted.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
	Root<TaskCompleted> root = cq.from(TaskCompleted.class);
	Path<String> pathApplication = root.get(TaskCompleted_.application);
	Path<String> pathApplicationName = root.get(TaskCompleted_.applicationName);
	cq.multiselect(pathApplication, pathApplicationName, cb.count(root)).where(predicate).groupBy(pathApplication);
	List<Tuple> os = em.createQuery(cq).getResultList();
	List<NameValueCountPair> list = new ArrayList<>();
	NameValueCountPair pair = null;
	for (Tuple o : os) {
		pair = new NameValueCountPair();
		pair.setName(o.get(pathApplicationName));
		pair.setValue(o.get(pathApplication));
		pair.setCount(o.get(2, Long.class));
		list.add(pair);
	}
	return list.stream().sorted(Comparator.comparing(NameValueCountPair::getCount).reversed())
			.collect(Collectors.toList());
}
 
Example #9
Source Project: juddi   Author: apache   File: ValidatePublish.java    License: Apache License 2.0 6 votes vote down vote up
public void validateSaveBindingMax(EntityManager em, String serviceKey) throws DispositionReportFaultMessage {

                //Obtain the maxSettings for this publisher or get the defaults
                Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName());
                Integer maxBindings = publisher.getMaxBindingsPerService();
                try {
                        if (maxBindings == null) {
                                if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_BINDINGS_PER_SERVICE)) {
                                        maxBindings = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1);
                                } else {
                                        maxBindings = -1;
                                }
                        }
                } catch (ConfigurationException e) {
                        log.error(e.getMessage(), e);
                        maxBindings = -1; //incase the config isn't available
                }
                //if we have the maxBindings set for a service then we need to make sure we did not exceed it.
                if (maxBindings > 0) {
                        //get the bindings owned by this service
                        org.apache.juddi.model.BusinessService modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey);
                        if (modelBusinessService.getBindingTemplates() != null && modelBusinessService.getBindingTemplates().size() > maxBindings) {
                                throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxBindingsExceeded"));
                        }
                }
        }
 
Example #10
Source Project: hibernate-types   Author: vladmihalcea   File: PostgreSQLGuavaRangeTypeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnboundedRangeIsRejected() {
    try {
        final Restriction ageRestrictionInt = doInJPA(new JPATransactionFunction<Restriction>() {
            @Override
            public Restriction apply(EntityManager entityManager) {
                Restriction restriction = new Restriction();
                restriction.setRangeInt(Ranges.<Integer>all());
                entityManager.persist(restriction);

                return restriction;
            }
        });
        fail("An unbounded range should throw an exception!");
    } catch (Exception e) {
        Throwable rootCause = Throwables.getRootCause(e);
        assertTrue(rootCause instanceof IllegalArgumentException);
        assertTrue(rootCause.getMessage().contains("doesn't have any upper or lower bound!"));
    }
}
 
Example #11
Source Project: o2oa   Author: o2oa   File: ActionFilterAttribute.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private List<NameValueCountPair> listActivityNamePair(Business business, EffectivePerson effectivePerson)
		throws Exception {
	EntityManager em = business.entityManagerContainer().get(TaskCompleted.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<TaskCompleted> root = cq.from(TaskCompleted.class);
	Predicate p = cb.equal(root.get(TaskCompleted_.person), effectivePerson.getDistinguishedName());
	p = cb.and(p,
			cb.or(cb.equal(root.get(TaskCompleted_.latest), true), cb.isNull(root.get(TaskCompleted_.latest))));
	cq.select(root.get(TaskCompleted_.activityName)).where(p).distinct(true);
	List<String> os = em.createQuery(cq).getResultList();
	List<NameValueCountPair> wos = new ArrayList<>();
	for (String str : os) {
		if (StringUtils.isNotEmpty(str)) {
			NameValueCountPair o = new NameValueCountPair();
			o.setValue(str);
			o.setName(str);
			wos.add(o);
		}
	}
	SortTools.asc(wos, "name");
	return wos;
}
 
Example #12
Source Project: we-cmdb   Author: WeBankPartners   File: CiServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, Object> doUpdate(EntityManager entityManager, int ciTypeId, Map<String, Object> ci, boolean enableStateTransition) {
    DynamicEntityMeta entityMeta = getDynamicEntityMetaMap().get(ciTypeId);

    String guid = ci.get(GUID).toString();
    Object entityBean = validateCi(ciTypeId, guid, entityMeta, entityManager, ACTION_MODIFICATION);
    DynamicEntityHolder entityHolder = new DynamicEntityHolder(entityMeta, entityBean);

    ciDataInterceptorService.preUpdate(entityHolder, ci);
    Map<String, Object> convertedCi = MultiValueFeildOperationUtils.convertMultiValueFieldsForCICreation(entityManager, ciTypeId, ci, (String) ci.get(CmdbConstants.DEFAULT_FIELD_GUID), ciTypeAttrRepository, this);
    Map<String, Object> updatedMap = null;
    if (onlyIncludeRefreshableFields(ciTypeId, convertedCi.keySet()) || !enableStateTransition) {
        entityHolder.update(convertedCi, CmdbThreadLocal.getIntance().getCurrentUser(), entityManager);
        entityManager.merge(entityHolder.getEntityObj());
    } else {
        updatedMap = stateTransEngine.process(entityManager, ciTypeId, guid, StateOperation.Update.getCode(), convertedCi, entityHolder);
        ci.put(CmdbConstants.DEFAULT_FIELD_STATE,StateOperation.Update.getCode());
    }

    ciDataInterceptorService.postUpdate(entityHolder, entityManager, ci);
    updatedMap = ClassUtils.convertBeanToMap(entityHolder.getEntityObj(), entityHolder.getEntityMeta(), false);
    return updatedMap;
}
 
Example #13
Source Project: o2oa   Author: o2oa   File: OkrTaskFactory.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 根据待办类别和用户身份,查询待办列表
 * @param taskTypeList
 * @param userIdentity
 * @return
 * @throws Exception 
 */
public List<OkrTask> listReadByTaskType( List<String> taskTypeList, String userIdentity, String workTypeName ) throws Exception {
	List<OkrTask> okrTaskList = null;
	EntityManager em = this.entityManagerContainer().get( OkrTask.class );
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery< OkrTask > cq = cb.createQuery( OkrTask.class );
	Root<OkrTask> root = cq.from( OkrTask.class);
	Predicate p = root.get( OkrTask_.dynamicObjectType ).in( taskTypeList );
	p = cb.and( p, cb.equal( root.get( OkrTask_.targetIdentity ), userIdentity ) );
	p = cb.and( p, cb.equal( root.get( OkrTask_.processType ), "READ" ) );
	if( workTypeName != null && !workTypeName.isEmpty() ){
		p = cb.and( p, cb.equal( root.get( OkrTask_.workType ), workTypeName ) );
	}
	okrTaskList = em.createQuery(cq.where(p)).getResultList();
	if( okrTaskList == null ){
		return null;
	}else{
		return okrTaskList;
	}
}
 
Example #14
Source Project: o2oa   Author: o2oa   File: OkrTaskHandledFactory.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 查询已办处理者身份列表(去重复)
 * @param identities_ok 排除身份
 * @param identities_error 排除身份
 * @return
 * @throws Exception 
 */
public List<String> listAllDistinctTargetIdentity(List<String> identities_ok, List<String> identities_error) throws Exception {
	EntityManager em = this.entityManagerContainer().get(OkrTaskHandled.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery( String.class );
	Root<OkrTaskHandled> root = cq.from(OkrTaskHandled.class);
	
	Predicate p = cb.isNotNull( root.get( OkrTaskHandled_.id ) );
	if( identities_ok != null && identities_ok.size() > 0 ){
		p = cb.and( p, cb.not(root.get( OkrTaskHandled_.targetIdentity ).in( identities_ok )) );
	}
	if( identities_error != null && identities_error.size() > 0 ){
		p = cb.and( p, cb.not(root.get( OkrTaskHandled_.targetIdentity ).in( identities_error )) );
	}
	cq.distinct(true).select(root.get( OkrTaskHandled_.targetIdentity ));
	return em.createQuery(cq.where(p)).getResultList();
}
 
Example #15
Source Project: o2oa   Author: o2oa   File: OkrTaskFactory.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 根据待办类别和用户身份,查询待办列表
 * @param taskTypeList
 * @param userIdentity
 * @return
 * @throws Exception 
 */
public List<OkrTask> listTaskByTaskType( List<String> taskTypeList, String userIdentity, String workTypeName ) throws Exception {
	List<OkrTask> okrTaskList = null;
	EntityManager em = this.entityManagerContainer().get( OkrTask.class );
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery< OkrTask > cq = cb.createQuery( OkrTask.class );
	Root<OkrTask> root = cq.from( OkrTask.class);
	Predicate p = root.get( OkrTask_.dynamicObjectType ).in( taskTypeList );
	p = cb.and( p, cb.equal( root.get( OkrTask_.targetIdentity ), userIdentity ) );
	p = cb.and( p, cb.equal( root.get( OkrTask_.processType ), "TASK" ) );
	if( workTypeName != null && !workTypeName.isEmpty() ){
		p = cb.and( p, cb.equal( root.get( OkrTask_.workType ), workTypeName ) );
	}
	okrTaskList = em.createQuery(cq.where(p)).getResultList();
	if( okrTaskList == null ){
		return null;
	}else{
		return okrTaskList;
	}
}
 
Example #16
Source Project: ranger   Author: apache   File: DaoManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public EntityManager getEntityManager() {
	EntityManager em = null;

	if(sEntityManager != null) {
		em = sEntityManager.get();

		if(em == null && this.emf != null) {
			em = this.emf.createEntityManager();

			sEntityManager.set(em);
		}
	} else {
		logger.error("EntityManagerFactory was not set in this thread.", new Throwable());
	}

	return em;
}
 
Example #17
Source Project: peer-os   Author: subutai-io   File: RequestDataService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Collection<RequestedHostImpl> getAll()
{
    Collection<RequestedHostImpl> result = Lists.newArrayList();
    EntityManager em = daoManager.getEntityManagerFromFactory();
    try
    {
        em.getTransaction().begin();
        result = em.createQuery( "select h from RequestedHostImpl h", RequestedHostImpl.class ).getResultList();
        em.getTransaction().commit();
    }
    catch ( Exception e )
    {
        LOGGER.error( e.toString(), e );
        if ( em.getTransaction().isActive() )
        {
            em.getTransaction().rollback();
        }
    }
    finally
    {
        em.close();
    }
    return result;
}
 
Example #18
Source Project: che   Author: eclipse   File: JpaProfileDao.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
@Transactional
public ProfileImpl getById(String userId) throws NotFoundException, ServerException {
  requireNonNull(userId, "Required non-null id");
  try {
    final EntityManager manager = managerProvider.get();
    final ProfileImpl profile = manager.find(ProfileImpl.class, userId);
    if (profile == null) {
      throw new NotFoundException(format("Couldn't find profile for user with id '%s'", userId));
    }
    manager.refresh(profile);
    return profile;
  } catch (RuntimeException x) {
    throw new ServerException(x.getLocalizedMessage(), x);
  }
}
 
Example #19
Source Project: o2oa   Author: o2oa   File: BaseAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private Long countExpiredTaskTask(Business business, DateRange dateRange, String applicationId, String processId,
		String activityId, List<String> units, String person) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Task.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Long> cq = cb.createQuery(Long.class);
	Root<Task> root = cq.from(Task.class);
	Predicate p = cb.between(root.get(Task_.expireTime), dateRange.getStart(), dateRange.getEnd());
	if (!StringUtils.equals(applicationId, StandardJaxrsAction.EMPTY_SYMBOL)) {
		p = cb.and(p, cb.equal(root.get(Task_.application), applicationId));
	}
	if (!StringUtils.equals(processId, StandardJaxrsAction.EMPTY_SYMBOL)) {
		p = cb.and(p, cb.equal(root.get(Task_.process), processId));
	}
	if (!StringUtils.equals(activityId, StandardJaxrsAction.EMPTY_SYMBOL)) {
		p = cb.and(p, cb.equal(root.get(Task_.activity), activityId));
	}
	if (ListTools.isNotEmpty(units)) {
		p = cb.and(p, root.get(Task_.unit).in(units));
	}
	if (!StringUtils.equals(person, StandardJaxrsAction.EMPTY_SYMBOL)) {
		p = cb.and(p, cb.equal(root.get(Task_.person), person));
	}
	cq.select(cb.count(root)).where(p);
	return em.createQuery(cq).getSingleResult();
}
 
Example #20
Source Project: cloud-espm-v2   Author: SAP-samples   File: StockTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test removing of a Business Partner.
 */
@Test
public void testRemoveStock() {
	Stock stockRes = null;
	String productId = "HY-1000";
	TestFactory tf = new TestFactory();
	EntityManager em = emf.createEntityManager();
	try {
		if (!tf.createStock(em, productId)) {
			fail("Unable to create Stock");
			return;
		}
		em.getTransaction().begin();
		// Remove Business Partner
		assertTrue("Stock not deleted", tf.deleteStock(em, productId));
		// Search for deleted business partner.
		stockRes = em.find(Stock.class, productId);
		assertNull(
				"Search via find method for removed Stock: Removed Stock with Product HT-1000 still exists ",
				stockRes);
	} finally {
		em.close();
	}
}
 
Example #21
Source Project: spring-analysis-note   Author: Vip-Augus   File: PersistenceInjectionTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testPublicSpecificExtendedPersistenceContextSetter() throws Exception {
	EntityManagerFactory mockEmf2 = mock(EntityManagerFactory.class);
	EntityManager mockEm2 = mock(EntityManager.class);
	given(mockEmf2.createEntityManager()).willReturn(mockEm2);

	GenericApplicationContext gac = new GenericApplicationContext();
	gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
	gac.getDefaultListableBeanFactory().registerSingleton("unit2", mockEmf2);
	gac.registerBeanDefinition("annotationProcessor",
			new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
	gac.registerBeanDefinition(SpecificPublicPersistenceContextSetter.class.getName(),
			new RootBeanDefinition(SpecificPublicPersistenceContextSetter.class));
	gac.refresh();

	SpecificPublicPersistenceContextSetter bean = (SpecificPublicPersistenceContextSetter) gac.getBean(
			SpecificPublicPersistenceContextSetter.class.getName());
	assertNotNull(bean.getEntityManager());
	bean.getEntityManager().flush();
	verify(mockEm2).getTransaction();
	verify(mockEm2).flush();
}
 
Example #22
Source Project: o2oa   Author: o2oa   File: StatisticUnitForDayFactory.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public List<String> listByUnitDayDate(List<String> name, String date) throws Exception {
	if (name == null || name.size() == 0) {
		logger.error(new UnitNamesEmptyException());
		return null;
	}

	EntityManager em = this.entityManagerContainer().get(StatisticUnitForDay.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<StatisticUnitForDay> root = cq.from(StatisticUnitForDay.class);
	Predicate p = root.get(StatisticUnitForDay_.unitName).in(name);
	if (date == null || date.isEmpty()) {
		logger.error(new StatisticDateEmptyException());
	} else {
		p = cb.and(p, cb.equal(root.get(StatisticUnitForDay_.statisticDate), date));
	}
	cq.select(root.get(StatisticUnitForDay_.id));
	return em.createQuery(cq.where(p)).setMaxResults(62).getResultList();
}
 
Example #23
Source Project: o2oa   Author: o2oa   File: BeginFactory.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public Begin getWithProcess(Process process) throws Exception {
	Begin o = null;
	Ehcache cache = ApplicationCache.instance().getCache(Begin.class);
	String cacheKey = "getWithProcess#" + process.getId();
	Element element = cache.get(cacheKey);
	if (null != element) {
		Object obj = element.getObjectValue();
		if (null != obj) {
			o = (Begin) obj;
		}
	} else {
		EntityManager em = this.entityManagerContainer().get(Begin.class);
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Begin> cq = cb.createQuery(Begin.class);
		Root<Begin> root = cq.from(Begin.class);
		Predicate p = cb.equal(root.get("process"), process.getId());
		cq.select(root).where(p);
		List<Begin> list = em.createQuery(cq).setMaxResults(1).getResultList();
		if (!list.isEmpty()) {
			o = list.get(0);
		}
		cache.put(new Element(cacheKey, o));
	}
	return o;
}
 
Example #24
Source Project: o2oa   Author: o2oa   File: OkrWorkReportBaseInfoFactory.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 查询工作汇报者身份列表(去重复)
 * @param identities_ok 排除身份
 * @param identities_error 排除身份
 * @return
 * @throws Exception 
 */
public List<String> listAllDistinctReporterIdentity(List<String> identities_ok, List<String> identities_error) throws Exception {
	EntityManager em = this.entityManagerContainer().get(OkrWorkReportBaseInfo.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery( String.class );
	Root<OkrWorkReportBaseInfo> root = cq.from(OkrWorkReportBaseInfo.class);
	
	Predicate p = cb.isNotNull( root.get( OkrWorkReportBaseInfo_.id ) );
	if( identities_ok != null && identities_ok.size() > 0 ){
		p = cb.and( p, cb.not(root.get( OkrWorkReportBaseInfo_.reporterIdentity ).in( identities_ok )) );
	}
	if( identities_error != null && identities_error.size() > 0 ){
		p = cb.and( p, cb.not(root.get( OkrWorkReportBaseInfo_.reporterIdentity ).in( identities_error )) );
	}
	cq.distinct(true).select(root.get( OkrWorkReportBaseInfo_.reporterIdentity ));
	return em.createQuery(cq.where(p)).getResultList();
}
 
Example #25
Source Project: open-platform-demo   Author: axelor   File: SaleOrderController.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public void reportMonthly(ActionRequest request, ActionResponse response) {
  EntityManager em = getEntityManager();
  Query q1 =
      em.createQuery(
          "SELECT SUM(self.totalAmount) FROM Order AS self "
              + "WHERE YEAR(self.orderDate) = YEAR(current_date) AND "
              + "MONTH(self.orderDate) = MONTH(current_date) - 1");

  Query q2 =
      em.createQuery(
          "SELECT SUM(self.totalAmount) FROM Order AS self "
              + "WHERE YEAR(self.orderDate) = YEAR(current_date) AND "
              + "MONTH(self.orderDate) = MONTH(current_date)");

  List<?> r1 = q1.getResultList();
  BigDecimal last = r1.get(0) == null ? BigDecimal.ZERO : (BigDecimal) r1.get(0);

  List<?> r2 = q2.getResultList();
  BigDecimal total = r2.get(0) == null ? BigDecimal.ZERO : (BigDecimal) r2.get(0);

  BigDecimal percent = BigDecimal.ZERO;
  if (total.compareTo(BigDecimal.ZERO) == 1) {
    percent =
        total.subtract(last).multiply(new BigDecimal(100)).divide(total, RoundingMode.HALF_UP);
  }

  Map<String, Object> data = new HashMap<>();
  data.put("total", total);
  data.put("percent", percent);
  data.put("down", total.compareTo(last) == -1);

  response.setData(Lists.newArrayList(data));
}
 
Example #26
Source Project: o2oa   Author: o2oa   File: StatFactory.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public List<String> listWithQuery(String queryId) throws Exception {
	EntityManager em = this.entityManagerContainer().get(Stat.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<Stat> root = cq.from(Stat.class);
	Predicate p = cb.equal(root.get(Stat_.query), queryId);
	cq.select(root.get(Stat_.id)).where(p);
	List<String> os = em.createQuery(cq).getResultList();
	return os;
}
 
Example #27
Source Project: o2oa   Author: o2oa   File: CalendarFactory.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 查询我自己(可管理)的日历
 * @param personName
 * @return
 * @throws Exception
 */
public List<String> listMyCalender( String personName ) throws Exception {
	EntityManager em = this.entityManagerContainer().get(Calendar.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<Calendar> root = cq.from(Calendar.class);
	Predicate permission = cb.equal( root.get(Calendar_.createor), personName );
	cq.select(root.get(Calendar_.id));
	return em.createQuery(cq.where(permission)).getResultList();
}
 
Example #28
Source Project: monolith   Author: ticket-monster-msa   File: NestedPerformanceDTO.java    License: Apache License 2.0 5 votes vote down vote up
public Performance fromDTO(Performance entity, EntityManager em)
{
   if (entity == null)
   {
      entity = new Performance();
   }
   if (this.id != null)
   {
      TypedQuery<Performance> findByIdQuery = em
            .createQuery(
                  "SELECT DISTINCT p FROM Performance p WHERE p.id = :entityId",
                  Performance.class);
      findByIdQuery.setParameter("entityId", this.id);
      try
      {
         entity = findByIdQuery.getSingleResult();
      }
      catch (javax.persistence.NoResultException nre)
      {
         entity = null;
      }
      return entity;
   }
   entity.setDate(this.date);
   entity = em.merge(entity);
   return entity;
}
 
Example #29
Source Project: o2oa   Author: o2oa   File: MeetingFactory.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public List<String> listFutureWithRoom(String roomId, boolean allowOnly) throws Exception {
	EntityManager em = this.entityManagerContainer().get(Meeting.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<Meeting> root = cq.from(Meeting.class);
	Predicate p = cb.greaterThanOrEqualTo(root.get(Meeting_.startTime), new Date());
	p = cb.and(p, cb.equal(root.get(Meeting_.room), roomId));
	p = cb.and(p, cb.equal(root.get(Meeting_.manualCompleted), false));
	if (allowOnly) {
		p = cb.and(p, cb.equal(root.get(Meeting_.confirmStatus), ConfirmStatus.allow));
	}
	cq.select(root.get(Meeting_.id)).where(p);
	return em.createQuery(cq).getResultList();
}
 
Example #30
Source Project: o2oa   Author: o2oa   File: RoleFactory.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private Role pickObject(String flag) throws Exception {
	Role o = this.entityManagerContainer().flag(flag, Role.class);
	if (o != null) {
		this.entityManagerContainer().get(Role.class).detach(o);
	} else {
		String name = flag;
		Matcher matcher = role_distinguishedName_pattern.matcher(flag);
		if (matcher.find()) {
			name = matcher.group(1);
			String unique = matcher.group(2);
			o = this.entityManagerContainer().flag(unique, Role.class);
			if (null != o) {
				this.entityManagerContainer().get(Role.class).detach(o);
			}
		}
		if (null == o) {
			EntityManager em = this.entityManagerContainer().get(Role.class);
			CriteriaBuilder cb = em.getCriteriaBuilder();
			CriteriaQuery<Role> cq = cb.createQuery(Role.class);
			Root<Role> root = cq.from(Role.class);
			Predicate p = cb.equal(root.get(Role_.name), name);
			List<Role> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
			if (os.size() == 1) {
				o = os.get(0);
				em.detach(o);
			}
		}
	}
	return o;
}