javax.persistence.EntityManager#find ( )源码实例Demo

下面列出了javax.persistence.EntityManager#find ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: TeaStore   文件: OrderItemRepository.java
/**
 * {@inheritDoc}
 */
@Override
public long createEntity(OrderItem entity) {
	PersistenceOrderItem item = new PersistenceOrderItem();
	item.setQuantity(entity.getQuantity());
	item.setUnitPriceInCents(entity.getUnitPriceInCents());
	EntityManager em = getEM();
    try {
        em.getTransaction().begin();
        PersistenceProduct prod = em.find(PersistenceProduct.class, entity.getProductId());
        PersistenceOrder order = em.find(PersistenceOrder.class, entity.getOrderId());
        if (prod != null && order != null) {
        	item.setProduct(prod);
        	item.setOrder(order);
        	em.persist(item);
        } else {
        	item.setId(-1L);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
    return item.getId();
}
 
源代码2 项目: lutece-core   文件: JPAGenericDAO.java
/**
 * {@inheritDoc }
 */
@Override
public void remove( K key )
{
    EntityManager em = getEM( );
    E entity = em.find( _entityClass, key );
    if ( entity == null )
    {
        LOG.debug( "Did not find entity to remove for key " + key.toString( ) );
        return;
    }
    LOG.debug( "Removing entity : " + entity.toString( ) );
    if ( em == _defaultEM )
    {
        em.getTransaction( ).begin( );
    }
    em.remove( entity );
    if ( em == _defaultEM )
    {
        em.getTransaction( ).commit( );
    }
    LOG.debug( "Entity removed : " + entity.toString( ) );
}
 
源代码3 项目: training   文件: StockPriceHistoryImpl.java
public StockPriceHistoryImpl(String s, Date startDate,
                             Date endDate, EntityManager em) {
    Date curDate = new Date(startDate.getTime());
    symbol = s;
    while (!curDate.after(endDate)) {
        StockPriceEagerLazyImpl sp =
            em.find(StockPriceEagerLazyImpl.class,
                    new StockPricePK(s, (Date) curDate.clone()));
        if (sp != null) {
            Date d = (Date) curDate.clone();
            if (firstDate == null) {
                firstDate = d;
            }
            prices.put(d, sp);
            lastDate = d;
        }
        curDate.setTime(curDate.getTime() + msPerDay);
    }
}
 
private static void findByIdItems(EntityManager em, String[] expectedDesc) {
    final Item i1 = em.find(Item.class, 1L);
    if (!i1.getDescription().equals(expectedDesc[0]))
        throw new RuntimeException("Incorrect description: " + i1.getDescription() + ", expected: " + expectedDesc[0]);

    final Item i2 = em.find(Item.class, 2L);
    if (!i2.getDescription().equals(expectedDesc[1]))
        throw new RuntimeException("Incorrect description: " + i2.getDescription() + ", expected: " + expectedDesc[1]);

    final Item i3 = em.find(Item.class, 3L);
    if (!i3.getDescription().equals(expectedDesc[2]))
        throw new RuntimeException("Incorrect description: " + i3.getDescription() + ", expected: " + expectedDesc[2]);

    List<Item> allitems = Arrays.asList(i1, i2, i3);
    if (allitems.size() != 3) {
        throw new RuntimeException("Incorrect number of results");
    }
    StringBuilder sb = new StringBuilder("list of stored Items names:\n\t");
    for (Item p : allitems)
        p.describeFully(sb);

    sb.append("\nList complete.\n");
    System.out.print(sb);
}
 
源代码5 项目: o2oa   文件: EntityManagerContainerTools.java
public static <T extends JpaObject> Integer batchDelete(EntityManagerContainer emc, Class<T> clz, Integer batchSize,
		List<String> ids) throws Exception {
	if (null == batchSize || batchSize < 1 || null == ids || ids.isEmpty()) {
		return 0;
	}
	Integer count = 0;
	EntityManager em = emc.get(clz);
	for (int i = 0; i < ids.size(); i++) {
		if (i % batchSize == 0) {
			em.getTransaction().begin();
		}
		T t = em.find(clz, ids.get(i));
		if (null != t) {
			em.remove(t);
		}
		if ((i % batchSize == (batchSize - 1)) || (i == ids.size() - 1)) {
			em.getTransaction().commit();
			count++;
		}
	}
	return count;
}
 
源代码6 项目: juddi   文件: ValidatePublish.java
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"));
                        }
                }
        }
 
