Example #1
0
  public ArrayList<City> getCitiesByZone(int idzone) {
    Session session = HibernateUtils.getSessionFactory().openSession();
    ArrayList<City> list = new ArrayList<City>();
    try {
      session.clear();
      Criteria cr = session.createCriteria(TblCity.class, "city");
      cr.createAlias("city.zone", "zone");
      cr.add(Restrictions.eq("zone.idzone", idzone));
      cr.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
      List<TblCity> cities = cr.list();
      if (cities.size() > 0) {
        for (Iterator<TblCity> iterator = cities.iterator(); iterator.hasNext(); ) {
          TblCity tblcity = iterator.next();
          City city = new City();
          city.convertFromTable(tblcity);
          list.add(city);
        }
      }
      session.clear();
    } catch (HibernateException e) {
      System.err.println("ERROR IN LIST!!!!!!");
      e.printStackTrace();
      throw new ExceptionInInitializerError(e);
    } finally {

      session.close();
    }
    return list;
  }
Example #2
0
  public ArrayList<Zone> getZones(int idcountry) {
    Session session = HibernateUtils.getSessionFactory().openSession();
    ArrayList<Zone> list = new ArrayList<Zone>();
    try {
      session.clear();
      Criteria cr = session.createCriteria(TblZone.class, "zone");
      cr.createAlias("zone.country", "country");
      cr.add(Restrictions.eq("country.idcountry", idcountry));
      cr.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
      List<TblZone> zones = cr.list();
      if (zones.size() > 0) {
        for (Iterator<TblZone> iterator = zones.iterator(); iterator.hasNext(); ) {
          TblZone tblzone = iterator.next();
          Zone zone = new Zone();
          zone.convertFromTable(tblzone);
          list.add(zone);
        }
      }
      session.clear();
    } catch (HibernateException e) {
      System.err.println("ERROR IN LIST!!!!!!");
      e.printStackTrace();
      throw new ExceptionInInitializerError(e);
    } finally {

      session.close();
    }
    return list;
  }
Example #3
0
  public ArrayList<Country> getCountries() {
    Session session = HibernateUtils.getSessionFactory().openSession();
    ArrayList<Country> list = new ArrayList<Country>();
    try {
      session.clear();
      Criteria cr = session.createCriteria(TblCountry.class, "country");
      cr.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
      List<TblCountry> countries = cr.list();
      if (countries.size() > 0) {
        for (Iterator<TblCountry> iterator = countries.iterator(); iterator.hasNext(); ) {
          TblCountry tblcountry = iterator.next();
          Country country = new Country();
          country.convertFromTable(tblcountry);
          list.add(country);
        }
      }
      session.clear();
    } catch (HibernateException e) {
      System.err.println("ERROR IN LIST!!!!!!");
      e.printStackTrace();
      throw new ExceptionInInitializerError(e);
    } finally {

      session.close();
    }
    return list;
  }
  public void testLoadingStrategies() {
    Session s = openSession();
    s.beginTransaction();
    Customer cust = new Customer("Acme, Inc.");
    Order order = new Order(new Order.Id(cust, 1));
    cust.getOrders().add(order);
    s.save(cust);
    s.getTransaction().commit();
    s.close();

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

    cust = (Customer) s.get(Customer.class, cust.getId());
    assertEquals(1, cust.getOrders().size());
    s.clear();

    cust = (Customer) s.createQuery("from Customer").uniqueResult();
    assertEquals(1, cust.getOrders().size());
    s.clear();

    cust = (Customer) s.createQuery("from Customer c join fetch c.orders").uniqueResult();
    assertEquals(1, cust.getOrders().size());
    s.clear();

    s.delete(cust);
    s.getTransaction().commit();
    s.close();
  }
