@Test
  public void testBasicOps() {
    Session session = openSession();
    session.beginTransaction();
    Country country = new Country("US", "United States of America");
    session.persist(country);
    Person person = new Person("Steve", new Address());
    person.getAddress().setLine1("123 Main");
    person.getAddress().setCity("Anywhere");
    person.getAddress().setCountry(country);
    person.getAddress().setPostalCode("123456789");
    session.persist(person);
    session.getTransaction().commit();
    session.close();

    session = openSession();
    session.beginTransaction();
    session.createQuery("from Person p where p.address.country.iso2 = 'US'").list();
    // same query!
    session.createQuery("from Person p where p.address.country.id = 'US'").list();
    person = (Person) session.load(Person.class, person.getId());
    session.delete(person);
    List countries = session.createQuery("from Country").list();
    assertEquals(1, countries.size());
    session.delete(countries.get(0));

    session.getTransaction().commit();
    session.close();
  }
  protected Dairy createDairy(String dairyNumber, String licenseeName) {
    Session session;
    Transaction transaction;

    Dairy dairy;
    Location location;

    session = getOrCreateSession();
    transaction = session.beginTransaction();

    location = ModelFactory.eINSTANCE.createLocation();
    location.setDescriptiveLocation(null);
    location.setMapLocation(null);
    location.setPostalLocation(null);
    location.setStatutoryLocation(null);
    session.persist(location);

    dairy = DairyFactory.eINSTANCE.createDairy();
    dairy.setRegistrationNumber(dairyNumber);
    dairy.setLegalName(licenseeName);
    // dairy.setCompanyId(getDairyId());

    dairy.setDescription("<description>");
    dairy.setCompanyName("<company common name>");
    dairy.setPhoneNumber("+254 0072 0000 0000");
    dairy.setEstablishedDate(new Date(1, 1, 1975));

    dairy.setLocation(location);
    session.persist(dairy);

    transaction.commit();

    return dairy;
  }
  @Before
  public void setupTestData() {
    Session s = openSession();
    Transaction tx = s.beginTransaction();

    Calendar dob = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH);
    dob.set(1958, 3, 7, 0, 0, 0);
    dob.set(Calendar.MILLISECOND, 0);

    GolfPlayer hergesheimer =
        new GolfPlayer.Builder()
            .firstName("Klaus")
            .lastName("Hergesheimer")
            .active(true)
            .dateOfBirth(dob.getTime())
            .handicap(3.4)
            .driveWidth(285)
            .ranking(311)
            .build();
    s.persist(hergesheimer);

    GolfPlayer kidd = new GolfPlayer.Builder().lastName("Kidd").build();
    s.persist(kidd);

    tx.commit();
    s.close();
  }
 public void testManyToOneGenerics() throws Exception {
   Paper white = new Paper();
   white.setName("WhiteA4");
   PaperType type = new PaperType();
   type.setName("A4");
   SomeGuy me = new SomeGuy();
   white.setType(type);
   white.setOwner(me);
   Price price = new Price();
   price.setAmount(new Double(1));
   price.setCurrency("Euro");
   white.setValue(price);
   Session s = openSession();
   Transaction tx = s.beginTransaction();
   s.persist(type);
   s.persist(price);
   s.persist(me);
   s.persist(white);
   tx.commit();
   // s.close();
   s = openSession();
   tx = s.beginTransaction();
   white = (Paper) s.get(Paper.class, white.getId());
   s.delete(white.getType());
   s.delete(white.getOwner());
   s.delete(white.getValue());
   s.delete(white);
   tx.commit();
   // s.close();
 }