源代码7 项目: juddi   文件: ValidateValueSetValidation.java
/**
 * return the publisher
 *
 * @param tmodelKey
 * @return
 * @throws ValueNotAllowedException
 */
public static TModel GetTModel_API_IfExists(String tmodelKey) throws ValueNotAllowedException {
        EntityManager em = PersistenceManager.getEntityManager();

        TModel apitmodel = null;
        if (em == null) {
                //this is normally the Install class firing up
                log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM"));
                return null;
        } else {


                EntityTransaction tx = em.getTransaction();
                try {
                        Tmodel modelTModel = null;
                        tx.begin();
                        modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);
                        if (modelTModel != null) {
                                apitmodel = new TModel();
                                try {
                                        MappingModelToApi.mapTModel(modelTModel, apitmodel);
                                } catch (DispositionReportFaultMessage ex) {
                                        log.warn(ex);
                                        apitmodel=null;
                                }


                        }
                        tx.commit();
                } finally {
                        if (tx.isActive()) {
                                tx.rollback();
                        }
                        em.close();
                }

        }
        return apitmodel;
}
 
源代码8 项目: Advanced_Java   文件: JpaPersonDAO.java
@Override
public Person findById(Integer id) {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    Person person = em.find(Person.class, id);
    em.getTransaction().commit();
    em.close();
    return person;
}
 
源代码9 项目: HibernateTips   文件: TestQueryTimeout.java
@Test
public void queryTimeoutOnEMfind() {
	log.info("... queryTimeoutOnEMfind ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();
	
	HashMap<String, Object> hints = new HashMap<>();
	hints.put("javax.persistence.query.timeout", 1);
	
	em.find(Author.class, 50L, hints);
	
	em.getTransaction().commit();
	em.close();
}
 
源代码10 项目: jerseyoauth2   文件: DatabaseClientService.java
@Override
public IRegisteredClientApp getRegisteredClient(String clientId) {
	EntityManager entityManager = emf.createEntityManager();
	try {
		return entityManager.find(RegisteredClient.class, clientId);
	} finally {
		entityManager.close();
	}
}
 
源代码11 项目: tutorials   文件: DateTimeEntityRepository.java
public JPA22DateTimeEntity find(Long id) {
    EntityManager entityManager = emf.createEntityManager();

    JPA22DateTimeEntity dateTimeTypes = entityManager.find(JPA22DateTimeEntity.class, id);

    entityManager.close();
    return dateTimeTypes;
}
 
源代码12 项目: oxTrust   文件: InumService.java
/**
 * get an inum from inum DB by inum value
 * 
 * @return InumSqlEntry
 */
public InumSqlEntry findInumByObject(EntityManager inumEntryManager, String inum) {

	boolean successs = false;

	EntityTransaction entityTransaction = inumEntryManager.getTransaction();

	entityTransaction.begin();
	InumSqlEntry result = null;

	try {

		InumSqlEntry tempInum = new InumSqlEntry();
		tempInum.setInum(inum);

		// find inum
		result = inumEntryManager.find(InumSqlEntry.class, tempInum);
		if (result != null) {
			successs = true;
		}
	} finally {
		if (successs) {
			// Commit transaction
			entityTransaction.commit();
		} else {
			// Rollback transaction
			entityTransaction.rollback();
		}
	}

	return result;

}
 
源代码13 项目: che   文件: JpaUserDao.java
@Transactional(rollbackOn = {RuntimeException.class, ServerException.class})
protected void doRemove(String id) {
  final EntityManager manager = managerProvider.get();
  final UserImpl user = manager.find(UserImpl.class, id);
  if (user != null) {
    manager.remove(user);
    manager.flush();
  }
}
 
private boolean containsRecommendation(Recommendation recommendation) {
  EntityManager mgr = getEntityManager();
  boolean contains = true;
  try {
    Recommendation item = mgr.find(Recommendation.class, recommendation.getKey());
    if (item == null) {
      contains = false;
    }
  } finally {
    mgr.close();
  }
  return contains;
}
 
@Transactional
protected void doStore(OrganizationDistributedResourcesImpl distributedResources)
    throws ServerException {
  EntityManager manager = managerProvider.get();
  final OrganizationDistributedResourcesImpl existingDistributedResources =
      manager.find(
          OrganizationDistributedResourcesImpl.class, distributedResources.getOrganizationId());
  if (existingDistributedResources == null) {
    manager.persist(distributedResources);
  } else {
    existingDistributedResources.getResourcesCap().clear();
    existingDistributedResources.getResourcesCap().addAll(distributedResources.getResourcesCap());
  }
  manager.flush();
}
 
源代码16 项目: peer-os   文件: PeerDataService.java
public void saveOrUpdate( PeerData peerData )
{
    EntityManager em = emf.createEntityManager();

    try
    {

        em.getTransaction().begin();
        if ( em.find( PeerData.class, peerData.getId() ) == null )
        {
            em.persist( peerData );
        }
        else
        {
            peerData = em.merge( peerData );
        }
        em.getTransaction().commit();
    }
    catch ( Exception e )
    {
        LOG.error( e.toString(), e );
        if ( em.getTransaction().isActive() )
        {
            em.getTransaction().rollback();
        }
    }
    finally
    {
        em.close();
    }
}
 
/**
 * This method removes the entity with primary key id. It uses HTTP DELETE method.
 *
 * @param id the primary key of the entity to be deleted.
 */
public void remove(@Named("id") Long id, User user)
    throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  Recommendation recommendation = null;
  try {
    recommendation = mgr.find(Recommendation.class, id);
    mgr.remove(recommendation);
  } finally {
    mgr.close();
  }
}
 
