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

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

源代码1 项目: HibernateTips   文件: TestAssociation.java
@Test
public void associationWithAttributes() {
	log.info("... associationWithAttributes ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	Book b = em.find(Book.class, 1L);
	Publisher p = em.find(Publisher.class, 1L);
	
	BookPublisher bp = new BookPublisher();
	bp.setId(new BookPublisherId());
	bp.setBook(b);
	bp.setPublisher(p);
	bp.setFormat(Format.PAPERBACK);
	
	em.persist(bp);
	
	em.getTransaction().commit();
	em.close();
}
 
/**
 * Inserts a new entity into App Engine datastore or updates existing entity.It uses HTTP POST
 * method.
 *
 * @param device the entity to be inserted/updated.
 * @return The inserted/updated entity.
 * @throws ServiceException when the call is unauthenticated and the backend is configured not to
 *         allow them
 */
public DeviceRegistration registerDevice(DeviceRegistration device, User user)
    throws ServiceException {

  if (user == null && !Configuration.ALLOW_UNAUTHENTICATED_CALLS) {
    throw new UnauthorizedException("Only authenticated calls are allowed");
  }

  EntityManager mgr = getEntityManager();
  try {
    device.setTimestamp(new Date());
    mgr.persist(device);
  } finally {
    mgr.close();
  }
  return device;
}
 
源代码3 项目: marathonv5   文件: DataAppLoader.java
public static void loadTransmission(EntityManager entityManager) {
    
    Transmission t1 = new Transmission(1, "MAN");
    t1.setGears(new Short ("5"));
    
    Transmission t2 = new Transmission(2, "MAN");
    t2.setGears(new Short ("6"));
    
    Transmission t3 = new Transmission(3, "AUTO");
    t3.setGears(new Short ("4"));

    Transmission t4 = new Transmission(4, "AUTO");
    t4.setGears(new Short ("5"));
    
    Transmission t5 = new Transmission(5, "AUTO");
    t5.setGears(new Short ("6"));
    
    Transmission t6 = new Transmission(6, "CVT");
    
    entityManager.persist(t1);
    entityManager.persist(t2);
    entityManager.persist(t3);
    entityManager.persist(t4);
    entityManager.persist(t5);
    entityManager.persist(t6);
}
 
private static void storeTestItems(final EntityManagerFactory emf, Counts expected) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Item tshirt = new Item("tshirt", "Hibernate T-shirt");
    em.persist(tshirt);
    final Item sticker = new Item("sticker", "Hibernate Sticker");
    em.persist(sticker);
    final Item mug = new Item("mug", "Hibernate Mug");
    em.persist(mug);

    transaction.commit();
    em.close();

    assertRegionStats(expected, Item.class.getName(), stats);
}
 
源代码5 项目: camunda-bpm-platform   文件: JPAVariableTest.java
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();
}
 
源代码6 项目: HibernateTips   文件: TestBidirectionalOneToOne.java
@Test
public void bidirectionalOneToOne() {
	log.info("... bidirectionalOneToOne ...");

	// Add a new Review
	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	Book b = em.find(Book.class, 1L);
	
	Manuscript m = new Manuscript();
	m.setBook(b);
	
	b.setManuscript(m);
	
	em.persist(m);
	
	em.getTransaction().commit();
	em.close();
	
	// Get Book entity with Authors
	em = emf.createEntityManager();
	em.getTransaction().begin();

	b = em.find(Book.class, 1L);
	
	m = b.getManuscript();
	Assert.assertEquals(b, m.getBook());
	
	em.getTransaction().commit();
	em.close();
}
 
/**
 * This inserts a new entity into App Engine datastore. If the entity already
 * exists in the datastore, an exception is thrown.
 * It uses HTTP POST method.
 *
 * @param checkin the entity to be inserted.
 * @return The inserted entity.
 */
