Java Code Examples for javax.persistence.EntityManager#persist()

The following examples show how to use javax.persistence.EntityManager#persist() . 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: TestAssociation.java    From HibernateTips with MIT License 6 votes vote down vote up
@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();
}
 
Example 2
Source File: DeviceRegistrationEndpoint.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 4
Source File: DataAppLoader.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 5
Source File: CheckInEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: JPAVariableTest.java    From camunda-bpm-platform 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 7
Source File: KradEclipseLinkCustomizerTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@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();
    }

}
 
Example 8
Source File: InvoiceEntityListener.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 9
Source File: HibernateOperations.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * 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();
}
 
Example 10
Source File: AbstractModelTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 11
Source File: TradeJPADirect.java    From jboss-daytrader with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: SalesOrderItemTest.java    From cloud-espm-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
	}
}
 
Example 13
Source File: ActionDelete.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
	}
}
 
Example 14
Source File: DeviceInfoEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 15
Source File: StockTest.java    From cloud-espm-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
	}

}
 
Example 16
Source File: CheckInEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 17
Source File: TestBidirectionalOneToOne.java    From HibernateTips with MIT License 5 votes vote down vote up
@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();
}
 
Example 18
Source File: MCRMetadataHistoryManager.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
private void store(MCRMetaHistoryItem item) {
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    em.persist(item);
}
 
Example 19
Source File: JBossAuthenticator.java    From juddi with Apache License 2.0 4 votes vote down vote up
/**
    *
    */
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;
}
 
Example 20
Source File: JPAVariableTest.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
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();
  }