@Test
  @Priority(10)
  public void initData() {
    // Revision 1
    EntityManager em = getEntityManager();
    em.getTransaction().begin();
    NotAuditedSubclassEntity nas =
        new NotAuditedSubclassEntity("nae", "super str", "not audited str");
    em.persist(nas);
    AuditedAllSubclassEntity ae = new AuditedAllSubclassEntity("ae", "super str", "audited str");
    em.persist(ae);
    id1_1 = ae.getId();
    id2_1 = nas.getId();
    em.getTransaction().commit();

    // Revision 2
    em.getTransaction().begin();
    ae = em.find(AuditedAllSubclassEntity.class, id1_1);
    ae.setStr("ae new");
    ae.setSubAuditedStr("audited str new");
    nas = em.find(NotAuditedSubclassEntity.class, id2_1);
    nas.setStr("nae new");
    nas.setNotAuditedStr("not aud str new");
    em.getTransaction().commit();
  }
  @Test
  public void testCfgXmlPar() throws Exception {
    File testPackage = buildCfgXmlPar();
    addPackageToClasspath(testPackage);

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("cfgxmlpar", new HashMap());
    EntityManager em = emf.createEntityManager();
    Item i = new Item();
    i.setDescr("Blah");
    i.setName("factory");
    Morito m = new Morito();
    m.setPower("SuperStrong");
    em.getTransaction().begin();
    em.persist(i);
    em.persist(m);
    em.getTransaction().commit();

    em.getTransaction().begin();
    i = em.find(Item.class, i.getName());
    em.remove(i);
    em.remove(em.find(Morito.class, m.getId()));
    em.getTransaction().commit();
    em.close();
    emf.close();
  }
示例#3
0
 public static void assignUserToProject(Long projectID, Long userID) {
   EntityManager em = getEM();
   ProjectUser pu = em.find(ProjectUser.class, userID);
   em.getTransaction().begin();
   pu.setContributor(em.find(Project.class, projectID));
   em.getTransaction().commit();
 }
  /**
   * Refresh method test loads an entity with two different entity managers. One updates the entity
   * and another refreshes it. The test checks whether refreshed entity contains changes.
   */
  @Test
  public void entityEquality_refresh_EntityManager() {
    // load an entity
    EntityManager emRefresh = factory.createEntityManager();
    Person person1 = emRefresh.find(Person.class, SIMON_SLASH_ID);

    // load the same entity by different entity manager
    EntityManager emChange = factory.createEntityManager();
    Person person2 = emChange.find(Person.class, SIMON_SLASH_ID);

    // change the first entity - second entity remains the same
    emRefresh.getTransaction().begin();
    person1.setFirstName("refreshDemo");
    assertNotSame("refreshDemo", person2.getFirstName());

    // commit the transaction - second entity still remains the same
    emRefresh.getTransaction().commit();
    assertNotSame("refreshDemo", person2.getFirstName());

    // refresh second entity - it changes
    emChange.refresh(person2);
    assertEquals("refreshDemo", person2.getFirstName());

    emRefresh.close();
    emChange.close();
  }
 /*
  * IllegalArgumentException, if the first argument does not denote an entity type or the second argument is not a valid type
  * for that entity's primary key.
  */
 @Test
 public void testIllegalArguments() {
   final EntityManager em = getEnvironment().getEntityManager();
   try {
     try {
       em.find(String.class, new Integer(17 + 4));
       flop("no IllegalArgumentException thrown");
     } catch (IllegalArgumentException ex) {
       verify(true, "");
     }
     try {
       em.find(Employee.class, "illegal key");
       flop("no IllegalArgumentException thrown");
     } catch (IllegalArgumentException ex) {
       verify(true, "");
     }
     try {
       em.find(Employee.class, null);
       flop("no IllegalArgumentException thrown");
     } catch (IllegalArgumentException ex) {
       verify(true, "");
     }
     try {
       em.find(null, "illegal key");
       flop("no IllegalArgumentException thrown");
     } catch (IllegalArgumentException ex) {
       verify(true, "");
     }
   } finally {
     closeEntityManager(em);
   }
 }
  @BeforeClass(dependsOnMethods = "init")
  public void initData() {
    EntityManager em = getEntityManager();

    StrTestEntity str1 = new StrTestEntity("str1");

    SetRefCollEntity coll1 = new SetRefCollEntity(3, "coll1");

    // Revision 1
    em.getTransaction().begin();

    em.persist(str1);

    coll1.setCollection(new HashSet<StrTestEntity>());
    em.persist(coll1);

    em.getTransaction().commit();

    // Revision 2
    em.getTransaction().begin();

    str1 = em.find(StrTestEntity.class, str1.getId());
    coll1 = em.find(SetRefCollEntity.class, coll1.getId());

    coll1.getCollection().add(str1);
    coll1.setData("coll2");

    em.getTransaction().commit();

    //

    str1_id = str1.getId();

    coll1_id = coll1.getId();
  }