@ApiMethod(name = "insertCheckIn")
public CheckIn insertCheckIn(CheckIn checkin) {
  EntityManager mgr = getEntityManager();
  try {
   
    mgr.persist(checkin);
  } finally {
    mgr.close();
  }
  return checkin;
}
 
源代码8 项目: cloud-espm-v2   文件: StockTest.java
/**
 * Test if Stock gets updated in database
 */
@Test
public void testUpdateStock() {
	Stock stock = null;
	String productId = "HY-1004";
	TestFactory tf = new TestFactory();
	EntityManager em = emf.createEntityManager();
	try {
		if (!tf.createStock(em, productId)) {
			fail("Unable to create "); // doubt
			return;
		}
		em.getTransaction().begin();
		// Find Stock for update
		stock = em.find(Stock.class, productId);
		// Update Business Partner
		stock.setQuantity(BigDecimal.valueOf(10));
		em.persist(stock);
		em.getTransaction().commit();
		// Find Business Partner after update
		stock = em.find(Stock.class, productId);
		assertEquals(
				"Update Stock: Stock attribute quantity not updated in the database",
				BigDecimal.valueOf(10), stock.getQuantity());
		tf.deleteStock(em, productId);
	} finally {
		em.close();
	}

}
 
/**
 * This method is used for updating an existing entity. If the entity does not
 * exist in the datastore, an exception is thrown.
 * It uses HTTP PUT method.
 *
 * @param deviceinfo the entity to be updated.
 * @return The updated entity.
 */
@ApiMethod(name = "updateDeviceInfo")
public DeviceInfo updateDeviceInfo(DeviceInfo deviceinfo) {
  EntityManager mgr = getEntityManager();
  try {
    if (!containsDeviceInfo(deviceinfo)) {
      throw new EntityNotFoundException("Object does not exist");
    }
    mgr.persist(deviceinfo);
  } finally {
    mgr.close();
  }
  return deviceinfo;
}
 
源代码10 项目: o2oa   文件: ActionDelete.java
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo> result = new ActionResult<>();
		Business business = new Business(emc);
		Folder2 folder = emc.find(id, Folder2.class);
		if (null == folder) {
			throw new ExceptionFolderNotExist(id);
		}
		if (!effectivePerson.isManager() && !StringUtils.equalsIgnoreCase(effectivePerson.getDistinguishedName(), folder.getPerson())) {
			throw new ExceptionAccessDenied(effectivePerson.getName());
		}
		if("正常".equals(folder.getStatus())){
			List<Folder2> folderList = new ArrayList<>();
			folderList.add(folder);
			folderList.addAll(business.folder2().listSubNested1(folder.getId(), null));
			for(Folder2 fo : folderList){
				EntityManager fem = emc.beginTransaction(Folder2.class);
				fo.setStatus("已删除");
				fem.getTransaction().commit();
				List<Attachment2> attachments = business.attachment2().listWithFolder2(fo.getId(),null);
				for (Attachment2 att : attachments) {
					EntityManager aem = emc.beginTransaction(Attachment2.class);
					att.setStatus("已删除");
					aem.getTransaction().commit();
				}
			}

			Recycle recycle = new Recycle(folder.getPerson(), folder.getName(), folder.getId(), "folder");
			EntityManager rem = emc.beginTransaction(Recycle.class);
			rem.persist(recycle);
			rem.getTransaction().commit();
			emc.commit();
		}

		Wo wo = new Wo();
		wo.setValue(true);
		result.setData(wo);
		return result;
	}
}
 
源代码11 项目: cloud-espm-v2   文件: SalesOrderItemTest.java
/**
 * Test if SalesOrderItem gets updated in database.
 */