Example #5
0
  /** 批量操作对象:添加、修改、删除 */
  private static void optEntities(final List<?> entities, final int opt) throws Exception {
    if (entities == null || entities.isEmpty()) {
      return;
    }

    Object idf = null;
    Session session = null;
    Transaction tx = null;
    try {
      idf = HibernateUtil.createSession();
      session = HibernateUtil.getSession();
      tx = session.beginTransaction();

      Object entity;
      for (int i = 0, len = entities.size(); i < len; i++) {
        entity = entities.get(i);
        if (entity == null) {
          continue;
        }

        switch (opt) {
          case OPT_SAVE:
            session.save(entity);
            break;
          case OPT_UPDATE:
            session.update(entity);
            break;
          case OPT_DELETE:
            session.delete(entity);
            break;
          default:
            break;
        }

        if ((i + 1) % 50 == 0) {
          session.flush();
          session.clear();
        }
      }

      session.flush();
      session.clear();
      tx.commit();
    } catch (Exception e) {
      if (tx != null) {
        tx.rollback();
        session.clear();
      }

      throw error(".optEntities()", e);
    } finally {
      if (idf != null && session != null) {
        closeQuickly(idf);
      }
    }
  }
Example #6
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();
  }
  public void testFieldBridge() throws Exception {
    LeakingLuceneBackend.reset();

    PersonPK johnDoePk = new PersonPK();
    johnDoePk.setFirstName("John");
    johnDoePk.setLastName("Doe");
    PersonCustomDocumentId johnDoe = new PersonCustomDocumentId();
    johnDoe.setFavoriteColor("Blue");
    johnDoe.setPersonNames(johnDoePk);
    johnDoe.setSecurityNumber("AB123");

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.save(johnDoe);
    tx.commit();
    s.clear();

    List<LuceneWork> lastProcessedQueue = LeakingLuceneBackend.getLastProcessedQueue();
    assertEquals(1, lastProcessedQueue.size());
    LuceneWork luceneWork = lastProcessedQueue.get(0);
    assertEquals("AB123", luceneWork.getIdInString());

    tx = s.beginTransaction();

    QueryBuilder queryBuilder =
        getSearchFactory().buildQueryBuilder().forEntity(PersonCustomDocumentId.class).get();
    Query query =
        queryBuilder.keyword().onField("id").ignoreAnalyzer().matching("AB123").createQuery();

    List results =
        Search.getFullTextSession(s)
            .createFullTextQuery(query, PersonCustomDocumentId.class)
            .list();
    assertEquals(1, results.size());
    johnDoe = (PersonCustomDocumentId) results.get(0);
    johnDoe.setFavoriteColor("Red");
    tx.commit();
    s.clear();

    tx = s.beginTransaction();
    results =
        Search.getFullTextSession(s)
            .createFullTextQuery(query, PersonCustomDocumentId.class)
            .list();
    assertEquals(1, results.size());
    johnDoe = (PersonCustomDocumentId) results.get(0);
    assertEquals("Red", johnDoe.getFavoriteColor());
    s.delete(results.get(0));
    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();
  }
  public void testEjb3ProxyUsage() {
    Session s = openSession();
    Transaction txn = s.beginTransaction();

    Item item = (Item) s.load(Item.class, new Long(-1));
    assertFalse(Hibernate.isInitialized(item));
    try {
      Hibernate.initialize(item);
      fail("proxy access did not fail on non-existent proxy");
    } catch (EntityNotFoundException e) {
      // expected behavior
    } catch (Throwable t) {
      fail("unexpected exception type on non-existent proxy access : " + t);
    }

    s.clear();

    Item item2 = (Item) s.load(Item.class, new Long(-1));
    assertFalse(Hibernate.isInitialized(item2));
    assertFalse(item == item2);
    try {
      item2.getName();
      fail("proxy access did not fail on non-existent proxy");
    } catch (EntityNotFoundException e) {
      // expected behavior
    } catch (Throwable t) {
      fail("unexpected exception type on non-existent proxy access : " + t);
    }

    txn.commit();
    s.close();
  }
Example #10
0
  @SuppressWarnings("unchecked")
  @Transactional(
      propagation = Propagation.REQUIRES_NEW,
      readOnly = false,
      rollbackFor = Throwable.class)
  private void removeRoles(Flota f) {
    try {
      if (f != null && f.getId() != null) {
        Session currentSession = getSession();
        currentSession.clear();

        f = this.get(f.getId());

        final Set<Rol> roles = Collections.unmodifiableSet(f.getRoles());
        if (f != null && roles != null)
          for (Rol r : roles) {
            r = (Rol) currentSession.get(Rol.class, r.getId());
            if (r != null && r.getFlotas() != null) {
              final Set<Flota> flotas = Collections.unmodifiableSet(r.getFlotas());
              List<Flota> aBorrar = new LinkedList<Flota>();
              for (Flota fl : flotas) if (fl.getId().equals(f.getId())) aBorrar.add(fl);
              for (Flota fl : aBorrar) r.getFlotas().remove(fl);
              currentSession.saveOrUpdate(r);
            }
          }
      }
    } catch (Throwable t) {
      log.error(t, t);
    }
  }