Example #5
0
  private void createData() {
    Session s = openSession();
    s.getTransaction().begin();
    Calendar cal = Calendar.getInstance();
    cal.set(2006, 10, 11);
    Driver driver = new Driver();
    driver.setDelivery(cal.getTime());
    driver.setId(1);
    driver.setName("Emmanuel");
    driver.setScore(5);
    driver.setTeacher("andre");
    s.persist(driver);

    cal.set(2007, 10, 11);
    driver = new Driver();
    driver.setDelivery(cal.getTime());
    driver.setId(2);
    driver.setName("Gavin");
    driver.setScore(3);
    driver.setTeacher("aaron");
    s.persist(driver);

    cal.set(2004, 10, 11);
    driver = new Driver();
    driver.setDelivery(cal.getTime());
    driver.setId(3);
    driver.setName("Liz");
    driver.setScore(5);
    driver.setTeacher("max");
    s.persist(driver);
    s.getTransaction().commit();
    s.close();
  }
  public void testSQLQueryInterface() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Organization ifa = new Organization("IFA");
    Organization jboss = new Organization("JBoss");
    Person gavin = new Person("Gavin");
    Employment emp = new Employment(gavin, jboss, "AU");

    s.persist(ifa);
    s.persist(jboss);
    s.persist(gavin);
    s.persist(emp);

    List l =
        s.createSQLQuery(getOrgEmpRegionSQL())
            .addEntity("org", Organization.class)
            .addJoin("emp", "org.employments")
            .addScalar("regionCode", Hibernate.STRING)
            .list();
    assertEquals(2, l.size());

    l =
        s.createSQLQuery(getOrgEmpPersonSQL())
            .addEntity("org", Organization.class)
            .addJoin("emp", "org.employments")
            .addJoin("pers", "emp.employee")
            .list();
    assertEquals(l.size(), 1);

    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();

    l =
        s.createSQLQuery(
                "select {org.*}, {emp.*} "
                    + "from ORGANIZATION org "
                    + "     left outer join EMPLOYMENT emp on org.ORGID = emp.EMPLOYER, ORGANIZATION org2")
            .addEntity("org", Organization.class)
            .addJoin("emp", "org.employments")
            .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE)
            .list();
    assertEquals(l.size(), 2);

    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();

    s.delete(emp);
    s.delete(gavin);
    s.delete(ifa);
    s.delete(jboss);

    t.commit();
    s.close();
  }
  @Test
  public void stateEntityImplSave() {

    session.createQuery("delete from StatefulEntityImpl").executeUpdate();
    session.flush();

    StatefulEntityImpl stateEntity = new StatefulEntityImpl("abc");
    session.persist(stateEntity);
    session.flush();

    StatefulEntityImpl stateEntity2 = new StatefulEntityImpl("가나다");
    session.persist(stateEntity2);
    session.flush();

    if (log.isDebugEnabled()) log.debug("엔티티를 저장했습니다. entity=" + stateEntity);

    session.clear();

    @SuppressWarnings("unchecked")
    final List<StatefulEntityImpl> loaded =
        (List<StatefulEntityImpl>)
            session.createQuery("from " + StatefulEntityImpl.class.getName()).list();

    assertEquals(2, loaded.size());

    StatefulEntityImpl entity = loaded.get(0);
    assertNotNull(entity);
    assertEquals("abc", entity.getName());

    entity.setName("modified");
    session.saveOrUpdate(entity);
    session.flush();

    log.debug("엔티티를 로드했습니다. entity=" + entity);
  }
 public void testOneToOneExplicitJoinColumn() throws Exception {
   assertTrue(SchemaUtil.isColumnPresent("MedicalHistory", "FK1", getCfg()));
   assertTrue(SchemaUtil.isColumnPresent("MedicalHistory", "FK2", getCfg()));
   assertTrue(!SchemaUtil.isColumnPresent("MedicalHistory", "firstname", getCfg()));
   Person e = new Person();
   e.id = new PersonId();
   e.id.firstName = "Emmanuel";
   e.id.lastName = "Bernard";
   Session s = openSession();
   s.getTransaction().begin();
   s.persist(e);
   MedicalHistory d = new MedicalHistory();
   d.patient = e;
   s.persist(d);
   s.flush();
   s.clear();
   PersonId pId = new PersonId();
   pId.firstName = e.id.firstName;
   pId.lastName = e.id.lastName;
   d = (MedicalHistory) s.get(MedicalHistory.class, pId);
   assertEquals(pId.firstName, d.patient.id.firstName);
   s.delete(d);
   s.delete(d.patient);
   s.getTransaction().commit();
   s.close();
 }
  public void testResultSetMappingDefinition() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Organization ifa = new Organization("IFA");
    Organization jboss = new Organization("JBoss");
    Person gavin = new Person("Gavin");
    Employment emp = new Employment(gavin, jboss, "AU");

    s.persist(ifa);
    s.persist(jboss);
    s.persist(gavin);
    s.persist(emp);

    List l =
        s.createSQLQuery(getOrgEmpRegionSQL()).setResultSetMapping("org-emp-regionCode").list();
    assertEquals(l.size(), 2);

    l = s.createSQLQuery(getOrgEmpPersonSQL()).setResultSetMapping("org-emp-person").list();
    assertEquals(l.size(), 1);

    s.delete(emp);
    s.delete(gavin);
    s.delete(ifa);
    s.delete(jboss);

    t.commit();
    s.close();
  }