源代码18 项目: cloud-espm-v2   文件: CustomerTest.java
/**
 * Test if a single Business Partner can be added and checks if it exists
 * via entitymanager.find.
 */
@Test
public void testExistingCustomerSearchFind() {
	String bupaId = "99999";
	Customer bupaAct = null;
	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();
	TestFactory tf = new TestFactory();
	try {
		// Add Business Partner
		assertTrue("Business Partner not created",
				tf.createCustomer(em, bupaId));
		// Search for Business Partner
		bupaAct = em.find(Customer.class, bupaId);
		assertNotNull("Search via find method: Added Business Partner "
				+ bupaId + " not persisted in database", bupaAct);
		if (bupaAct != null) {
			assertEquals(
					"Added Business Partner not persisted in the database ",
					bupaId, bupaAct.getCustomerId());
			tf.deleteCustomer(em, bupaId);
		}
	} finally {
		em.close();
	}

}
 
源代码19 项目: juddi   文件: ValidatePublish.java
public void validateBusinessEntity(EntityManager em, org.uddi.api_v3.BusinessEntity businessEntity,
        Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage {

        // A supplied businessEntity can't be null
        if (businessEntity == null) {
                throw new ValueNotAllowedException(new ErrorMessage("errors.businessentity.NullInput"));
        }

        boolean entityExists = false;
        validateNotSigned(businessEntity);
        String entityKey = businessEntity.getBusinessKey();
        if (entityKey == null || entityKey.length() == 0) {
                KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator();
                entityKey = keyGen.generate(publisher);
                businessEntity.setBusinessKey(entityKey);
        } else {
                // Per section 4.4: keys must be case-folded
                entityKey = entityKey.toLowerCase();
                businessEntity.setBusinessKey(entityKey);
                validateKeyLength(entityKey);
                Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, entityKey);
                if (obj != null) {
                        entityExists = true;

                        // Make sure publisher owns this entity.
                        AccessCheck(obj, entityKey);

                } else {
                        // Inside this block, we have a key proposed by the publisher on a new entity

                        // Validate key and then check to see that the proposed key is valid for this publisher
                        ValidateUDDIKey.validateUDDIv3Key(entityKey);
                        if (!publisher.isValidPublisherKey(em, entityKey)) {
                                throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey));
                        }

                }
        }

        if (!entityExists) {
                // Check to make sure key isn't used by another entity.
                if (!isUniqueKey(em, entityKey)) {
                        throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey));
                }
        }

        // was TODO: validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support
        //covered by ref integrity checks
        validateNames(businessEntity.getName());
        validateDiscoveryUrls(businessEntity.getDiscoveryURLs());
        validateContacts(businessEntity.getContacts(), config);
        validateCategoryBag(businessEntity.getCategoryBag(), config, false);
        validateIdentifierBag(businessEntity.getIdentifierBag(), config, false);
        validateDescriptions(businessEntity.getDescription());
        validateBusinessServices(em, businessEntity.getBusinessServices(), businessEntity, config, publisher);
        validateSignaturesBusiness(businessEntity, config);

}
 
