public static void main(String[] args) {
    HibernateUtils.start();
    HibernateUtils.startTransaction();
    Pessoa p = new Pessoa();
    p.setNome("Pedro");
    HibernateUtils.getSession().save(p);
    p.setNome("Pedro Batista");

    // Nem 'Pedro' nem 'Pedro Batista' será inserido!
    HibernateUtils.rollbackTransaction();
  }
 /** delete data by raw SQL */
 public void updateBySQL(String sql) {
   Session session = HibernateUtils.getSession();
   try {
     sql = sql + conditionBuilder.build();
     this.queryBuilder.buildSQLQuery(session, sql).executeUpdate();
   } catch (Throwable e) {
     LOGGER.error("fail to update, sql: {}, list: {}", sql, e);
     throw e;
   } finally {
     HibernateUtils.commit(session); // ensure session is closed
   }
 }
 /**
  * method to execute update
  *
  * @param clazz class to update
  * @param setClause such as 'username=:username,password=:password' and so on
  */
 public void update(Class<?> clazz, String setClause) {
   Session session = HibernateUtils.getSession();
   String hql =
       "UPDATE " + clazz.getSimpleName() + " SET " + setClause + " " + conditionBuilder.build();
   try {
     this.queryBuilder.buildQuery(session, hql).executeUpdate();
   } catch (Throwable e) {
     LOGGER.error("fail to update, hql: {}, info: {}", hql, e);
     throw e;
   } finally {
     HibernateUtils.commit(session); // ensure session is closed
   }
 }
 public static void inserePessoas() {
   HibernateUtils.startTransaction();
   Pessoa p = null;
   Calendar c = Calendar.getInstance();
   c.add(Calendar.YEAR, -101);
   for (int i = 1; i <= 10; i++) {
     p = new Pessoa();
     p.setNome(Integer.toString(i));
     c.add(Calendar.YEAR, 1);
     p.setNascimento((Calendar) c.clone());
     p.setSexo(i % 2 == 0 ? 'M' : 'F');
     p.setCasado(i % 2 == 0);
     p.setPeso(i);
     HibernateUtils.getSession().save(p);
   }
   HibernateUtils.commitTransaction();
 }
 private Criteria createCriteria() throws HibernateException {
   Session session = HibernateUtils.getSessionFactory().openSession();
   Criteria criteria = session.createCriteria(Emprestimo.class, "c");
   criteria.createAlias("c.bemMaterial", "bema");
   criteria.createAlias("bema.categoria", "cate");
   criteria.createAlias("cate.usuario", "u");
   criteria.add(Restrictions.eq("u.id", getUsrLogado().getId()));
   return criteria;
 }
  /**
   * Fermeture de la session courante.
   *
   * @throws DAORequestException Exception lors de la fermeture de la connexion.
   */
  public void close() throws DAORequestException {
    getSession().flush();
    HibernateUtils.closeSession();

    // Extension de la base pour l'écriture sur le fichier.
    try {
      Connection jdbcConnection =
          DriverManager.getConnection("jdbc:hsqldb:file:/tmp/dbtpj2ee/tpdb", "sa", "");
      jdbcConnection.createStatement().execute("SHUTDOWN");
      jdbcConnection.close();
    } catch (SQLException e) {
      throw new DAORequestException("Echec de fermeture de la connexion.", e);
    }
  }