Example #10
0
  public static void main(String[] args) {
    getSessionFactory();

    Session session = factory.openSession();

    Transaction t = session.beginTransaction();

    Employee e1 = new Employee();
    e1.setName("Kavya");

    Regular_Employee e2 = new Regular_Employee();
    e2.setName("Nala");
    e2.setSalary(50000);
    e2.setBonus(5);

    Contract_Employee e3 = new Contract_Employee();
    e3.setName("Rajan");
    e3.setPay_per_hour(1000);
    e3.setContract_duration("15 hours");

    session.persist(e1);
    session.persist(e2);
    session.persist(e3);

    t.commit();
    session.close();
    System.out.println("success");
  }
Example #11
0
  @Test
  public void testOrderedListAndCompositeId() throws Exception {
    Session session = openSession();
    Transaction transaction = session.beginTransaction();
    Race race = new Race();
    race.setRaceId(new Race.RaceId(23, 75));
    Runner runner = new Runner();
    runner.setAge(37);
    runner.setRunnerId(new Runner.RunnerId("Emmanuel", "Bernard"));
    Runner runner2 = new Runner();
    runner2.setAge(105);
    runner2.setRunnerId(new Runner.RunnerId("Pere", "Noel"));
    race.getRunnersByArrival().add(runner);
    race.getRunnersByArrival().add(runner2);
    session.persist(race);
    session.persist(runner);
    session.persist(runner2);
    transaction.commit();

    session.clear();

    transaction = session.beginTransaction();
    race = (Race) session.get(Race.class, race.getRaceId());
    assertThat(race.getRunnersByArrival()).hasSize(2);
    assertThat(race.getRunnersByArrival().get(0).getRunnerId().getFirstname())
        .isEqualTo("Emmanuel");
    session.delete(race.getRunnersByArrival().get(0));
    session.delete(race.getRunnersByArrival().get(1));
    session.delete(race);
    transaction.commit();

    session.close();
    checkCleanCache();
  }
  public void testGetLoad() {
    clearCounts();

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    Employer emp = new Employer();
    s.persist(emp);
    Node node = new Node("foo");
    Node parent = new Node("bar");
    parent.addChild(node);
    s.persist(parent);
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.get(Employer.class, emp.getId());
    assertTrue(Hibernate.isInitialized(emp));
    assertFalse(Hibernate.isInitialized(emp.getEmployees()));
    node = (Node) s.get(Node.class, node.getName());
    assertTrue(Hibernate.isInitialized(node));
    assertFalse(Hibernate.isInitialized(node.getChildren()));
    assertFalse(Hibernate.isInitialized(node.getParent()));
    assertNull(s.get(Node.class, "xyz"));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.load(Employer.class, emp.getId());
    emp.getId();
    assertFalse(Hibernate.isInitialized(emp));
    node = (Node) s.load(Node.class, node.getName());
    assertEquals(node.getName(), "foo");
    assertFalse(Hibernate.isInitialized(node));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.get("org.hibernate.ejb.test.ops.Employer", emp.getId());
    assertTrue(Hibernate.isInitialized(emp));
    node = (Node) s.get("org.hibernate.ejb.test.ops.Node", node.getName());
    assertTrue(Hibernate.isInitialized(node));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.load("org.hibernate.ejb.test.ops.Employer", emp.getId());
    emp.getId();
    assertFalse(Hibernate.isInitialized(emp));
    node = (Node) s.load("org.hibernate.ejb.test.ops.Node", node.getName());
    assertEquals(node.getName(), "foo");
    assertFalse(Hibernate.isInitialized(node));
    tx.commit();
    s.close();

    assertFetchCount(0);
  }
  public void testAddJoinForManyToMany() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Person gavin = new Person("Gavin");
    Person max = new Person("Max");
    Person pete = new Person("Pete");

    Group hibernate = new Group("Hibernate");
    Group seam = new Group("Seam");

    s.persist(gavin);
    s.persist(max);
    s.persist(pete);
    s.persist(seam);
    s.persist(hibernate);

    hibernate.getPersons().add(gavin);
    hibernate.getPersons().add(max);
    seam.getPersons().add(gavin);
    seam.getPersons().add(pete);

    s.flush();
    s.clear();

    // todo : see http://opensource.atlassian.com/projects/hibernate/browse/HHH-3908
    //		String sqlStr = "SELECT {groupp.*} , {gp.*} " +
    //				"FROM GROUPP groupp, GROUP_PERSON gp, PERSON person WHERE groupp.ID = gp.GROUP_ID and
    // person.PERID = gp.PERSON_ID";
    //
    //		List l = s.createSQLQuery( sqlStr )
    //				.addEntity("groupp", Group.class)
    //				.addJoin("gp","groupp.persons")
    //				.list();
    List l = s.getNamedQuery("manyToManyFetch").list();
    // assertEquals( 2, l.size() );

    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();

    seam.getPersons().remove(gavin);
    seam.getPersons().remove(pete);

    hibernate.getPersons().remove(gavin);
    hibernate.getPersons().remove(max);

    s.delete(seam);
    s.delete(hibernate);
    s.delete(gavin);
    s.delete(max);
    s.delete(pete);

    t.commit();
    s.close();
  }