示例#7
0
  @Test
  public void testOrderBy() {
    final JPAEnvironment env = getEnvironment();
    final EntityManager em = env.getEntityManager();
    final SortedMap<String, Employee> attendeeMap = new TreeMap<String, Employee>();
    try {
      env.beginTransaction(em);
      final Course course = createAndPersistCourse(em);
      final Long courseId = Long.valueOf(course.getCourseId());
      final Employee employee1 = em.find(Employee.class, EMP_ID_DORIS);
      attendeeMap.put(employee1.getLastName(), employee1);
      final Employee employee2 = em.find(Employee.class, EMP_ID_SABINE);
      attendeeMap.put(employee2.getLastName(), employee2);
      env.commitTransactionAndClear(em);

      env.beginTransaction(em);
      final Course storedCourse = em.find(Course.class, courseId);
      verify(storedCourse != null, "didnt find course again");
      final List<Employee> attendees = storedCourse.getAttendees();
      verify(attendees != null, "course lost attendees");
      final Iterator<Employee> orderedEmployees = attendees.iterator();
      for (final String lastName : attendeeMap.keySet()) {
        Employee nextEmployee = orderedEmployees.next();
        verify(
            nextEmployee.getLastName().equals(lastName),
            "wrong order of employees, expected name: "
                + lastName
                + ", but got name: "
                + nextEmployee.getLastName());
      }
      env.commitTransactionAndClear(em);
    } finally {
      closeEntityManager(em);
    }
  }
 @Transactional
 @RegisterActivity(type = UserActivityType.BILLING_MODEL_RAPPEL_MERGE)
 public Message<BillingModel> mergeRappelDetail(Rappel entity) {
   try {
     // TODO deberiamos tener un constructor de mensajes a partir de errores de validacion en lugar
     // de tomar solo el primer mensaje
     Set<ConstraintViolation<Rappel>> violations = validator.validate(entity);
     if (!violations.isEmpty()) {
       String messageKey = violations.iterator().next().getMessage();
       return new Message<>(Message.CODE_GENERIC_ERROR, i18nService.getMessage(messageKey));
     }
     EntityManager entityManager = entityManagerProvider.get();
     BillingModel model = entityManager.find(BillingModel.class, entity.getModel().getId());
     Rappel current;
     String message;
     if (entity.getId() == null) {
       current = new Rappel();
       current.merge(entity);
       current.setModel(model);
       entityManager.persist(current);
       message = i18nService.getMessage("billingModel.rappel.persist");
     } else {
       current = entityManager.find(Rappel.class, entity.getId());
       current.merge(entity);
       entityManager.merge(current);
       message = i18nService.getMessage("billingModel.rappel.merge");
     }
     auditService.processModified(model);
     return new Message<>(Message.CODE_SUCCESS, message, model);
   } catch (Exception ex) {
     return new Message<>(
         Message.CODE_GENERIC_ERROR, i18nService.getMessage("billingModel.rappel.merge"));
   }
 }