源代码20 项目: jboss-daytrader   文件: TradeJPADirect.java
public OrderDataBean sell(String userID, Integer holdingID,
                          int orderProcessingMode) {
    EntityManager entityManager = emf.createEntityManager();

    OrderDataBean order = null;
    BigDecimal total;
    try {
        entityManager.getTransaction().begin();
        if (Log.doTrace())
            Log.trace("TradeJPADirect:sell", userID, holdingID, orderProcessingMode);

        AccountProfileDataBean profile = entityManager.find(
                                                           AccountProfileDataBean.class, userID);

        AccountDataBean account = profile.getAccount();
        HoldingDataBean holding = entityManager.find(HoldingDataBean.class,
                                                     holdingID);

        if (holding == null) {
            Log.error("TradeJPADirect:sell User " + userID
                      + " attempted to sell holding " + holdingID
                      + " which has already been sold");

            OrderDataBean orderData = new OrderDataBean();
            orderData.setOrderStatus("cancelled");

            entityManager.persist(orderData);
            entityManager.getTransaction().commit();
            return orderData;
        }

        QuoteDataBean quote = holding.getQuote();
        double quantity = holding.getQuantity();

        order = createOrder(account, quote, holding, "sell", quantity,
                            entityManager);
        // UPDATE the holding purchase data to signify this holding is
        // "inflight" to be sold
        // -- could add a new holdingStatus attribute to holdingEJB
        holding.setPurchaseDate(new java.sql.Timestamp(0));

        // UPDATE - account should be credited during completeOrder
        BigDecimal price = quote.getPrice();
        BigDecimal orderFee = order.getOrderFee();
        BigDecimal balance = account.getBalance();
        total = (new BigDecimal(quantity).multiply(price)).subtract(orderFee);

        account.setBalance(balance.add(total));

        // commit the transaction before calling completeOrder
        entityManager.getTransaction().commit();

        if (orderProcessingMode == TradeConfig.SYNCH) {                
            synchronized(soldholdingIDlock) {
                this.soldholdingID = holding.getHoldingID();
                completeOrder(order.getOrderID(), false);
            }                
        } else if (orderProcessingMode == TradeConfig.ASYNCH_2PHASE)
            queueOrder(order.getOrderID(), true);

    }
    catch (Exception e) {
        Log.error("TradeJPADirect:sell(" + userID + "," + holdingID + ") --> failed", e);
        // TODO figure out JPA cancel
        if (order != null)
            order.cancel();

        entityManager.getTransaction().rollback();

        throw new RuntimeException("TradeJPADirect:sell(" + userID + "," + holdingID + ")", e);
    } finally {
        if (entityManager != null) {
            entityManager.close();
            entityManager = null;
        }
    }

    if (!(order.getOrderStatus().equalsIgnoreCase("cancelled")))
        //after the purchase or sell of a stock, update the stocks volume and price
        updateQuotePriceVolume(order.getSymbol(), TradeConfig.getRandomPriceChangeFactor(), order.getQuantity());

    return order;
}