Example #14
0
  @Test
  public void testBackRef() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Parent p = new Parent("Marc");
    Parent p2 = new Parent("Nathalie");
    Child c = new Child("Elvira");
    Child c2 = new Child("Blase");
    p.getChildren().add(c);
    p.getChildren().add(c2);
    s.persist(p);
    s.persist(p2);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    c = (Child) s.get(Child.class, "Elvira");
    c.setAge(2);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    p = (Parent) s.get(Parent.class, "Marc");
    c = (Child) s.get(Child.class, "Elvira");
    c.setAge(18);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    p = (Parent) s.get(Parent.class, "Marc");
    p2 = (Parent) s.get(Parent.class, "Nathalie");
    c = (Child) s.get(Child.class, "Elvira");
    assertEquals(p.getChildren().indexOf(c), 0);
    p.getChildren().remove(c);
    p2.getChildren().add(c);
    t.commit();

    s.close();
    s = openSession();
    t = s.beginTransaction();
    Parent p3 = new Parent("Marion");
    p3.getChildren().add(new Child("Gavin"));
    s.merge(p3);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    s.createQuery("delete from Child").executeUpdate();
    s.createQuery("delete from Parent").executeUpdate();
    t.commit();
    s.close();
  }
Example #15
0
  public void testMapAndElementCollection() throws Exception {
    Session session = openSession();
    Transaction tx = session.beginTransaction();
    Address home = new Address();
    home.setCity("Paris");
    Address work = new Address();
    work.setCity("San Francisco");
    User user = new User();
    user.getAddresses().put("home", home);
    user.getAddresses().put("work", work);
    user.getNicknames().add("idrA");
    user.getNicknames().add("day[9]");
    session.persist(home);
    session.persist(work);
    session.persist(user);
    User user2 = new User();
    user2.getNicknames().add("idrA");
    user2.getNicknames().add("day[9]");
    session.persist(user2);
    tx.commit();

    session.clear();

    tx = session.beginTransaction();
    user = (User) session.get(User.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");
    tx.commit();

    session.clear();

    tx = session.beginTransaction();
    user = (User) session.get(User.class, user.getId());
    // TODO do null value
    assertThat(user.getAddresses()).as("List should have 2 elements").hasSize(2);
    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]");
    session.delete(user);
    session.delete(session.load(Address.class, home.getId()));
    session.delete(session.load(Address.class, work.getId()));

    user2 = (User) session.get(User.class, user2.getId());
    assertThat(user2.getNicknames()).as("Should have 2 nicks").hasSize(2);
    assertThat(user2.getNicknames()).as("Should contain nick").contains("idrA", "day[9]");
    session.delete(user2);

    tx.commit();

    session.close();

    checkCleanCache();
  }