Example #11
0
  @SuppressWarnings("unchecked")
  public static List<Profile> getProfileList() {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;

    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      List<Profile> profiles =
          session
              .createQuery(
                  "SELECT distinct profile "
                      + "FROM Profile profile "
                      + "left join fetch profile.layoutProfiles laypro "
                      + "left join fetch laypro.layout "
                      + "ORDER BY profile.name, laypro.ordering ")
              .list();

      tx.commit();
      return profiles;
    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
      return null;
    } finally {
      session.clear();
      session.close();
    }
  }
Example #12
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();
  }
  public void testUpdateOwnerAfterClear() {
    Session s = openSession();
    s.beginTransaction();
    Parent p = new Parent("p");
    p.getChildren().add(new Child("c"));
    s.save(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    p = (Parent) s.get(Parent.class, "p");
    // clear...
    s.clear();
    // now try to reattach...
    s.update(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    s.delete(p);
    s.getTransaction().commit();
    s.close();
  }
Example #14
0
  public static void deleteProfile(Profile profile) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;

    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      for (LayoutProfile layoutProfile : profile.getLayoutProfiles()) {
        session.delete(layoutProfile);
      }

      session.delete(profile);

      tx.commit();

    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
    } finally {
      session.clear();
      session.close();
    }
  }
  /**
   * Tests that @DocumentId can be specified on a field other than the @Id annotated one. See
   * HSEARCH-574.
   *
   * @throws Exception in case the test fails.
   */
  @Test
  public void testExplicitDocumentIdMultipleResults() throws Exception {
    Article hello = new Article();
    hello.setDocumentId(1);
    hello.setText("Hello World");

    Article goodbye = new Article();
    goodbye.setDocumentId(2);
    goodbye.setText("Goodbye World");

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.save(hello);
    s.save(goodbye);
    tx.commit();
    s.clear();

    tx = s.beginTransaction();
    List results =
        Search.getFullTextSession(s)
            .createFullTextQuery(new TermQuery(new Term("text", "world")))
            .list();
    assertEquals(2, results.size());
    tx.commit();
    s.close();
  }
Example #16
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();
  }
Example #17
0
  public static Profile getProfile(Long id) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;

    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      Profile profile =
          (Profile)
              session
                  .createQuery(
                      "SELECT distinct profile "
                          + "FROM Profile profile "
                          + "left join fetch profile.layoutProfiles laypro "
                          + "left join fetch laypro.layout "
                          + "WHERE profile.id = :pid ")
                  .setParameter("pid", id)
                  .uniqueResult();

      tx.commit();

      return profile;
    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
      return null;
    } finally {
      session.clear();
      session.close();
    }
  }
  @Test
  @SuppressWarnings("unchecked")
  public void testGrantAllResourceToDept() throws Exception {
    // 岗位ID
    String deptId = "8a8140ef4c112cf6014c112d6efd0000";

    // 查询出所有有效的菜单的ID(在权限表中,资源的id对应的是菜单的id)
    List<String> resourceIds =
        session
            .createCriteria(Menu.class)
            .setProjection(Projections.id())
            .add(Restrictions.eq("status", CommonStatus.ACTIVE.getValue()))
            .add(Restrictions.eq("show", true))
            .list();
    Assert.assertNotNull("没有查询到菜单资源数据!", resourceIds);
    Assert.assertTrue("没有查询到菜单资源数据!", !resourceIds.isEmpty());

    logger.info("开始将[菜单资源]授予岗位:" + deptId);
    int i = 0;
    for (String id : resourceIds) {
      AccreditMenu accreditMenu = new AccreditMenu();
      accreditMenu.setResourceId(id);
      accreditMenu.setDeptId(deptId);
      accreditMenu.setId(UUIDGenerator.generate());
      session.save(accreditMenu);
      if (i++ % 10 == 0) {
        session.flush();
        session.clear();
      }
    }
  }
  @Test
  public void testUnidirectionalManyToMany() {
    Session session = openSession();
    Transaction tx = session.beginTransaction();

    Student john = new Student("john", "John Doe");
    Student kate = new Student("kate", "Kate Doe");
    Student mario = new Student("mario", "Mario Rossi");

    ClassRoom math = new ClassRoom(1L, "Math");
    math.getStudents().add(john);
    math.getStudents().add(mario);
    ClassRoom english = new ClassRoom(2L, "English");
    english.getStudents().add(kate);
    math.getStudents().add(mario);

    persist(session, math, english, john, mario, kate);
    tx.commit();

    assertThat(getNumberOfEntities(sessionFactory)).isEqualTo(5);
    assertThat(getNumberOfAssociations(sessionFactory)).isEqualTo(expectedAssociationNumber());
    session.clear();

    delete(session, math, english, john, mario, kate);

    session.close();
    checkCleanCache();
  }
  public void saveUser(User aUser, ArrayList<Authorization> aAuthorizationList)
      throws ControllerException {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;
    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      session.saveOrUpdate(aUser);
      for (Authorization authorization : aUser.getAuthorizations()) {
        session.delete(authorization);
      }
      Authorization authorization;
      for (Authorization newAuthorization : aAuthorizationList) {
        session.save(newAuthorization);
      }

      tx.commit();
    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
      throw new ControllerException("à¡Ô´¤ÇÒÁ¼Ô´¾ÅÒ´ÃÐËÇèÒ§¡Òúѹ·Ö¡ÃÒ¡ÒüÙéãªé");
    } finally {
      session.clear();
      session.close();
      //			if (session!= null && session.isOpen()) {
      //				session.close();
      //			}
    }
  }