@Test
public void testUpdateSalesOrderItem() {
	SalesOrderItem soItemAct = null;
	String soId = "111110";
	TestFactory tf = new TestFactory();
	EntityManager em = emf.createEntityManager();
	try {
		if (!tf.createSalesOrderItem(em, soId)) {
			fail("Unable to create Sales Order Item");
			return;
		}
		em.getTransaction().begin();
		// Find Sales Order Item for update.
		soItem = em.find(SalesOrderItem.class,
				new SalesOrderItemId(soId, 1));
		// Update Sales Order Item.
		soItem.setCurrencyCode("EUR");
		em.persist(soItem);
		em.getTransaction().commit();
		// Find Sales Order Item after update.
		soItemAct = em.find(SalesOrderItem.class, new SalesOrderItemId(
				soId, 1));
		assertEquals(
				"Update Sales Orde Item: Sales Order Item attribute Sales Order Item Position not updated in the database",
				"EUR", soItemAct.getCurrencyCode());
		tf.deleteSalesOrderItem(em, soId);
	} finally {
		em.close();
	}
}
 
源代码12 项目: jboss-daytrader   文件: TradeJPADirect.java
private OrderDataBean createOrder(AccountDataBean account,
                                  QuoteDataBean quote, HoldingDataBean holding, String orderType,
                                  double quantity, EntityManager entityManager) {
    OrderDataBean order;
    if (Log.doTrace())
        Log.trace("TradeJPADirect:createOrder(orderID=" + " account="
                  + ((account == null) ? null : account.getAccountID())
                  + " quote=" + ((quote == null) ? null : quote.getSymbol())
                  + " orderType=" + orderType + " quantity=" + quantity);
    try {
        order = new OrderDataBean(orderType, 
                                  "open", 
                                  new Timestamp(System.currentTimeMillis()), 
                                  null, 
                                  quantity, 
                                  quote.getPrice().setScale(FinancialUtils.SCALE, FinancialUtils.ROUND),
                                  TradeConfig.getOrderFee(orderType), 
                                  account, 
                                  quote, 
                                  holding);
            entityManager.persist(order);
    }
    catch (Exception e) {
        entityManager.getTransaction().rollback();
        Log.error("TradeJPADirect:createOrder -- failed to create Order", e);
        throw new RuntimeException("TradeJPADirect:createOrder -- failed to create Order", e);
    }
    return order;
}
 
源代码13 项目: pnc   文件: AbstractModelTest.java
/**
 * Inserts example BuildConfigurations to the database
 *
 * @param em Entity manager
 * @param repositoryConfiguration RepositoryConfiguration object, which was already persisted to the database
 */
protected void insertExampleBuildConfigurations(EntityManager em, RepositoryConfiguration repositoryConfiguration) {
    BuildConfiguration buildConfig1 = BuildConfiguration.Builder.newBuilder()
            .id(1)
            .name("Test Build Configuration 1")
            .description("Test Build Configuration 1 Description")
            .project(Project.Builder.newBuilder().id(1).build())
            .repositoryConfiguration(repositoryConfiguration)
            .buildScript("mvn install")
            .buildEnvironment(BuildEnvironment.Builder.newBuilder().id(1).build())
            .build();

    BuildConfiguration buildConfig2 = BuildConfiguration.Builder.newBuilder()
            .id(2)
            .name("Test Build Configuration 2")
            .description("Test Build Configuration 2 Description")
            .project(Project.Builder.newBuilder().id(1).build())
            .repositoryConfiguration(repositoryConfiguration)
            .buildScript("mvn install")
            .buildEnvironment(BuildEnvironment.Builder.newBuilder().id(1).build())
            .build();

    em.getTransaction().begin();
    em.persist(buildConfig1);
    em.persist(buildConfig2);
    em.getTransaction().commit();
}
 
源代码14 项目: tutorials   文件: HibernateOperations.java
/**
 * Saves the movie entity into the database. Here we are using Application Managed EntityManager, hence should handle transactions by ourselves.
 */
public void saveMovie() {
    EntityManager em = HibernateOperations.getEntityManager();
    em.getTransaction()
        .begin();
    Movie movie = new Movie();
    movie.setId(1L);
    movie.setMovieName("The Godfather");
    movie.setReleaseYear(1972);
    movie.setLanguage("English");
    em.persist(movie);
    em.getTransaction()
        .commit();
}
 