Example #16
0
  @Test
  public void testCurrentSessionWithScroll() throws Exception {
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s = sessionFactory().getCurrentSession();
    Map item1 = new HashMap();
    item1.put("name", "Item - 1");
    item1.put("description", "The first item");
    s.persist("Item", item1);

    Map item2 = new HashMap();
    item2.put("name", "Item - 2");
    item2.put("description", "The second item");
    s.persist("Item", item2);
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();

    // First, test partially scrolling the result with out closing
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    s = sessionFactory().getCurrentSession();
    ScrollableResults results = s.createQuery("from Item").scroll();
    results.next();
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();

    // Next, test partially scrolling the result with closing
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    s = sessionFactory().getCurrentSession();
    results = s.createQuery("from Item").scroll();
    results.next();
    results.close();
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();

    // Next, scroll the entire result (w/o closing)
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    s = sessionFactory().getCurrentSession();
    results = s.createQuery("from Item").scroll();
    while (results.next()) {
      // do nothing
    }
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();

    // Next, scroll the entire result (closing)
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    s = sessionFactory().getCurrentSession();
    results = s.createQuery("from Item").scroll();
    while (results.next()) {
      // do nothing
    }
    results.close();
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();

    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    s = sessionFactory().getCurrentSession();
    s.createQuery("delete from Item").executeUpdate();
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
  }
 @Before
 public void init() {
   Session session = openSession();
   Transaction transaction = session.beginTransaction();
   session.persist(portia);
   session.persist(athanasia);
   session.persist(imperatrix);
   transaction.commit();
   session.clear();
   session.close();
 }
 private void createDoeFamily() {
   Session s = openSession();
   Transaction tx = s.beginTransaction();
   Detective detective = new Detective();
   detective.setName("John Doe");
   s.persist(detective);
   Suspect suspect = new Suspect();
   suspect.setName("Jane Doe");
   s.persist(suspect);
   tx.commit();
   s.close();
 }
  @Test
  @Category(SkipOnElasticsearch.class) // Dynamic boosting is not supported on Elasticsearch
  public void testDynamicBoosts() throws Exception {

    Session session = openSession();
    session.beginTransaction();

    DynamicBoostedDescLibrary lib1 = new DynamicBoostedDescLibrary();
    lib1.setName("one");
    session.persist(lib1);

    DynamicBoostedDescLibrary lib2 = new DynamicBoostedDescLibrary();
    lib2.setName("two");
    session.persist(lib2);

    session.getTransaction().commit();
    session.close();

    float lib1Score = getScore(new TermQuery(new Term("name", "one")));
    float lib2Score = getScore(new TermQuery(new Term("name", "two")));
    assertEquals("The scores should be equal", lib1Score, lib2Score, 0f);

    // set dynamic score and reindex!
    session = openSession();
    session.beginTransaction();

    session.refresh(lib2);
    lib2.setDynScore(2.0f);

    session.getTransaction().commit();
    session.close();

    lib1Score = getScore(new TermQuery(new Term("name", "one")));
    lib2Score = getScore(new TermQuery(new Term("name", "two")));
    assertTrue("lib2score should be greater than lib1score", lib1Score < lib2Score);

    lib1Score = getScore(new TermQuery(new Term("name", "foobar")));
    assertEquals("lib1score should be 0 since term is not yet indexed.", 0.0f, lib1Score, 0f);

    // index foobar
    session = openSession();
    session.beginTransaction();

    session.refresh(lib1);
    lib1.setName("foobar");

    session.getTransaction().commit();
    session.close();

    lib1Score = getScore(new TermQuery(new Term("name", "foobar")));
    lib2Score = getScore(new TermQuery(new Term("name", "two")));
    assertTrue("lib1score should be greater than lib2score", lib1Score > lib2Score);
  }
  @Test
  public void testCascadeFromDetachedToNonDirtyRepresentations() {
    Item item1 = new Item();
    item1.setName("item1");

    Hoarder hoarder = new Hoarder();
    hoarder.setName("joe");

    Session s = openSession();
    Transaction tx = session.beginTransaction();
    s.persist(item1);
    s.persist(hoarder);
    tx.commit();
    s.close();

    // Get another representation of the same Item from a different session.

    s = openSession();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    s.close();

    // item1_1 and item1_2 are unmodified representations of the same persistent entity.
    assertFalse(item1 == item1_1);
    assertTrue(item1.equals(item1_1));

    // Update hoarder (detached) to references both representations.
    hoarder.getItems().add(item1);
    hoarder.setFavoriteItem(item1_1);

    s = openSession();
    tx = s.beginTransaction();
    hoarder = (Hoarder) s.merge(hoarder);
    assertEquals(1, hoarder.getItems().size());
    assertSame(hoarder.getFavoriteItem(), hoarder.getItems().iterator().next());
    assertEquals(item1.getId(), hoarder.getFavoriteItem().getId());
    assertEquals(item1.getCategory(), hoarder.getFavoriteItem().getCategory());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    hoarder = (Hoarder) s.merge(hoarder);
    assertEquals(1, hoarder.getItems().size());
    assertSame(hoarder.getFavoriteItem(), hoarder.getItems().iterator().next());
    assertEquals(item1.getId(), hoarder.getFavoriteItem().getId());
    assertEquals(item1.getCategory(), hoarder.getFavoriteItem().getCategory());
    tx.commit();
    s.close();

    cleanup();
  }
  @Test
  public void testTopLevelEntityNewerThanNested() {
    Item item = new Item();
    item.setName("item");

    Category category = new Category();
    category.setName("category");

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item);
    s.persist(category);
    tx.commit();
    s.close();

    // Get the Category from a different session.
    s = openSession();
    tx = s.beginTransaction();
    Category category1_2 = (Category) s.get(Category.class, category.getId());
    tx.commit();
    s.close();

    // Get and update the same Category.
    s = openSession();
    tx = s.beginTransaction();
    Category category1_1 = (Category) s.get(Category.class, category.getId());
    category1_1.setName("new name");
    tx.commit();
    s.close();

    assertTrue(category1_2.getVersion() < category1_1.getVersion());

    category1_1.setExampleItem(item);
    item.setCategory(category1_2);

    s = openSession();
    tx = s.beginTransaction();
    try {
      // representation merged at top level is newer than nested representation.
      category1_1 = (Category) s.merge(category1_1);
      fail("should have failed because one representation is an older version.");
    } catch (StaleObjectStateException ex) {
      // expected
    } finally {
      tx.rollback();
      s.close();
    }

    cleanup();
  }
 public void doWork(Session session) throws Exception {
   XorShiftRandom rng = new XorShiftRandom(seeder.nextInt());
   Order order = new Order();
   session.persist(order);
   for (int i = 0; i < 10; i++) {
     int productId = rng.nextInt() & 1023;
     Product product = (Product) session.get(Product.class, productId);
     OrderLine orderLine = new OrderLine();
     orderLine.setOrder(order);
     orderLine.setProduct(product);
     session.persist(orderLine);
     order.getOrderLines().add(orderLine);
   }
 }
 public void testAllParams() throws Exception {
   Session s = openSession();
   Transaction tx = s.beginTransaction();
   Radio radio = new Radio();
   radio.setFrequency("32 MHz");
   s.persist(radio);
   assertEquals(new Integer(1), radio.getId());
   radio = new Radio();
   radio.setFrequency("32 MHz");
   s.persist(radio);
   assertEquals(new Integer(2), radio.getId());
   tx.commit();
   s.close();
 }
  @Test
  // there is a mismatch of the index name as handled by IndexManagerHolder and the ES-IM: Animal.0
  // vs. Animal00
  @Category(ElasticsearchSupportInProgress.class)
  public void testBehavior() throws Exception {
    Session s = openSession();
    Transaction tx = s.beginTransaction();
    Animal a = new Animal();
    a.setId(1);
    a.setName("Elephant");
    s.persist(a);
    a = new Animal();
    a.setId(2);
    a.setName("Bear");
    s.persist(a);
    tx.commit();

    s.clear();

    tx = s.beginTransaction();
    a = s.get(Animal.class, 1);
    a.setName("Mouse");
    Furniture fur = new Furniture();
    fur.setColor("dark blue");
    s.persist(fur);
    tx.commit();

    s.clear();

    tx = s.beginTransaction();
    FullTextSession fts = Search.getFullTextSession(s);
    QueryParser parser = new QueryParser("id", TestConstants.stopAnalyzer);

    List results = fts.createFullTextQuery(parser.parse("name:mouse OR name:bear")).list();
    assertEquals(
        "Either double insert, single update, or query fails with shards", 2, results.size());

    results = fts.createFullTextQuery(parser.parse("name:mouse OR name:bear OR color:blue")).list();
    assertEquals("Mixing shared and non sharded properties fails", 3, results.size());
    results = fts.createFullTextQuery(parser.parse("name:mouse OR name:bear OR color:blue")).list();
    assertEquals(
        "Mixing shared and non sharded properties fails with indexreader reuse", 3, results.size());
    for (Object o : results) {
      s.delete(o);
    }
    tx.commit();
    s.close();
  }
 @Override
 public void create(List<Statistics> statistics) {
   Session session = sessionFactory.getCurrentSession();
   for (Statistics stat : statistics) {
     session.persist(stat);
   }
 }
    public HibernateTestEntity runOperationInTxn() {
      HibernateTestEntity entity = new HibernateTestEntity();
      entity.setText(UNIQUE_TEXT);
      session.persist(entity);

      return entity;
    }
  public void insertTarjetaHistorico(PsTarjeta tarjeta, String xml) {

    try {

      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      Session newSession = sessionFactory.openSession();

      newSession.beginTransaction();
      ArmResponsePsTarjeta j = new ArmResponsePsTarjeta();
      j.setIdTarjetaArm(tarjeta.getIDTarjetaARM());
      j.setIdTarjetaFrida(tarjeta.getIDTarjetaFrida());
      j.setNombreTarjeta(tarjeta.getNombreTarjeta());
      j.setMeesageId(tarjeta.getMeesageID());
      j.setXmlMessage(xml);
      j.setFechaMensaje(new Date());

      newSession.persist(j);

      newSession.getTransaction().commit();
      newSession.close();

    } catch (HibernateException e) {

    } finally {

    }
  }