示例#9
0
  @Test
  public void testCascadeAndFetchEntity() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Troop disney = new Troop();
    disney.setName("Disney");
    Soldier mickey = new Soldier();
    mickey.setName("Mickey");
    disney.addSoldier(mickey);
    em.persist(disney);
    em.getTransaction().commit();
    em.close();

    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Soldier soldier = em.find(Soldier.class, mickey.getId());
    assertFalse(Hibernate.isInitialized(soldier.getTroop()));
    em.getTransaction().commit();
    assertFalse(Hibernate.isInitialized(soldier.getTroop()));
    em.close();
    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Troop troop = em.find(Troop.class, disney.getId());
    em.remove(troop);
    // Fail because of HHH-1187
    em.getTransaction().commit();
    em.close();
  }
  @Test
  @Priority(10)
  public void initData() {
    DetachedNamingTestEntity uni1 = new DetachedNamingTestEntity(1, "data1");
    StrTestEntity str1 = new StrTestEntity("str1");

    // Revision 1
    EntityManager em = getEntityManager();
    em.getTransaction().begin();

    uni1.setCollection(new HashSet<StrTestEntity>());
    em.persist(uni1);
    em.persist(str1);

    em.getTransaction().commit();

    // Revision 2
    em.getTransaction().begin();

    uni1 = em.find(DetachedNamingTestEntity.class, uni1.getId());
    str1 = em.find(StrTestEntity.class, str1.getId());
    uni1.getCollection().add(str1);

    em.getTransaction().commit();

    //

    uni1_id = uni1.getId();
    str1_id = str1.getId();
  }
示例#11
0
  @Test
  public void departmentTest() throws Exception {
    Department dpNew = new Department();
    em.getTransaction().begin();
    dpNew.setName("Bob's Department");
    dpNew.setLocation("Baltimore");
    em.persist(dpNew);
    em.getTransaction().commit();
    int newId = dpNew.getId();

    // test earlier persist
    Department dpLoad1 = em.find(Department.class, newId);
    assertEquals(dpLoad1.getId(), newId);
    assertEquals("Insert didn't work", dpLoad1.getName(), "Bob's Department");
    assertEquals("Insert didn't work", dpLoad1.getLocation(), "Baltimore");

    // test update
    em.getTransaction().begin();
    dpLoad1.setName("Phil's Department");
    dpLoad1.setLocation("Philadelphia");
    em.getTransaction().commit();
    Department dpLoad2 = em.find(Department.class, newId);
    assertEquals(dpLoad2.getId(), newId);
    assertEquals("Update didn't work", dpLoad2.getName(), "Phil's Department");
    assertEquals("Update didn't work", dpLoad2.getLocation(), "Philadelphia");

    em.getTransaction().begin();
    em.remove(dpLoad1);
    em.getTransaction().commit();

    Department shouldBeNull = em.find(Department.class, newId);
    assertNull("Delete didn't work", shouldBeNull);
  }
示例#12
0
  public MediaartDto mediaartFindByPrimaryKey(String cNr, TheClientDto theClientDto)
      throws EJBExceptionLP {
    myLogger.logData(cNr);

    if (cNr == null) {
      throw new EJBExceptionLP(EJBExceptionLP.FEHLER, new Exception("cNr == null"));
    }

    MediaartDto mediaartDtoO = null;

    // try {
    Mediaart mediaart = em.find(Mediaart.class, cNr);
    if (mediaart == null) {
      throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY, "");
    }
    mediaartDtoO = assembleMediaartDto(mediaart);

    try {
      Mediaartspr mediaartspr =
          em.find(
              Mediaartspr.class,
              new MediaartsprPK(mediaartDtoO.getCNr(), theClientDto.getLocUiAsString()));
      mediaartDtoO.setMediaartsprDto(assembleMediaartsprDto(mediaartspr));
    } catch (Throwable t) {
      // nothing here.
    }
    // }
    // catch (FinderException ex) {
    // throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY,
    // ex);
    // }

    return mediaartDtoO;
  }