源代码15 项目: elexis-3-core   文件: InvoiceEntityListener.java
/**
 * Finds the current invoice number, checks for uniqueness, retrieves it and increments by one
 * 
 * @return
 */
private int findAndIncrementInvoiceNumber(){
	int ret = 0;
	EntityManager em = (EntityManager) ElexisEntityManagerServiceHolder.getEntityManager()
		.getEntityManager(false);
	try {
		em.getTransaction().begin();
		Config invoiceNr = em.find(Config.class, "RechnungsNr");
		if (invoiceNr == null) {
			Config invoiceNrConfig = new Config();
			invoiceNrConfig.setParam("RechnungsNr");
			invoiceNrConfig.setWert("1");
			em.persist(invoiceNrConfig);
			ret = 1;
		} else {
			em.lock(invoiceNr, LockModeType.PESSIMISTIC_WRITE);
			ret = Integer.parseInt(invoiceNr.getWert());
			ret += 1;
			
			while (true) {
				TypedQuery<Invoice> query =
					em.createNamedQuery("Invoice.number", Invoice.class);
				query.setParameter("number", Integer.toString(ret));
				List<Invoice> results = query.getResultList();
				if (results.isEmpty()) {
					break;
				} else {
					ret += 1;
				}
			}
			invoiceNr.setWert(Integer.toString(ret));
		}
		em.getTransaction().commit();
		return ret;
	} finally {
		ElexisEntityManagerServiceHolder.getEntityManager().closeEntityManager(em);
	}
}
 
源代码16 项目: rice   文件: KradEclipseLinkCustomizerTest.java
@Test
public void testQueryCustomizerNoMatchMultipleCustomizers() throws Exception {
    EntityManagerFactory factory = (EntityManagerFactory) context.getBean("entityManagerFactory");
    assertNotNull(factory);

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

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

    EntityManager entityManager = factory.createEntityManager();

    try {
        testEntity1 = new TestEntity9();
        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(TestEntity9.class, testEntity1.getNumber());
        assertTrue("Match found for base entity", testEntity1 != null && StringUtils.equals("MyCustomFilter",
                testEntity1.getName()));
        assertTrue("Found no travel extension that matches", testEntity1.getAccountExtension() == null);
    } finally {
        entityManager.close();
    }

}
 
/**
 * This method is used for updating an existing entity. If the entity does not
 * exist in the datastore, an exception is thrown.
 * It uses HTTP PUT method.
 *
 * @param checkin the entity to be updated.
 * @return The updated entity.
 */
@ApiMethod(name = "updateCheckIn")
public CheckIn updateCheckIn(CheckIn checkin) {
  EntityManager mgr = getEntityManager();
  try {
    if (!containsCheckIn(checkin)) {
      throw new EntityNotFoundException("Object does not exist");
    }
    mgr.persist(checkin);
  } finally {
    mgr.close();
  }
  return checkin;
}
 