Example #21
0
  @Override
  public ArrayList<User> getAllUsers() throws Exception {
    dLog.info("Entering method getAllUsers");
    ArrayList<User> result = new ArrayList<User>();
    Session session = null;

    try {
      session = getSession();
      session.clear();
      Transaction tranx = session.beginTransaction();

      String hql = "select from User";
      Query query = session.createQuery(hql);
      List<?> list = query.list();

      for (int n = 0; n < list.size(); n++) {
        result.add((User) list.get(n));
      }

      tranx.commit();
      session.flush();
      session.evict(User.class);
    } catch (Exception e) {
      dLog.error("Exception in getAllUsers", e);
    } finally {
      // ensure that session is close regardless of the errors in try/catch
      if (session != null) {
        session.close();
      }
    }

    return result;
  }
  public User checkDuplicateUser(String aUsername) throws ControllerException {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;
    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      User user =
          (User)
              session
                  .createQuery(
                      "SELECT DISTINCT user "
                          + "FROM User user "
                          + "WHERE "
                          + "user.username = :pusername "
                          + "AND user.status = 'NORMAL' "
                          + "AND user.mainSystemName = 'SYS_MAIN_STOCK' ")
                  .setParameter("pusername", aUsername)
                  .uniqueResult();
      tx.commit();
      return user;
    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
      throw new ControllerException("à¡Ô´¤ÇÒÁ¼Ô´¾ÅÒ´ÃÐËÇèÒ§¡Òô֧¢éÍÁÙÅ");
    } finally {
      session.clear();
      session.close();
    }
  }
  @Test
  public void testUpdateAfterClear() {
    Session s = openSession();
    s.beginTransaction();
    Parent p = new Parent("p");
    s.save(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    p = (Parent) s.load(Parent.class, "p");
    // clear...
    s.clear();
    // now try to reattach...
    s.update(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    s.delete(p);
    s.getTransaction().commit();
    s.close();
  }
Example #24
0
  public static Panel savePanel(Panel panel) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;

    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      session.saveOrUpdate(panel);

      tx.commit();

      return panel;
    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
      return null;
    } finally {
      session.clear();
      session.close();
    }
  }
  /**
   * Tests that the document id must be unique
   *
   * @throws Exception in case the test fails.
   */
  @Test
  public void testDocumentIdMustBeUnique() throws Exception {
    Article hello = new Article();
    hello.setDocumentId(1);
    hello.setText("Hello World");

    Article goodbye = new Article();
    goodbye.setDocumentId(1);
    goodbye.setText("Goodbye World");

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.save(hello);
    s.save(goodbye);
    tx.commit();
    s.clear();

    tx = s.beginTransaction();
    try {
      Search.getFullTextSession(s)
          .createFullTextQuery(new TermQuery(new Term("text", "world")))
          .list();
      fail("Test should fail, because document id is not unique.");
    } catch (SearchException e) {
      assertEquals(
          "Loading entity of type org.hibernate.search.test.id.Article using 'documentId' as document id and '1' as value was not unique",
          e.getMessage());
    }
    tx.commit();
    s.close();
  }
