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 File: TestStoredProcedureQuery.java    From HibernateTips with 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 File: PostgreSQLGuavaRangeTypeTest.java    From hibernate-types with 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 #3
Source File: RequestDataService.java    From peer-os with 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 #4
Source File: DaoManager.java    From ranger with 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 #5
Source File: OkrTaskFactory.java    From o2oa with 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 #6
Source File: CrawlWork.java    From o2oa with 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 File: ChannelDatabase.java    From joynr with 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 #8
Source File: V2List.java    From o2oa with 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 #9
Source File: UserResource.java    From bouncr with 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 #10
Source File: JpaProfileDao.java    From che with 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 #11
Source File: ActionListSummaryWithPortalCategory.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #12
Source File: BaseAction.java    From o2oa with 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 #13
Source File: V2Count.java    From o2oa with 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 #14
Source File: ValidatePublish.java    From juddi with 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 #15
Source File: OkrTaskHandledFactory.java    From o2oa with 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 #16
Source File: StockTest.java    From cloud-espm-v2 with 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 #17
Source File: OkrTaskFactory.java    From o2oa with 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 #18
Source File: PersistenceInjectionTests.java    From spring-analysis-note with 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 #19
Source File: StatisticUnitForDayFactory.java    From o2oa with 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 #20
Source File: CiServiceImpl.java    From we-cmdb with 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 #21
Source File: BeginFactory.java    From o2oa with 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 #22
Source File: ActionFilterAttribute.java    From o2oa with 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 #23
Source File: AggregatedDefaultEntityManagerInjectionTest.java    From deltaspike with 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 #24
Source File: OkrWorkReportBaseInfoFactory.java    From o2oa with 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 File: KradEclipseLinkCustomizerTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testQueryCustomizerValueClass() throws Exception {
    EntityManagerFactory factory = (EntityManagerFactory) context.getBean("entityManagerFactory");
    assertNotNull(factory);

    TestEntity8 testEntity1 = new TestEntity8();
    testEntity1.setName("MyAwesomeTestEntity1");

    TestRelatedExtension extension = new TestRelatedExtension();
    extension.setAccountTypeCode("NM");

    EntityManager entityManager = factory.createEntityManager();

    try {
        testEntity1 = new TestEntity8();
        testEntity1.setName("MyCustomFilter");
        entityManager.persist(testEntity1);
        extension.setNumber(testEntity1.getNumber());
        entityManager.persist(extension);
        entityManager.flush();
    } finally {
        entityManager.close();
    }

    //Now confirm that the entity fetch found travel extension
    try {
        entityManager = factory.createEntityManager();
        testEntity1 = entityManager.find(TestEntity8.class, testEntity1.getNumber());
        assertTrue("Matched found for base entity", testEntity1 != null && StringUtils.equals("MyCustomFilter",
                testEntity1.getName()));
        assertTrue("Matching travel extension", testEntity1.getAccountExtension() == null);
    } finally {
        entityManager.close();
    }

}
 
Example #26
Source File: EjbqlApp.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 
 */
private static Map<String, Object> getParameters(EntityManager em) {
	Map<String, Object> parameters = new HashMap<String, Object>();
	parameters.put(JRJpaQueryExecuterFactory.PARAMETER_JPA_ENTITY_MANAGER, em);
	parameters.put("ReportTitle", "JRMDb - The JasperReports Movie Database");
	Calendar calendar = Calendar.getInstance();
	calendar.set(1990, 1, 1);
	parameters.put("DateFrom", new Date(calendar.getTimeInMillis()));
	parameters.put("DateTo", new Date(System.currentTimeMillis()));
	parameters.put("OrderClause", "m.genre, m.title");
	
	return parameters;
}
 
Example #27
Source File: OkrConfigSecretaryFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public List<String> listAll() throws Exception {
	EntityManager em = this.entityManagerContainer().get(OkrConfigSecretary.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<OkrConfigSecretary> root = cq.from( OkrConfigSecretary.class);
	cq.select(root.get(OkrConfigSecretary_.id));
	return em.createQuery(cq).getResultList();
}
 
Example #28
Source File: LogFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public List<String> getRecordIdsWithCount( int maxCount ) throws Exception {
	EntityManager em = this.entityManagerContainer().get( Log.class );
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery( String.class );
	Root<Log> root = cq.from( Log.class );
	cq.orderBy( cb.desc( root.get( Log_.createTime )));
	cq.select(root.get(Log_.id));
	return em.createQuery(cq).setMaxResults( maxCount ).getResultList();
}
 
Example #29
Source File: JPAVariableTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void setupIllegalJPAEntities() {
  EntityManager manager = entityManagerFactory.createEntityManager();
  manager.getTransaction().begin();

  compoundIdJPAEntity = new CompoundIdJPAEntity();
  EmbeddableCompoundId id = new EmbeddableCompoundId();
  id.setIdPart1(123L);
  id.setIdPart2("part2");
  compoundIdJPAEntity.setId(id);
  manager.persist(compoundIdJPAEntity);

  manager.flush();
  manager.getTransaction().commit();
  manager.close();
}
 
Example #30
Source File: CountryResourceIntTest.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
/**
 * Create an entity for this test.
 *
 * This is a static method, as tests for other entities might also need it,
 * if they test an entity which requires the current entity.
 */
public static Country createEntity(EntityManager em) {
    Country country = new Country()
        .code(DEFAULT_CODE)
        .name(DEFAULT_NAME)
        .continent(DEFAULT_CONTINENT)
        .region(DEFAULT_REGION)
        .surfaceArea(DEFAULT_SURFACE_AREA)
        .population(DEFAULT_POPULATION)
        .lifeExpectancy(DEFAULT_LIFE_EXPECTANCY)
        .localName(DEFAULT_LOCAL_NAME)
        .governmentForm(DEFAULT_GOVERNMENT_FORM);
    return country;
}