示例#13
0
  public void unrollManagerInEvent(Long managerId, Long eventId)
      throws EntityDoesNotExistsException, ManagerNotEnrolledException {
    try {
      Event event = em.find(Event.class, eventId);
      if (event == null) {
        throw new EntityDoesNotExistsException("There is no event with that id.");
      }

      Manager manager = em.find(Manager.class, managerId);
      if (manager == null) {
        throw new AttendantNotEnrolledException("There is no manager with that id.");
      }

      if (!event.getManagers().contains(manager)) {
        throw new ManagerNotEnrolledException("Manager is not enrolled in that event.");
      }

      event.removeManager(manager);
      manager.removeEvent(event);

    } catch (EntityDoesNotExistsException | ManagerNotEnrolledException e) {
      throw e;
    } catch (Exception e) {
      throw new EJBException(e.getMessage());
    }
  }
示例#14
0
  public void enrollManagerInEvent(Long managerId, Long eventId)
      throws EntityDoesNotExistsException, ManagerEnrolledException {
    System.out.println("Eeeeeeeeevent ID: ");

    try {
      Manager manager = em.find(Manager.class, managerId);
      if (manager == null) {
        throw new EntityDoesNotExistsException("There is no manager with that id.");
      }

      Event event = em.find(Event.class, eventId);
      if (event == null) {
        throw new EntityDoesNotExistsException("There is no event with that id.");
      }

      if (event.getManagers().contains(manager)) {
        throw new ManagerEnrolledException("Manager is already enrolled in that event.");
      }

      event.addManager(manager);
      manager.addEvent(event);

    } catch (EntityDoesNotExistsException | ManagerEnrolledException e) {
      throw e;
    } catch (Exception e) {
      throw new EJBException(e.getMessage());
    }
  }
示例#15
0
  public void addPartToBillOfMaterial(
      String bomPartNumber, int bomRevision, String partNumber, int revision) {
    logger.log(Level.INFO, "BOM part number: {0}", bomPartNumber);
    logger.log(Level.INFO, "BOM revision: {0}", bomRevision);
    logger.log(Level.INFO, "Part number: {0}", partNumber);
    logger.log(Level.INFO, "Part revision: {0}", revision);
    try {
      PartKey bomKey = new PartKey();
      bomKey.setPartNumber(bomPartNumber);
      bomKey.setRevision(bomRevision);

      Part bom = em.find(Part.class, bomKey);
      logger.log(Level.INFO, "BOM Part found: {0}", bom.getPartNumber());

      PartKey partKey = new PartKey();
      partKey.setPartNumber(partNumber);
      partKey.setRevision(revision);

      Part part = em.find(Part.class, partKey);
      logger.log(Level.INFO, "Part found: {0}", part.getPartNumber());
      bom.getParts().add(part);
      part.setBomPart(bom);
    } catch (EJBException e) {
    }
  }
  @BeforeClass(dependsOnMethods = "init")
  public void initData() {
    ed_id1 = new EmbIdNaming(10, 20);
    ed_id2 = new EmbIdNaming(11, 21);
    ing_id1 = new EmbIdNaming(12, 22);

    JoinEmbIdNamingRefEdEntity ed1 = new JoinEmbIdNamingRefEdEntity(ed_id1, "data1");
    JoinEmbIdNamingRefEdEntity ed2 = new JoinEmbIdNamingRefEdEntity(ed_id2, "data2");

    JoinEmbIdNamingRefIngEntity ing1 = new JoinEmbIdNamingRefIngEntity(ing_id1, "x", ed1);

    // Revision 1
    EntityManager em = getEntityManager();
    em.getTransaction().begin();

    em.persist(ed1);
    em.persist(ed2);
    em.persist(ing1);

    em.getTransaction().commit();

    // Revision 2
    em.getTransaction().begin();

    ed2 = em.find(JoinEmbIdNamingRefEdEntity.class, ed2.getId());

    ing1 = em.find(JoinEmbIdNamingRefIngEntity.class, ing1.getId());
    ing1.setData("y");
    ing1.setReference(ed2);

    em.getTransaction().commit();
  }
 public void testEL254937() {
   EntityManager em = createEntityManager(m_persistenceUnit);
   beginTransaction(em);
   LargeProject lp1 = new LargeProject();
   lp1.setName("one");
   em.persist(lp1);
   commitTransaction(em);
   em = createEntityManager(m_persistenceUnit);
   beginTransaction(em);
   em.remove(em.find(LargeProject.class, lp1.getId()));
   em.flush();
   JpaEntityManager eclipselinkEm = (JpaEntityManager) em.getDelegate();
   RepeatableWriteUnitOfWork uow = (RepeatableWriteUnitOfWork) eclipselinkEm.getActiveSession();
   // duplicate the beforeCompletion call
   uow.issueSQLbeforeCompletion();
   // commit the transaction
   uow.setShouldTerminateTransaction(true);
   uow.commitTransaction();
   // duplicate the AfterCompletion call.  This should merge, removing the LargeProject from the
   // shared cache
   uow.mergeClonesAfterCompletion();
   em = createEntityManager(m_persistenceUnit);
   LargeProject cachedLargeProject = em.find(LargeProject.class, lp1.getId());
   closeEntityManager(em);
   assertTrue(
       "Entity removed during flush was not removed from the shared cache on commit",
       cachedLargeProject == null);
 }
  // if producto generico admin
  // else user
  @PUT
  @Path("{id}")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response updateProducto(@PathParam(value = "id") Long id, DataProducto dp) {
    Producto p = em.find(Producto.class, id);
    p.setNombre(dp.getNombre());
    p.setDescripcion(dp.getDescripcion());
    p.setGenerico(dp.getIsgenerico());
    Categoria cat = em.find(Categoria.class, dp.getCategoria());
    if (cat == null) {
      DataResponse dr = new DataResponse();
      dr.setMensaje("Categoria " + dp.getCategoria() + " no existe");
      return Response.status(500).entity(dr).build();
    }
    p.setCategoria(cat);

    em.merge(p);

    // mongo thread
    dp.setID(p.getId());
    new MongoController().upsertProduct(dp);

    return Response.status(200).build();
  }