Example #26
0
  public static List<ClientProfile> getClientProfileList() {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;

    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      List<ClientProfile> profiles =
          session.createQuery("SELECT distinct profile " + "FROM ClientProfile profile ").list();

      tx.commit();
      return profiles;
    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
      return null;
    } finally {
      session.clear();
      session.close();
    }
  }
  /**
   * Opens new session or returns currently open session for this thread.
   *
   * @return session object.
   * @throws HibernateException if something with session creation goes wrong.
   */
  public static Session openSession() throws HibernateException {
    if (!inited) init();

    Session s = SESSION.get();
    if (s != null) {
      LOG.log(
          Level.WARNING,
          "Openning session more than once from the same thread!",
          new Exception("Dump"));

      s.clear();

      return s;
    } else {
      try {
        lock.lock();
      } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted waiting for session.");
      }

      s = sessionHandler.getSession();
      SESSION.set(s);
    }

    return s;
  }
Example #28
0
  public static ClientProfile getClientProfileByDisplay(String display) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;

    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      ClientProfile profiles =
          (ClientProfile)
              session
                  .createQuery(
                      "SELECT distinct client "
                          + "FROM ClientProfile client "
                          + "left join fetch client.layout layout "
                          + "left join fetch client.profile profile "
                          + "left join fetch profile.layoutProfiles laypro "
                          + "left join fetch layout.panels panel "
                          + "left join fetch panel.texts "
                          + "left join fetch panel.videos "
                          + "left join fetch panel.images "
                          + "left join fetch panel.webs "
                          + "left join fetch panel.slideShows "
                          + "left join fetch panel.feeds "
                          + "left join fetch laypro.layout lay "
                          + "left join fetch lay.panels pan "
                          + "left join fetch pan.texts "
                          + "left join fetch pan.videos "
                          + "left join fetch pan.images "
                          + "left join fetch pan.webs "
                          + "left join fetch pan.slideShows "
                          + "left join fetch pan.feeds "
                          + "WHERE client.clientName = :pname")
                  .setParameter("pname", display)
                  .uniqueResult();

      tx.commit();

      if (profiles != null && profiles.getProfile() != null) {
        Map<Long, LayoutProfile> map = new LinkedHashMap<Long, LayoutProfile>();
        for (LayoutProfile layoutProfile : profiles.getProfile().getLayoutProfiles()) {
          map.put(layoutProfile.getId(), layoutProfile);
        }
        profiles.getProfile().getLayoutProfiles().clear();
        profiles.getProfile().getLayoutProfiles().addAll(map.values());
      }

      return profiles;
    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
      return null;
    } finally {
      session.clear();
      session.close();
    }
  }
Example #29
0
  public static List<Object[]> executeTerminal(String sql) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = null;
    Transaction tx = null;

    try {
      session = sf.openSession();
      tx = session.beginTransaction();

      List<Object[]> result = session.createSQLQuery(sql).list();

      tx.commit();

      return result;
    } catch (Exception e) {
      e.printStackTrace();
      if (tx != null) {
        tx.rollback();
      }
      return null;
    } finally {
      session.clear();
      session.close();
    }
  }
  public Object inserirComCommit(Object objeto) throws ErroRepositorioException {

    Session session = HibernateUtil.getSession();

    Object retorno = null;

    try {

      // session.beginTransaction();
      session.persist(objeto);
      retorno = session.save(objeto);
      //	session.getTransaction().commit();
      session.flush();
      session.clear();

      return retorno;
    } catch (GenericJDBCException ex) {
      ex.printStackTrace();
      throw new ErroRepositorioException(ex, "Erro no Hibernate");
    } catch (CallbackException e) {
      e.printStackTrace();
      throw new ErroRepositorioException(e, e.getMessage());
    } catch (HibernateException e) {
      e.printStackTrace();
      throw new ErroRepositorioException(e, "Erro no Hibernate");
    } finally {
      HibernateUtil.closeSession(session);
    }
  }