Exemplo n.º 1
0
  /**
   * This test will demonstrate using a compound foreign key in a many-to-one, uni-directional
   * relationship.
   */
  @Test
  public void testManyToOneUniCompoundFK() {
    log.info("*** testManyToOneUniCompoundFK ***");

    House house = new House(new HousePK(1600, "PA Ave"), "White House");
    Occupant occupant = new Occupant("bo", house);
    log.debug("persisting parent");
    em.persist(house);
    log.debug("persisting child");
    em.persist(occupant);
    em.flush();

    log.debug("getting new instances");
    em.clear();
    Occupant occupant2 = em.find(Occupant.class, occupant.getId());
    log.debug("checking child");
    assertEquals("unexpected child data", occupant.getName(), occupant2.getName());
    log.debug("checking parent");
    assertEquals("unexpected parent data", house.getName(), occupant2.getResidence().getName());

    log.debug("add more child entities");
    Occupant occupantB = new Occupant("miss beazily", occupant2.getResidence());
    em.persist(occupantB);
    em.flush();

    log.debug("getting new instances of children");
    em.clear();
    List<Occupant> occupants =
        em.createQuery(
                "select o from Occupant o " + "where o.residence.id=:houseId", Occupant.class)
            .setParameter("houseId", occupant.getResidence().getId())
            .getResultList();
    assertEquals("unexpected number of children", 2, occupants.size());
  }