Example #28
0
  /**
   * Create a single <code>Patient</code> record. The generated id will be available in the
   * patientRecord.
   *
   * @param patientRecord
   * @return boolean
   */
  public boolean create(Patient patientRecord) {
    log.debug("PatientDAO.create() - Begin");
    Session session = null;
    Transaction tx = null;
    boolean result = true;

    if (patientRecord != null) {
      try {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        log.info("Inserting Record...");

        session.persist(patientRecord);

        log.info("Patient Inserted seccussfully...");
        tx.commit();
      } catch (Exception e) {
        result = false;
        if (tx != null) {
          tx.rollback();
        }
        log.error("Exception during insertion caused by :" + e.getMessage(), e);
      } finally {
        // Actual Patient insertion will happen at this step
        if (session != null) {
          session.close();
        }
      }
    }
    log.debug("PatientDAO.create() - End");
    return result;
  }
Example #29
0
 public void save(Treatment treatment) {
   Session session = this.sessionFactory.openSession();
   Transaction tx = session.beginTransaction();
   session.persist(treatment);
   tx.commit();
   session.close();
 }
Example #30
0
  public void testDefaultConfigurationModeIsInherited() throws Exception {
    User john = new User();
    john.setFirstname("John");
    john.setLastname("Doe");
    List<User> friends = new ArrayList<User>();
    User friend = new User();
    friend.setFirstname("Jane");
    friend.setLastname("Doe");
    friends.add(friend);
    john.setFriends(friends);

    Session s = openSession();
    s.persist(john);
    Transaction tx = s.beginTransaction();
    tx.commit();
    s.clear();
    tx = s.beginTransaction();
    john = (User) s.get(User.class, john.getId());
    assertEquals("Wrong number of friends", 1, john.getFriends().size());
    assertNull(john.firstname);

    s.delete(john);
    tx.commit();
    s.close();
  }