Exemple #7
0
 public void savePet() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Cat cat = new Cat();
     cat.setId(1);
     cat.setName("cat");
     cat.setCatProperty("cat property");
     session.save(cat);
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #8
0
 public void deletePet() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     /**
      * 1. 这里需要注意, 如果此时1对应的一个对象时一个cat时, 也就是说此时cat中的pet_id=1, 那么 此时删除是会报错的, 因为此时删除pet, 但是外键约束,
      * 所以不能删除
      */
     //			Pet pet = new Pet();
     //			pet.setId(1);
     //			session.delete(pet);
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #9
0
 public void getPet() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     // Cat cat = (Cat) session.get(Cat.class, 1);
     // System.out.println(cat.getCatProperty());
     /**
      * 当使用pet来查找的时候, 虽然一个id肯定只能时对应于一个cat, 或者时一个dog但是它此时会连接所以 的pet dog cat表进行查找,
      * 因为此时它并不知道为1的pet到底是一个dog还是一个cat, 所以它会全部 都查找出来, 再根据结果来创建dog或者是cat。如果此时什么也不是, 那么此时的对象为一个pet。
      */
     Pet pet = (Pet) session.get(Pet.class, 1);
     System.out.println(pet.getClass());
     tx.rollback();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
  public void insertComponentUpdateEntry(
      String in_componentId,
      String in_updateName,
      List<ComponentDescription> in_componentDescriptions)
      throws LoggingException {

    Session session = null;
    session = HibernateUtils.getNewSession();

    if (session == null) return;

    ArrayList<CUDestination> cuDestinationList = new ArrayList<CUDestination>();
    ArrayList<CUAttribute> cuAttributeList = new ArrayList<CUAttribute>();

    ComponentUpdate componentUpdateEntry = new ComponentUpdate();
    componentUpdateEntry.setComponentid(in_componentId);
    componentUpdateEntry.setUpdatename(in_updateName);
    componentUpdateEntry.setUpdatetime(new Date());

    for (ComponentDescription compDescr : in_componentDescriptions) {
      // Set up the cuDestination entry
      CUDestination cuDestinationEntry = new CUDestination();
      cuDestinationEntry.setComponentUpdate(componentUpdateEntry);
      cuDestinationEntry.setDestinationcomponentid(compDescr.id);
      cuDestinationEntry.setSuccess(new Boolean(true));
      cuDestinationList.add(cuDestinationEntry);

      AttributeNameValue<?> attributeNameValue;

      // Set up the constant attribute entries
      for (Attribute<?> attribute : compDescr.getConstantAttributes()) {
        CUAttribute cuAttributeEntry = new CUAttribute();
        cuAttributeEntry.setAttributename(attribute.getName());
        cuAttributeEntry.setAttributetype(attribute.getType());
        cuAttributeEntry.setConstant(true);
        cuAttributeEntry.setCUDestination(cuDestinationEntry);

        // AttributeNameValue is a subclass of Attribute
        if (attribute instanceof AttributeNameValue<?>) {
          // check the value associated with this AttributeNameValue
          attributeNameValue = (AttributeNameValue<?>) attribute;
          if (attributeNameValue.getType().equals(String.class)) {
            cuAttributeEntry.setAttributevaluestring((String) attributeNameValue.getValue());
          } else if (attributeNameValue.getType().isInstance(Number.class)) {
            cuAttributeEntry.setAttributevaluenumeric(
                Float.valueOf(attributeNameValue.getValue().toString()));
          }
        }
        cuAttributeList.add(cuAttributeEntry);
      }

      // Set up the non constant attribute entries
      for (Attribute<?> attribute : compDescr.getNonConstantAttributes().values()) {
        CUAttribute cuAttributeEntry = new CUAttribute();
        cuAttributeEntry.setAttributename(attribute.getName());
        cuAttributeEntry.setAttributetype(attribute.getType());
        cuAttributeEntry.setConstant(false);
        cuAttributeEntry.setCUDestination(cuDestinationEntry);

        if (attribute instanceof AttributeNameValue<?>) {
          attributeNameValue = (AttributeNameValue<?>) attribute;
          if (attributeNameValue.getType().equals(String.class)) {
            cuAttributeEntry.setAttributevaluestring((String) attributeNameValue.getValue());
          } else if (attributeNameValue.getType().isInstance(Number.class)) {
            cuAttributeEntry.setAttributevaluenumeric(
                Float.valueOf(attributeNameValue.getValue().toString()));
          }
        }
        cuAttributeList.add(cuAttributeEntry);
      }
    }

    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      session.save(componentUpdateEntry);

      for (int i = 0; i < cuDestinationList.size(); i++) {
        session.save(cuDestinationList.get(i));
      }

      for (int i = 0; i < cuAttributeList.size(); i++) {
        session.save(cuAttributeList.get(i));
      }

      tx.commit(); // flush the Session and commit the transaction
    } catch (Exception e) {
      try {
        if (tx != null) tx.rollback(); // rollback the transaction
      } catch (Exception x) {
        throw new LoggingException(x);
      }
    } finally {
      try {
        session.close();
      } catch (Exception e) {
        throw new LoggingException(e);
      }
    }
  }
 @Override
 protected void close() {
   HibernateUtils.Close();
 }
 public static void main(String[] args) {
   HibernateUtils.start();
   inserePessoas();
 }
 /** Fermeture de la session courante. */
 public void closeSession() {
   HibernateUtils.closeSession();
 }
 /**
  * Retourne une session hibernate ou null si la factory n'est pas correctement initialisée.
  *
  * @return Une instance de Session
  */
 protected Session getSession() {
   return HibernateUtils.currentSession();
 }
 /**
  * Méthode de configuration de la factory.
  *
  * @throws DAOConfigureException Exception lors de la configuration du DAO.
  * @see fr.sigl.imoe.servlet.tp.dao.DAOFactory#configure()
  */
 protected void configure() throws DAOConfigureException {
   HibernateUtils.configure(HIBERNATE_CONFIG_FILENAME);
 }