示例#19
0
 @Test
 public void testUpdate() {
   final JPAEnvironment env = getEnvironment();
   final EntityManager em = env.getEntityManager();
   try {
     env.beginTransaction(em);
     final Course course = createAndPersistCourse(em);
     final Long courseId = Long.valueOf(course.getCourseId());
     env.commitTransactionAndClear(em);
     env.beginTransaction(em);
     // the remove of Doris takes place on the managed entity
     em.find(Course.class, courseId).removeAttendee(em.find(Employee.class, EMP_ID_DORIS));
     env.commitTransactionAndClear(em);
     final Course storedCourse = em.find(Course.class, courseId);
     verify(storedCourse != null, "didnt find course again");
     verify(storedCourse.getAttendees() != null, "course lost attendees");
     verify(
         storedCourse.getAttendees().size() == 1,
         "number of attendees in course (expected: 1, got: "
             + storedCourse.getAttendees().size()
             + ").");
     for (final Employee attendee : storedCourse.getAttendees()) {
       verify("Sabine".equals(attendee.getFirstName()), "Wrong attendee: " + attendee);
     }
   } finally {
     closeEntityManager(em);
   }
 }
示例#20
0
  @NotNull(message = "{kundeSERV.notFound.id}")
  public AbstractKunde findKundeById(Long id, FetchType fetch) {
    if (id == null) {
      return null;
    }

    AbstractKunde kunde;
    EntityGraph<?> entityGraph;
    Map<String, Object> props;
    switch (fetch) {
      case NUR_KUNDE:
        kunde = em.find(AbstractKunde.class, id);
        break;

      case MIT_BESTELLUNGEN:
        entityGraph = em.getEntityGraph(AbstractKunde.GRAPH_BESTELLUNGEN);
        props = ImmutableMap.of(LOADGRAPH, (Object) entityGraph);
        kunde = em.find(AbstractKunde.class, id, props);
        break;

      default:
        kunde = em.find(AbstractKunde.class, id);
        break;
    }

    return kunde;
  }
  @Test
  @Priority(10)
  public void initData() {
    EntityManager em = getOrCreateEntityManager();
    try {
      // Revision 1
      em.getTransaction().begin();
      NameInfo ni = new NameInfo("John", "Doe");
      Person person1 = new Person("JDOE", ni);
      em.persist(person1);
      em.getTransaction().commit();

      // Revision 2
      em.getTransaction().begin();
      person1 = em.find(Person.class, person1.getId());
      person1.getNameInfo().setFirstName("Jane");
      em.merge(person1);
      em.getTransaction().commit();

      // Revision 3
      em.getTransaction().begin();
      person1 = em.find(Person.class, person1.getId());
      person1.setName("JDOE2");
      em.merge(person1);
      em.getTransaction().commit();

      personId = person1.getId();
    } finally {
      em.close();
    }
  }
  public static void main(String[] args) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("TA-FINAL-PU");
    EntityManager em = emf.createEntityManager();

    Filme f = new Filme();
    Filme ff = em.find(Filme.class, 42);

    Cinema c = new Cinema();
    Cinema cc = em.find(Cinema.class, 2);

    Sessao obj = new Sessao();
    obj.setData(Calendar.getInstance());
    obj.setHora("16h as 18h");
    obj.setValorInteiro(28.00);
    obj.setValorMeia(14.00);
    obj.setNumSala("25b");

    obj.setCinema(cc);
    obj.setFilme(ff);

    em.getTransaction().begin();
    em.persist(obj);
    em.getTransaction().commit();
    em.close();
    emf.close();
  }
  /**
   * The merge method should copy all entity data into entity manager. Entity itself in not attached
   * nor persisted.
   */
  @Test
  public void entityEquality_mergeInto_EntityManager() {
    // load and detach entity
    EntityManager em1 = factory.createEntityManager();
    Person person1 = em1.find(Person.class, SIMON_SLASH_ID);
    em1.close();

    // change its property
    person1.setFirstName("New Name");

    // merge it into some entity manager
    EntityManager em2 = factory.createEntityManager();
    em2.merge(person1);

    // this change will be ignored
    person1.setFirstName("Ignored Change");

    Person person2 = em2.find(Person.class, SIMON_SLASH_ID);
    em2.close();

    // entity itself was not attached
    assertNotSame(person1, person2);
    // however, its changed data was
    assertEquals("New Name", person2.getFirstName());

    // changed data are NOT available in different entity manager
    EntityManager em3 = factory.createEntityManager();
    Person person3 = em3.find(Person.class, SIMON_SLASH_ID);
    em3.close();

    assertNotSame("New Name", person3.getFirstName());
  }
  public void testDetach() {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();

    Tooth tooth = new Tooth();
    Mouth mouth = new Mouth();
    em.persist(mouth);
    em.persist(tooth);
    tooth.mouth = mouth;
    mouth.teeth = new ArrayList<Tooth>();
    mouth.teeth.add(tooth);
    em.getTransaction().commit();
    em.close();

    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    mouth = em.find(Mouth.class, mouth.id);
    assertNotNull(mouth);
    assertEquals(1, mouth.teeth.size());
    tooth = mouth.teeth.iterator().next();
    em.detach(mouth);
    assertFalse(em.contains(tooth));
    em.getTransaction().commit();
    em.close();

    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    em.remove(em.find(Mouth.class, mouth.id));

    em.getTransaction().commit();
    em.close();
  }
 @Test
 public void testFindRemoved() {
   final JPAEnvironment env = getEnvironment();
   final EntityManager em = env.getEntityManager();
   try {
     env.beginTransaction(em);
     Island island = new Island();
     em.persist(island);
     env.commitTransactionAndClear(em);
     Integer islandId = Integer.valueOf(island.getId());
     env.beginTransaction(em);
     island = em.find(Island.class, islandId);
     em.remove(island);
     verify(
         em.find(Island.class, islandId) == null, "entity in state FOR_DELETE but found by find");
     env.rollbackTransactionAndClear(em);
     env.beginTransaction(em);
     island = em.find(Island.class, islandId);
     em.remove(island);
     em.flush();
     verify(
         em.find(Island.class, islandId) == null,
         "entity in state DELETE_EXECUTED but found by find");
     env.rollbackTransactionAndClear(em);
   } finally {
     closeEntityManager(em);
   }
 }