源代码18 项目: camunda-bpm-platform   文件: JPAVariableTest.java
public void setupJPAEntities() {

    EntityManager manager = entityManagerFactory.createEntityManager();
    manager.getTransaction().begin();

    // Simple test data
    simpleEntityFieldAccess = new FieldAccessJPAEntity();
    simpleEntityFieldAccess.setId(1L);
    simpleEntityFieldAccess.setValue("value1");
    manager.persist(simpleEntityFieldAccess);

    simpleEntityPropertyAccess = new PropertyAccessJPAEntity();
    simpleEntityPropertyAccess.setId(1L);
    simpleEntityPropertyAccess.setValue("value2");
    manager.persist(simpleEntityPropertyAccess);

    subclassFieldAccess = new SubclassFieldAccessJPAEntity();
    subclassFieldAccess.setId(1L);
    subclassFieldAccess.setValue("value3");
    manager.persist(subclassFieldAccess);

    subclassPropertyAccess = new SubclassPropertyAccessJPAEntity();
    subclassPropertyAccess.setId(1L);
    subclassPropertyAccess.setValue("value4");
    manager.persist(subclassPropertyAccess);

    // Test entities with all possible ID types
    byteIdJPAEntity = new ByteIdJPAEntity();
    byteIdJPAEntity.setByteId((byte)1);
    manager.persist(byteIdJPAEntity);

    shortIdJPAEntity = new ShortIdJPAEntity();
    shortIdJPAEntity.setShortId((short)123);
    manager.persist(shortIdJPAEntity);

    integerIdJPAEntity = new IntegerIdJPAEntity();
    integerIdJPAEntity.setIntId(123);
    manager.persist(integerIdJPAEntity);

    longIdJPAEntity = new LongIdJPAEntity();
    longIdJPAEntity.setLongId(123456789L);
    manager.persist(longIdJPAEntity);

    floatIdJPAEntity = new FloatIdJPAEntity();
    floatIdJPAEntity.setFloatId((float) 123.45678);
    manager.persist(floatIdJPAEntity);

    doubleIdJPAEntity = new DoubleIdJPAEntity();
    doubleIdJPAEntity.setDoubleId(12345678.987654);
    manager.persist(doubleIdJPAEntity);

    charIdJPAEntity = new CharIdJPAEntity();
    charIdJPAEntity.setCharId('g');
    manager.persist(charIdJPAEntity);

    dateIdJPAEntity = new DateIdJPAEntity();
    dateIdJPAEntity.setDateId(new java.util.Date());
    manager.persist(dateIdJPAEntity);

    sqlDateIdJPAEntity = new SQLDateIdJPAEntity();
    sqlDateIdJPAEntity.setDateId(new java.sql.Date(Calendar.getInstance().getTimeInMillis()));
    manager.persist(sqlDateIdJPAEntity);

    stringIdJPAEntity = new StringIdJPAEntity();
    stringIdJPAEntity.setStringId("azertyuiop");
    manager.persist(stringIdJPAEntity);

    bigDecimalIdJPAEntity = new BigDecimalIdJPAEntity();
    bigDecimalIdJPAEntity.setBigDecimalId(new BigDecimal("12345678912345678900000.123456789123456789"));
    manager.persist(bigDecimalIdJPAEntity);

    bigIntegerIdJPAEntity = new BigIntegerIdJPAEntity();
    bigIntegerIdJPAEntity.setBigIntegerId(new BigInteger("12345678912345678912345678900000"));
    manager.persist(bigIntegerIdJPAEntity);

    manager.flush();
    manager.getTransaction().commit();
    manager.close();
  }
 
源代码19 项目: mycore   文件: MCRMetadataHistoryManager.java
private void store(MCRMetaHistoryItem item) {
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    em.persist(item);
}
 
源代码20 项目: juddi   文件: JBossAuthenticator.java
/**
    *
    */
public String authenticate(final String userID, final String credential)
		throws AuthenticationException {
	if (userID == null) {
		throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId", userID));
	}

	EntityManager em = PersistenceManager.getEntityManager();
	EntityTransaction tx = em.getTransaction();
	try {
		// Create a principal for the userID
		Principal principal = new Principal() {
			public String getName() {
				return userID;
			}
		};

		if (!authManager.isValid(principal, credential)) {
			throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials"));
		} else {
			tx.begin();
			Publisher publisher = em.find(Publisher.class, userID);
			if (publisher == null) {
				publisher = new Publisher();
				publisher.setAuthorizedName(userID);
				publisher.setIsAdmin("false");
				publisher.setIsEnabled("true");
				publisher.setMaxBindingsPerService(199);
				publisher.setMaxBusinesses(100);
				publisher.setMaxServicesPerBusiness(100);
				publisher.setMaxTmodels(100);
				publisher.setPublisherName("Unknown");
				em.persist(publisher);
				tx.commit();
			}
		}
	} finally {
		if (tx.isActive()) {
			tx.rollback();
		}
		em.close();
	}
	return userID;
}