Exemple #16
0
 /**
  * Получение следующего вопроса
  *
  * @param questionKind Маска поиска вопроса. Константы - в определении класса <br>
  *     ВНИМАНИЕ! Сейчас - не работает!
  * @return Следующий вопрос или null в случае проблем
  */
 public static Question getNextQuestion(int questionKind) {
   Question res = null;
   //
   Session sess = HibernateUtils.getSession();
   // Делаем хитрую сортировку. Пытаемся искать вопросы через random
   // Вопросы пытаемся искать до 3-х раз...
   int tries = 0;
   Criteria criteria;
   while (tries < 3) {
     double rand = Math.random();
     criteria =
         sess.createCriteria(Question.class)
             .addOrder(Order.asc("rand"))
             .add(Restrictions.eq("played", false))
             .add(Restrictions.ge("rand", rand));
     criteria.setMaxResults(1);
     res = (Question) criteria.uniqueResult();
     if (res == null) {
       tries++;
       rand /= 2;
     } else {
       break;
     }
   }
   if (res == null) {
     // Значит за 3 попытки не смогли найти вопрос - значит просто
     // выберем первый
     criteria =
         sess.createCriteria(Question.class)
             .addOrder(Order.asc("rand"))
             .add(Restrictions.eq("played", false));
     criteria = doFormKindsCriteria(criteria, questionKind);
     criteria.setMaxResults(1);
     res = (Question) criteria.uniqueResult();
   }
   // Отладочное
   // Question res = new Question();
   // res.setChampionship("ЧГК-микст \"Кубок Аленки - 2011\" (Санкт-Петербург)");
   // res.setDate("07-Jun-2011");
   // res.setInfo("Посвящено двухлетию Елены Львовны Орловой. Авторы благодарят за\n"
   // +
   // "тестирование и ценные советы Евгения Рубашкина, Асю Самойлову, Дмитрия\n"
   // +
   // "Карякина, Диану Ильягуеву, Анну Парфёнову, Сергея Коновалова, Ирину\n"
   // +
   // "Медноногову, Игоря Бахарева, Владимира Севриновского, Екатерину и\n"
   // + "Станислава Мереминских, Константина Изъюрова.");
   // res.setRound("1 тур");
   // res.setQuestionNum("Вопрос 1:");
   // res.setQuestion("(pic: 20110432.jpg) (pic: 20000001.gif)\n"
   // + "(aud: 20110001.mp3) (aud: 20050001.mp3)\n"
   // + "Тезка этих девочек, появившаяся на свет в Петербурге, по мнению\n"
   // +
   // "некоторых остряков, является однофамилицей советского политического\n"
   // + "деятеля. Назовите имя и отчество этого деятеля.");
   // res.setAnswer("Надежда Константиновна.");
   // res.setComment("Раздатка изображает обертки шоколадки \"Аленка\" разных лет. Петербургская\n"
   // +
   // "\"Фабрика им. Крупской\" выпускает шоколадки \"Крупская Аленка\".");
   // res.setSource("1. http://www.alenka.ru/museum/\n"
   // + "2. http://www.uralweb.ru/pages/article.4455.html");
   // res.setAuthor("Лев Орлов и Светлана Орлова");
   return res;
 }