示例#26
0
 @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
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * com.mydomain.maizsoft.cargaarchivos.IArchivoXMLNotas#guardarArchivoXml()
   */
  @Override
  public String guardarArchivoXml() {

    ConfiguracionesSistema path = entityManager.find(ConfiguracionesSistema.class, 1l);
    ConfiguracionesSistema pathbackup = entityManager.find(ConfiguracionesSistema.class, 20l);
    String pathFinal =
        path.getDetallesPropiedad() + "//" + pathbackup.getDetallesPropiedad() + "//";
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat simple = new SimpleDateFormat("yyyyddMMhhmmss");
    String date = simple.format(calendar.getTime());
    setNombre(date + "_backupNotas.xml");
    setPath(pathFinal);
    File directorio = new File(pathFinal);
    if (!directorio.exists()) {
      directorio.mkdirs();
    }

    try {
      open();
      write();

    } catch (Exception e) {
      FacesMessages mensaje = (FacesMessages) Component.getInstance(FacesMessages.class);
      mensaje.add("Se produjo un error técnico :(");
    }

    FacesMessages mensaje = (FacesMessages) Component.getInstance(FacesMessages.class);
    mensaje.add("Se genero el archivo " + getNombre() + " exitosamente :-)");

    return "";
  }
  @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();
  }
  public void edit(Long altId, Vote vote)
      throws NonExistingEntityException, RollbackFailureException, Exception {
    Alternative alternative = em.find(Alternative.class, altId);
    if (alternative == null) {
      throw new NonExistingEntityException("Alternative with Id = " + altId + " does not exist");
    }
    vote.setAlternative(alternative);

    Vote persistentVote = em.find(Vote.class, vote.getId());
    Alternative alternativeOld = persistentVote.getAlternative();
    Alternative alternativeNew = vote.getAlternative();
    if (alternativeNew != null) {
      alternativeNew = em.getReference(alternativeNew.getClass(), alternativeNew.getId());
      vote.setAlternative(alternativeNew);
    }
    vote = em.merge(vote);
    if (alternativeOld != null && !alternativeOld.equals(alternativeNew)) {
      alternativeOld.getVotes().remove(vote);
      alternativeOld = em.merge(alternativeOld);
    }
    if (alternativeNew != null && !alternativeNew.equals(alternativeOld)) {
      alternativeNew.getVotes().add(vote);
      alternativeNew = em.merge(alternativeNew);
    }
  }
示例#30
0
  @Test
  @Priority(10)
  public void initData() {
    JoinNamingRefEdEntity ed1 = new JoinNamingRefEdEntity("data1");
    JoinNamingRefEdEntity ed2 = new JoinNamingRefEdEntity("data2");

    JoinNamingRefIngEntity ing1 = new JoinNamingRefIngEntity("x", ed1);

    // Revision 1
    EntityManager em = getEntityManager();
    em.getTransaction().begin();

    em.persist(ed1);
    em.persist(ed2);
    em.persist(ing1);

    em.getTransaction().commit();

    // Revision 2
    em.getTransaction().begin();

    ed2 = em.find(JoinNamingRefEdEntity.class, ed2.getId());

    ing1 = em.find(JoinNamingRefIngEntity.class, ing1.getId());
    ing1.setData("y");
    ing1.setReference(ed2);

    em.getTransaction().commit();

    //

    ed_id1 = ed1.getId();
    ed_id2 = ed2.getId();
    ing_id1 = ing1.getId();
  }