@Test public void shouldSyncDbAttributesWhileUpdatingWorkspace() throws Exception { final AccountImpl account = new AccountImpl("accountId", "namespace", "test"); final WorkspaceImpl workspace = createWorkspace("id", account, "name"); // persist the workspace manager.getTransaction().begin(); manager.persist(account); manager.persist(workspace); manager.getTransaction().commit(); manager.clear(); // put a new attribute workspace .getConfig() .getProjects() .get(0) .getAttributes() .put("new-attr", singletonList("value")); workspaceDao.update(workspace); manager.clear(); // check it's okay assertEquals( workspaceDao.get(workspace.getId()).getConfig().getProjects().get(0).getAttributes().size(), 3); }
@Test public void shouldCascadeRemoveObjectsWhenTheyRemovedFromEntity() { final AccountImpl account = new AccountImpl("accountId", "namespace", "test"); final WorkspaceImpl workspace = createWorkspace("id", account, "name"); // Persist the account manager.getTransaction().begin(); manager.persist(account); manager.getTransaction().commit(); manager.clear(); // Persist the workspace manager.getTransaction().begin(); manager.persist(workspace); manager.getTransaction().commit(); manager.clear(); // Cleanup one to many dependencies manager.getTransaction().begin(); final WorkspaceConfigImpl config = workspace.getConfig(); config.getProjects().clear(); config.getCommands().clear(); config.getEnvironments().clear(); manager.merge(workspace); manager.getTransaction().commit(); manager.clear(); // If all the One To Many dependencies are removed then all the embedded objects // which depend on those object are also removed, which guaranteed by foreign key constraints assertEquals(asLong("SELECT COUNT(p) FROM ProjectConfig p"), 0L, "Project configs"); assertEquals(asLong("SELECT COUNT(c) FROM Command c"), 0L, "Commands"); assertEquals(asLong("SELECT COUNT(e) FROM Environment e"), 0L, "Environments"); }
@Test public void mapAndElementCollection() throws Exception { OneToManyAddress home = new OneToManyAddress(); home.setCity("Paris"); OneToManyAddress work = new OneToManyAddress(); work.setCity("San Francisco"); OneToManyUser user = new OneToManyUser(); user.getAddresses().put("home", home); user.getAddresses().put("work", work); user.getNicknames().add("idrA"); user.getNicknames().add("day[9]"); em.persist(home); em.persist(work); em.persist(user); OneToManyUser user2 = new OneToManyUser(); user2.getNicknames().add("idrA"); user2.getNicknames().add("day[9]"); em.persist(user2); em.flush(); em.clear(); user = em.find(OneToManyUser.class, user.getId()); assertThat(user.getNicknames()).as("Should have 2 nick1").hasSize(2); assertThat(user.getNicknames()).as("Should contain nicks").contains("idrA", "day[9]"); user.getNicknames().remove("idrA"); user.getAddresses().remove("work"); em.persist(user); em.flush(); em.clear(); user = em.find(OneToManyUser.class, user.getId()); // TODO do null value assertThat(user.getAddresses()).as("List should have 1 elements").hasSize(1); assertThat(user.getAddresses().get("home").getCity()) .as("home address should be under home") .isEqualTo(home.getCity()); assertThat(user.getNicknames()).as("Should have 1 nick1").hasSize(1); assertThat(user.getNicknames()).as("Should contain nick").contains("day[9]"); em.remove(user); // CascadeType.ALL 로 user 삭제 시 address 삭제 됨 // em.srem(em.load(Address.class, home.getId())); // em.srem(em.load(Address.class, work.getId())); user2 = em.find(OneToManyUser.class, user2.getId()); assertThat(user2.getNicknames()).as("Should have 2 nicks").hasSize(2); assertThat(user2.getNicknames()).as("Should contain nick").contains("idrA", "day[9]"); em.remove(user2); em.flush(); }
@Test @Ignore public void testMoreHutsPaidAndNew() { final int id1 = reservationService.createReservationAdmin(ReservationModelUtils.createReservationModel()); reservationService.updateReservationState(ReservationState.PAID.name(), id1); entityManager.clear(); final int id2 = reservationService.createReservationAdmin(ReservationModelUtils.createReservationModel()); reservationService.updateReservationState(ReservationState.PAID.name(), id2); entityManager.clear(); final int id3 = reservationService.createReservationAdmin(ReservationModelUtils.createReservationModel()); reservationService.updateReservationState(ReservationState.PAID.name(), id3); entityManager.clear(); final int id4 = reservationService.createReservationAdmin(ReservationModelUtils.createReservationModel()); reservationService.createReservationAdmin(ReservationModelUtils.createReservationModel()); // final List<Reservation> reservations = reservationRepository.findAll(); assertNotNull(reservations); assertFalse(reservations.isEmpty()); assertEquals(5, reservations.size()); }
@Override public void syncronizePhotos() throws QueryModelException { List<Long> listPerTarjetas = new ArrayList<Long>(); // Se obtienen las fotos de los usuarios que tienen tarjetas desde la base de datos try { TypedQuery<Long> cardsQuery = entityManagerSyncronize.createQuery( "select distinct x.perId from ScuVTarjeta x", Long.class); listPerTarjetas = cardsQuery.getResultList(); } catch (Exception ex) { logger.error("No se ha podido consultar la base de datos.", ex); entityManagerSyncronize.clear(); throw new QueryModelException(ex); } for (Long id : listPerTarjetas) { try { if (id == 164200) { selectPerson(id); } else { selectPerson(id); } } catch (QueryModelException qmEx) { logger.info("No se ha podido obtener la Foto del usuario de la base de datos."); } } entityManagerSyncronize.clear(); }
@Test(expected = RuntimeException.class) // @Ignore("mails") public void testMoreHutsPaid() { final int id1 = reservationService.createReservationAdmin(ReservationModelUtils.createReservationModel()); reservationService.updateReservationState(ReservationState.PAID.name(), id1); entityManager.clear(); final int id2 = reservationService.createReservationAdmin(ReservationModelUtils.createReservationModel()); reservationService.updateReservationState(ReservationState.PAID.name(), id2); entityManager.clear(); final int id3 = reservationService.createReservationAdmin(ReservationModelUtils.createReservationModel()); reservationService.updateReservationState(ReservationState.PAID.name(), id3); entityManager.clear(); final int id4 = reservationService.createReservationAdmin(ReservationModelUtils.createReservationModel()); reservationService.updateReservationState(ReservationState.PAID.name(), id4); entityManager.clear(); reservationService.createReservationAdmin(ReservationModelUtils.createReservationModel()); }
@Test(expectedExceptions = OptimisticLockException.class) public void testOptimisticLockException() { ComponentSpec cs = createComponentSpec( Long.toString(1), "chris", "cs", "type1", "chris", Collections.<Tag>emptyList(), Collections.<String, String>emptyMap()); em.getTransaction().begin(); em.persist(cs); em.getTransaction().commit(); em.clear(); Assert.assertFalse(em.contains(cs)); em.getTransaction().begin(); ComponentSpec orig = em.find(ComponentSpec.class, Long.toString(1)); orig.setComponentName("revisedName"); em.getTransaction().commit(); em.clear(); ComponentSpec current = em.find(ComponentSpec.class, Long.toString(1)); Assert.assertEquals(current.getObjVersion(), 1); Assert.assertEquals(cs.getObjVersion(), 0); em.getTransaction().begin(); em.merge(cs); em.getTransaction() .commit(); // optimistic lock exception should be thrown as there has been an intervening // commit }
public void testNonInsertableAndUpdatable121Mappings() { EntityManager em = createEntityManager(); try { beginTransaction(em); Order order = new Order(); order.setQuantity(10); Item item = new Item(); item.setName("Party Balloons"); order.setItem(item); Item itemPair = new Item(); itemPair.setName("Ribbons"); order.setItemPair(itemPair); em.persist(order); em.persist(item); em.persist(itemPair); commitTransaction(em); em.clear(); clearCache(); // Now try to read it back and update. beginTransaction(em); order = em.find(Order.class, order.getOrderId()); assertTrue("The item pair was inserted", order.getItemPair() == null); order.setItemPair(em.merge(itemPair)); Item newItem = new Item(); newItem.setName("Party Boots"); order.setItem(newItem); em.persist(newItem); commitTransaction(em); em.clear(); clearCache(); order = em.find(Order.class, order.getOrderId()); assertTrue("The item pair was not updated.", order.getItemPair() != null); assertTrue("Orginal item was replaced", order.getItem().getItemId().equals(item.getItemId())); assertFalse( "New item replaced original item", order.getItem().getItemId().equals(newItem.getItemId())); } catch (IllegalStateException e) { if (isTransactionActive(em)) { rollbackTransaction(em); } } finally { closeEntityManager(em); } }
private void selectPerson(long id) throws QueryModelException { ICacheEntry cacheEntry = null; PerFoto perFotos = null; try { TypedQuery<PerFoto> photosQuery = entityManagerSyncronize.createQuery( "select x from PerFotos x where x.perId = '" + id + "'", PerFoto.class); perFotos = photosQuery.getSingleResult(); } catch (Exception ex) { entityManagerSyncronize.clear(); throw new QueryModelException(ex); } byte[] cacheEntryBytes = null; Date cacheEntryTimestamp = null; try { cacheEntry = this.diskCache.getEntry(perFotos.getPerId()); } catch (DiskCacheException dcEx) { logger.error("No se ha podido obtener la entrada para el perId indicado", dcEx); } if (cacheEntry != null) { try { cacheEntryBytes = cacheEntry.getBytes(); cacheEntryTimestamp = cacheEntry.getTimestamp(); if (cacheEntryBytes == null || cacheEntryTimestamp == null || cacheEntryTimestamp.compareTo(perFotos.getFecha()) < 0) { try { diskCache.addEntry(perFotos.getPerId(), perFotos.getFecha(), perFotos.getBinario()); } catch (DiskCacheException dcEx) { logger.error("No se ha podido persistir la entrada en disco", dcEx); } } } catch (DiskCacheException dcEx) { logger.error("No se han podido obtener los parametros de la entrada", dcEx); } } else { try { diskCache.addEntry(perFotos.getPerId(), perFotos.getFecha(), perFotos.getBinario()); } catch (DiskCacheException dcEx) { logger.error("No se ha podido persistir la entrada en disco", dcEx); } } entityManagerSyncronize.clear(); }
@Override public void clear() { EntityManager em = emf.createEntityManager(); EntityTransaction txn = em.getTransaction(); try { // the clear operation often deadlocks - let's try several times for (int i = 0; ; ++i) { txn.begin(); try { log.trace("Clearing JPA Store"); String entityTable = em.getMetamodel().entity(configuration.entityClass()).getName(); @SuppressWarnings("unchecked") List<Object> items = em.createQuery("FROM " + entityTable).getResultList(); for (Object o : items) em.remove(o); if (configuration.storeMetadata()) { String metadataTable = em.getMetamodel().entity(MetadataEntity.class).getName(); Query clearMetadata = em.createQuery("DELETE FROM " + metadataTable); clearMetadata.executeUpdate(); } txn.commit(); em.clear(); break; } catch (Exception e) { log.trace("Failed to clear store", e); if (i >= 10) throw new JpaStoreException("Exception caught in clear()", e); } finally { if (txn != null && txn.isActive()) txn.rollback(); } } } finally { em.close(); } }
@Override public List<VigenciasNormasEmpleados> buscarVigenciasNormasEmpleados(EntityManager em) { em.clear(); CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(VigenciasNormasEmpleados.class)); return em.createQuery(cq).getResultList(); }
public void modifyAttribute( String uniqueIdentifier, Attribute attribute, HashMap<String, String> parameters) throws KLMSItemNotFoundException { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); ManagedObject object = getObjectByUID(uniqueIdentifier, em); ArrayList<Attribute> objectAttributes = object.getAttributes(); for (Attribute attrib : objectAttributes) { if (attrib.getAttributeName().equals(attribute.getAttributeName())) { KLMSAttributeValue[] values = attrib.getValues(); KLMSAttributeValue[] newValues = attribute.getValues(); if (attrib.getAttributeType() == EnumTypeKLMS.Structure) { for (int i = 0; i < values.length; i++) { attrib.setValue(newValues[i].getValueString(), newValues[i].getName()); } } else { attrib.setValue(newValues[0].getValueString(), null); } } } em.getTransaction().commit(); em.clear(); }
private void commonTestFindLockModeIsolations( EntityManager em, LockModeType lockMode, int expectedSupportSQLCount, String expectedSupportSQL, int expectedNonSupportSQLCount, String expectedNonSupportSQL, int expectedVersionUpdateCount, String expectedVersionUpdateSQL) { OpenJPAEntityManager oem = (OpenJPAEntityManager) em.getDelegate(); JDBCFetchConfigurationImpl fConfig = (JDBCFetchConfigurationImpl) ((EntityManagerImpl) oem).getBroker().getFetchConfiguration(); DBDictionary dict = ((JDBCConfiguration) ((OpenJPAEntityManagerSPI) oem).getConfiguration()) .getDBDictionaryInstance(); em.clear(); resetSQL(); int beforeIsolation = fConfig.getIsolation(); em.find(LockEmployee.class, 1, lockMode); if (dict.supportsIsolationForUpdate() && dict instanceof DB2Dictionary) { assertEquals(expectedSupportSQLCount, getSQLCount()); assertAllSQLInOrder(expectedSupportSQL); } else { assertEquals(expectedNonSupportSQLCount, getSQLCount()); assertAllSQLInOrder(expectedNonSupportSQL); } resetSQL(); em.flush(); assertEquals(expectedVersionUpdateCount, getSQLCount()); if (expectedVersionUpdateSQL != null) assertAllSQLInOrder(expectedVersionUpdateSQL); assertEquals(beforeIsolation, fConfig.getIsolation()); }
@Test public void testJPAPolymorphicCollection() throws Exception { em.getTransaction().begin(); Hero h = new Hero(); h.setName("Spartacus"); em.persist(h); SuperHero sh = new SuperHero(); sh.setName("Batman"); sh.setSpecialPower("Technology and samurai techniques"); em.persist(sh); HeroClub hc = new HeroClub(); hc.setName("My hero club"); hc.getMembers().add(h); hc.getMembers().add(sh); em.persist(hc); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); HeroClub lhc = em.find(HeroClub.class, hc.getName()); assertThat(lhc).isNotNull(); Hero lh = lhc.getMembers().get(0); assertThat(lh).isNotNull(); assertThat(lh).isInstanceOf(Hero.class); Hero lsh = lhc.getMembers().get(1); assertThat(lsh).isNotNull(); assertThat(lsh).isInstanceOf(SuperHero.class); lhc.getMembers().clear(); em.remove(lh); em.remove(lsh); em.remove(lhc); em.getTransaction().commit(); }
public static void main(String[] args) { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myunit"); EntityManager manager = entityManagerFactory.createEntityManager(); Teacher teacher1 = new Teacher("Bloch3", 5); for (int i = 0; i < 1000; i++) { teacher1.getCourses().add(new Course(String.valueOf(i), "desc", teacher1)); } manager.getTransaction().begin(); manager.persist(teacher1); manager.getTransaction().commit(); manager.clear(); Teacher teacher = manager .createQuery("SELECT t FROM Teacher t WHERE t.name = :tName", Teacher.class) .setParameter("tName", "Bloch") .getSingleResult(); System.out.println(teacher); int level = teacher.getLevel(); int size = teacher.getCourses().size(); }
public boolean estudianteCumplePreRequisitos(Integer id, Integer prerequisitoCursoId) throws NoPrerrequisitosException { EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); boolean ret = false; try { tx = em.getTransaction(); tx.begin(); tx.commit(); ret = service.estudianteCumplePreRequisitos(id, prerequisitoCursoId, em); if (ret == false) throw new NoPrerrequisitosException("El estudiante no cumple con los prerequisitos"); } catch (Exception e) { if (em != null && tx != null) { tx.rollback(); } throw new NoPrerrequisitosException("El estudiante no cumple con los prerequisitos"); } finally { if (em != null) { em.clear(); em.close(); } return ret; } }
public void testPersistAttachment() { Attachment attach1 = new Attachment(); attach1.setId(2); attach1.setDescription("some attachment description"); attach1.setPath("/home/user"); manager.getTransaction().begin(); manager.persist(attach1); manager.getTransaction().commit(); manager.getTransaction().begin(); manager.clear(); manager.getTransaction().commit(); manager.getTransaction().begin(); Attachment att = manager.find(Attachment.class, 2); assertEquals("/home/user", att.getPath()); manager.getTransaction().commit(); StringWriter writer = new StringWriter(); try { traceDatabase(writer); System.out.println(writer); } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void testCreateAndFindMessage() { Message msg = new Message(); msg.setText("Hallo JPA"); msg.setDate(new Date()); em.getTransaction().begin(); em.persist(msg); msg.setSubject("My new subject"); em.getTransaction().commit(); em.clear(); Message found = em.find(Message.class, msg.getId()); assertNotNull("Should find message object.", found); em.getTransaction().begin(); found.setSubject("Very new subject"); em.getTransaction().commit(); em.close(); em = emf.createEntityManager(); found.setText("Changed in detached mode"); em.getTransaction().begin(); Message merged = em.merge(found); merged.setSubject("Merged"); em.getTransaction().commit(); // em.refresh(found); assertNotNull("Message should be found.", found); }
@Test public void testJTAStandalone() throws Exception { final EntityManagerFactory emf = Persistence.createEntityManagerFactory( "jpajtastandalone", TestHelper.getEnvironmentProperties()); TransactionManager transactionManager = extractJBossTransactionManager(emf); transactionManager.begin(); final EntityManager em = emf.createEntityManager(); Poem poem = new Poem(); poem.setName("L'albatros"); em.persist(poem); transactionManager.commit(); em.clear(); transactionManager.begin(); poem = em.find(Poem.class, poem.getId()); assertThat(poem).isNotNull(); assertThat(poem.getName()).isEqualTo("L'albatros"); em.remove(poem); transactionManager.commit(); em.close(); dropSchemaAndDatabase(emf); emf.close(); }
private void withBatch() { int entityCount = 100; // tag::batch-session-batch-insert-example[] EntityManager entityManager = null; EntityTransaction txn = null; try { entityManager = entityManagerFactory().createEntityManager(); txn = entityManager.getTransaction(); txn.begin(); int batchSize = 25; for (int i = 0; i < entityCount; ++i) { Person Person = new Person(String.format("Person %d", i)); entityManager.persist(Person); if (i % batchSize == 0) { // flush a batch of inserts and release memory entityManager.flush(); entityManager.clear(); } } txn.commit(); } catch (RuntimeException e) { if (txn != null && txn.isActive()) txn.rollback(); throw e; } finally { if (entityManager != null) { entityManager.close(); } } // end::batch-session-batch-insert-example[] }
public void verifyUserPermission(UserPermissionEntry requestUserPermissionEntry) throws KLMSPermissionDeniedException { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); String query = "select k from UserPermissionEntry k where k.uid = '" + requestUserPermissionEntry.getUniqueIdentifier() + "'"; TypedQuery<UserPermissionEntry> tq = em.createQuery(query, UserPermissionEntry.class); UserPermissionEntry userPermissionEntry = tq.getSingleResult(); if (userPermissionEntry.hasCredential() && !requestUserPermissionEntry.hasCredential()) { throw new KLMSPermissionDeniedException("Request Credential is missing"); } if (userPermissionEntry.hasCredential() && requestUserPermissionEntry.hasCredential()) { if (!userPermissionEntry.equals(requestUserPermissionEntry)) { throw new KLMSPermissionDeniedException( "Request Credential does not match the Credential of the requested Object"); } } em.getTransaction().commit(); em.clear(); }
public void testEnumInEmbeddedId() { EntityManager em = emf.createEntityManager(); Beneficiary b = new Beneficiary(); b.setId("b8"); List<BeneContact> contacts = new ArrayList<BeneContact>(); BeneContact c = new BeneContact(); c.setEmail("email8"); BeneContactId id = new BeneContactId(); id.setContactType(BeneContactId.ContactType.HOME); c.setBeneficiary(b); c.setId(id); em.persist(c); contacts.add(c); b.setContacts(contacts); em.persist(b); em.getTransaction().begin(); em.flush(); em.getTransaction().commit(); em.clear(); BeneContactId id1 = c.getId(); BeneContact c1 = em.find(BeneContact.class, id1); assertEquals("email8", c1.getEmail()); em.close(); }
public Hashtable<String, String> getNumberOfObjects() { Hashtable<String, String> objects = new Hashtable<>(); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Query q = em.createNativeQuery("SELECT count(ID) AS Anzahl FROM MANAGEDOBJECT"); objects.put("Managed Objects", q.getSingleResult().toString()); Query q2 = em.createNativeQuery("SELECT count(ID) AS Anzahl FROM SYMMETRICKEY"); objects.put("Symmetric Keys", q2.getSingleResult().toString()); Query q3 = em.createNativeQuery("SELECT count(ID) AS Anzahl FROM TEMPLATE"); objects.put("Templates", q3.getSingleResult().toString()); Query q4 = em.createNativeQuery("SELECT count(ID) AS Anzahl FROM PRIVATEKEY"); objects.put("Private Keys", q4.getSingleResult().toString()); Query q5 = em.createNativeQuery("SELECT count(ID) AS Anzahl FROM PUBLICKEY"); objects.put("Public Keys", q5.getSingleResult().toString()); Query q6 = em.createNativeQuery("SELECT count(ID) AS Anzahl FROM SECRETDATA"); objects.put("Secret Data", q6.getSingleResult().toString()); // Query q7 = em.createNativeQuery("SELECT count(ID) AS Anzahl FROM CERTIFICATE"); // objects.put("Certificates", q7.getSingleResult().toString()); // Query q8 = em.createNativeQuery("SELECT count(ID) AS Anzahl FROM OPAQUEOBJECT"); // objects.put("Opaque Objects", q8.getSingleResult().toString()); em.getTransaction().commit(); em.clear(); return objects; }
public void add(ManagedObject o) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(o); em.getTransaction().commit(); em.clear(); }
public Committer createCommit(Committer c) { em.persist(c); tx.commit(); em.clear(); return c; }
@BeforeClass public static void setUp() throws Exception { entityManager = provider.em(); transaction = provider.tx(); transaction.begin(); entityManager.flush(); entityManager.clear(); }
@Override public void create(Location location) { try { entityManager.persist(location); } catch (RuntimeException ex) { entityManager.clear(); throw ex; } }
public void persistUserPermissionEntry(UserPermissionEntry userPermissionEntry) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(userPermissionEntry); em.getTransaction().commit(); em.clear(); }
public void addManagedObjects(ArrayList<ManagedObject> moList) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); for (ManagedObject mo : moList) { em.persist(mo); } em.getTransaction().commit(); em.clear(); }
public void recover(String uniqueIdentifier) throws KLMSItemNotFoundException { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); getObjectByUID(uniqueIdentifier, em).recover(); em.getTransaction().commit(); em.clear(); }