コード例 #1
0
ファイル: GetDemo.java プロジェクト: bin2907/bin-examples
  public static void main(String[] args) {
    System.out.println("Hibernate smaple is running");

    Configuration configuration =
        new Configuration().configure(GetDemo.class.getResource("/hibernate.one.to.many.cfg.xml"));
    StandardServiceRegistryBuilder builder =
        new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());

    Session session = sessionFactory.openSession();

    User user = (User) session.get(User.class, 1);
    System.out.println(user);

    User user3 =
        (User)
            session.get(
                User.class,
                10); // 10 is not exist on db BUT not error => IT use load method WILL have
    // exception
    System.out.println(user3);

    sessionFactory.close();

    System.out.println("Hibernate sample stopped");
  }
コード例 #2
0
  public static void main(String[] args) {

    // Prep Work
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();

    try {
      Employee emp = (Employee) session.get(Employee.class, new Long(200));
      System.out.println("Employee get called");
      if (emp != null) {
        System.out.println("Employee GET ID= " + emp.getId());
        System.out.println("Employee Get Details:: " + emp + "\n");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    // load Example
    try {
      Employee emp1 = (Employee) session.load(Employee.class, new Long(100));
      System.out.println("Employee load called");
      System.out.println("Employee LOAD ID= " + emp1.getId());
      System.out.println("Employee load Details:: " + emp1 + "\n");
    } catch (Exception e) {
      e.printStackTrace();
    }

    // Close resources
    tx.commit();
    sessionFactory.close();
  }
コード例 #3
0
 public void dispose() {
   try {
     factory.close();
   } catch (Exception e) {
     LOG.error("error closing", e);
   }
 }
コード例 #4
0
ファイル: StoreData.java プロジェクト: swetha2104/JHApp
  public ArrayList store() {
    Configuration cfg = new Configuration();
    cfg.configure();
    SessionFactory sf = cfg.buildSessionFactory();
    Session hs = sf.openSession();

    String hqlquery = "from com.mangium.Car";
    Query query = hs.createQuery(hqlquery);
    ArrayList list = (ArrayList) query.list();
    Iterator i = list.iterator();

    cr = new ArrayList();

    while (i.hasNext()) {
      Car c = (Car) i.next();
      System.out.println(c.getCarid());
      System.out.println(c.getCarname());
      System.out.println(c.getCarcost());
      System.out.println(c.getCartype());
      cr.add(c);
    }
    hs.close();
    sf.close();

    System.out.println(cr);
    setCr(cr);
    return cr;
  }
コード例 #5
0
  @SuppressWarnings({"unchecked"})
  public static void main(String[] args) {
    SessionFactory factory = null;
    Session session = null;
    org.hibernate.Transaction tx = null;

    try {
      factory = HibernateUtil.getSessionFactory();
      session = factory.openSession();
      tx = session.beginTransaction();

      //			Query query = session.createQuery("select distinct t.account from Transaction t"
      //				+ " where t.amount > 500 and lower(t.transactionType) = 'deposit'");

      Query query = session.getNamedQuery("Account.largeDeposits");
      List<Account> accounts = query.list();

      for (Account a : accounts) {
        System.out.println(a.getName());
      }

      tx.commit();
    } catch (Exception e) {
      e.printStackTrace();
      tx.rollback();
    } finally {
      session.close();
      factory.close();
    }
  }
コード例 #6
0
ファイル: AppHQL.java プロジェクト: rzuniga64/hibernate
  @SuppressWarnings("unchecked")
  public static void main(String[] args) {

    SessionFactory factory = null;
    Session session = null;
    org.hibernate.Transaction tx = null;

    try {
      factory = HibernateUtil.getSessionFactory();
      session = factory.openSession();
      tx = session.beginTransaction();

      Query query = session.createQuery("select t from Transaction t");

      List<Transaction> transactions = query.list();

      for (Transaction transaction : transactions) {
        System.out.println(transaction.getTitle());
      }

      tx.commit();
    } catch (Exception e) {
      tx.rollback();
    } finally {
      session.close();
      factory.close();
    }
  }
コード例 #7
0
  @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    SessionFactory factory = null;
    Session session = null;
    org.hibernate.Transaction tx = null;

    try {
      factory = HibernateUtil.getSessionFactory();
      session = factory.openSession();
      tx = session.beginTransaction();

      List<Transaction> transactions =
          session.createCriteria(Transaction.class).addOrder(Order.desc("title")).list();

      for (Transaction t : transactions) {
        System.out.println(t.getTitle());
      }

      tx.commit();

    } catch (Exception e) {
      e.printStackTrace();
      tx.rollback();
    } finally {
      session.close();
      factory.close();
    }
  }
コード例 #8
0
ファイル: AppConflict.java プロジェクト: zberhe/EA
  public static void main(String[] args) {
    Session session = null;
    Transaction tx = null;
    try {
      session = sessionFactory.openSession();
      tx = session.beginTransaction();

      // retieve all cars
      @SuppressWarnings("unchecked")
      Car car = (Car) session.createQuery("from Car c where id =1").uniqueResult();
      car.setPrice(car.getPrice() + 50);

      tx.commit();
      System.out.println(
          "brand= " + car.getBrand() + ", year= " + car.getYear() + ", price= " + car.getPrice());

    } catch (HibernateException e) {
      if (tx != null) {
        System.err.println("Rolling back: " + e.getMessage());
        tx.rollback();
      }
    } finally {
      if (session != null) {
        session.close();
      }
    }

    // Close the SessionFactory (not mandatory)
    sessionFactory.close();
    System.exit(0);
  }
コード例 #9
0
ファイル: SessionIntro.java プロジェクト: hephecqq/hibernate
 @After
 public void destroy() {
   // System.out.println("destroy...");
   transaction.commit();
   session.close();
   sessionFactory.close();
 }
コード例 #10
0
 public void complete() {
   if (sessionFactory != null) {
     sessionFactory.close();
     sessionFactory = null;
   }
   configuration = null;
 }
コード例 #11
0
  public static void main(String args[]) throws Exception {
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession(); // changed to
    // openSession
    Transaction tx = session.beginTransaction();
    Department department;

    // Demo 1: Get single record
    department = (Department) session.get(Department.class, "IT");
    System.out.println("Name for IT = " + department.getName());

    // Demo 2: Get all records
    List departmentList = session.createQuery("from Department").list();
    for (int i = 0; i < departmentList.size(); i++) {
      department = (Department) departmentList.get(i);
      System.out.println(
          "Row "
              + (i + 1)
              + "> "
              + department.getName()
              + " ("
              + department.getDepartmentCode()
              + ")");
    }

    tx.commit();
    session.close();
    sessionFactory.close();
  }
コード例 #12
0
ファイル: Display.java プロジェクト: aparajitha-n/Lava
  public static void main(String a[]) {
    try {
      Configuration cfg = new Configuration();
      cfg.configure("/Hibernate.cfg.xml");
      SessionFactory factory = cfg.buildSessionFactory();
      Session session = factory.openSession();
      Transaction tx = session.beginTransaction();

      //        Object o=session.load(Data.class,5);
      //        Data s=(Data)o;
      //        String s1=s.getSname();
      //        System.out.println(s1);
      //        String i=s.getAddress();
      //        System.out.println(i);

      Data s = new Data();
      s.setSid(111);
      s.setSname("hai");
      s.setAddress("hello");

      session.save(s);
      tx.commit();

      session.close();
      factory.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
コード例 #13
0
  /** Close database connection */
  public void closeSession() {

    LOG.info("Closing hibernate session");

    session.close();
    factory.close();
  }
コード例 #14
0
 public void set(Entrada x) {
   SessionFactory factory = new Configuration().configure().buildSessionFactory();
   Session session = factory.getCurrentSession();
   session.beginTransaction();
   session.save(x);
   session.getTransaction().commit();
   factory.close();
 }
コード例 #15
0
ファイル: HibernateUtil.java プロジェクト: Temster/Bakalarka
 public static void closeFactory() {
   if (sessionFactory != null) {
     try {
       sessionFactory.close();
     } catch (HibernateException e) {
       System.out.println(e);
     }
   }
 }
コード例 #16
0
 /**
  * Rebuild the SessionFactory with the given Hibernate Configuration.
  *
  * <p>HibernateUtil does not configure() the given Configuration object, it directly calls
  * buildSessionFactory(). This method also closes the old SessionFactory before, if still open.
  *
  * @param cfg
  */
 public static void rebuildSessionFactory(Configuration cfg) {
   log.debug("Rebuilding the SessionFactory from given Configuration.");
   synchronized (sessionFactory) {
     if (sessionFactory != null && !sessionFactory.isClosed()) sessionFactory.close();
     if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) cfg.buildSessionFactory();
     else sessionFactory = cfg.buildSessionFactory();
     configuration = cfg;
   }
 }
コード例 #17
0
ファイル: MainTester.java プロジェクト: UpSport/loop
  public static void main(String args[]) throws Exception {
    sessionFactory = new SessionFactoryProvider().provide();
    transientSessionExecutor = new TransientSessionExecutor(sessionFactory);

    // addUp();
    // query();

    sessionFactory.close();
  }
コード例 #18
0
 public ArrayList<Entrada> all() throws Exception {
   SessionFactory factory = new Configuration().configure().buildSessionFactory();
   Session session = factory.getCurrentSession();
   session.beginTransaction();
   ArrayList<Entrada> l = (ArrayList<Entrada>) session.createQuery("FROM Entrada").list();
   session.getTransaction().commit();
   factory.close();
   return l;
 }
コード例 #19
0
 public static void closeSession() {
   if (session != null && session.isOpen()) {
     session.disconnect();
     session.flush();
     session.close();
     session = null;
     sessionFactory.close();
     isSessionOpen = false;
   }
 }
コード例 #20
0
  @After
  public void cleanDb() {
    Session session = sessionFactory.openSession();

    session.createQuery("delete from Task").executeUpdate();

    session.close();

    sessionFactory.close();
  }
コード例 #21
0
ファイル: HibernateUtil.java プロジェクト: spydemon/Royal_
 /**
  * Shutdown the hsqldb database
  *
  * @throws SQLException
  * @throws HibernateException
  */
 public static void shutdown() throws HibernateException, SQLException {
   if (sessionFactory != null) {
     if (selectedDB.getDialect().equals(HSQLDB)) {
       HibernateUtil.currentSession().connection().createStatement().execute("SHUTDOWN");
     }
     sessionFactory.close();
   }
   HibernateUtil.closeSession();
   sessionFactory = null;
 }
コード例 #22
0
 public void rebuild() {
   if (!allowRebuild) {
     return;
   }
   if (sessionFactory != null) {
     sessionFactory.close();
     sessionFactory = null;
   }
   sessionFactory = configuration.buildSessionFactory();
   settings.afterSessionFactoryBuilt((SessionFactoryImplementor) sessionFactory);
 }
コード例 #23
0
  @Test
  public void testGeneratedUuidId() {
    StandardServiceRegistry ssr =
        new StandardServiceRegistryBuilder()
            .applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop")
            .build();
    try {
      Metadata metadata =
          new MetadataSources(ssr).addAnnotatedClass(TheEntity.class).buildMetadata();
      ((MetadataImpl) metadata).validate();

      PersistentClass entityBinding = metadata.getEntityBinding(TheEntity.class.getName());
      assertEquals(UUID.class, entityBinding.getIdentifier().getType().getReturnedClass());
      IdentifierGenerator generator =
          entityBinding
              .getIdentifier()
              .createIdentifierGenerator(
                  metadata.getIdentifierGeneratorFactory(),
                  metadata.getDatabase().getDialect(),
                  null,
                  null,
                  (RootClass) entityBinding);
      assertTyping(UUIDGenerator.class, generator);

      // now a functional test
      SessionFactory sf = metadata.buildSessionFactory();
      try {
        TheEntity theEntity = new TheEntity();

        Session s = sf.openSession();
        s.beginTransaction();
        s.save(theEntity);
        s.getTransaction().commit();
        s.close();

        assertNotNull(theEntity.id);

        s = sf.openSession();
        s.beginTransaction();
        s.delete(theEntity);
        s.getTransaction().commit();
        s.close();
      } finally {
        try {
          sf.close();
        } catch (Exception ignore) {
        }
      }
    } finally {
      StandardServiceRegistryBuilder.destroy(ssr);
    }
  }
コード例 #24
0
ファイル: HibernatePlugIn.java プロジェクト: gusmina/sicaco
  /** Destroys the <code>SessionFactory</code> instance. */
  public void destroy() {
    _servlet = null;
    _config = null;
    try {
      _log.info("Destroying SessionFactory...");

      _factory.close();

      _log.info("SessionFactory destroyed...");
    } catch (Exception e) {
      _log.error("Unable to destroy SessionFactory...(exception ignored)", e);
    }
  }
コード例 #25
0
 @Test
 public void testOverwritesCacheManager() throws NoSuchFieldException, IllegalAccessException {
   URL resource =
       ClassLoaderUtil.getStandardClassLoader().getResource("hibernate-config/ehcache.xml");
   config.setProperty("net.sf.ehcache.configurationResourceName", "file://" + resource.getFile());
   config.setProperty("net.sf.ehcache.cacheManagerName", "overwrittenCacheManagerName");
   SessionFactory sessionFactory = config.buildSessionFactory();
   final Field cache_managers_map = CacheManager.class.getDeclaredField("CACHE_MANAGERS_MAP");
   cache_managers_map.setAccessible(true);
   assertThat(((Map) cache_managers_map.get(null)).get("tc"), nullValue());
   assertThat(
       ((Map) cache_managers_map.get(null)).get("overwrittenCacheManagerName"), notNullValue());
   sessionFactory.close();
 }
コード例 #26
0
 public Boolean exists(String identificador) throws Exception {
   SessionFactory factory = new Configuration().configure().buildSessionFactory();
   Session session = factory.getCurrentSession();
   session.beginTransaction();
   ArrayList<Entrada> l =
       (ArrayList<Entrada>)
           session
               .createQuery("FROM Entrada WHERE identificador = :em")
               .setParameter("em", identificador)
               .list();
   session.getTransaction().commit();
   factory.close();
   return l != null;
 }
コード例 #27
0
ファイル: Demo.java プロジェクト: jagadeesh-mri/test
  public static void main(String[] args) {

    Employee employee = new Employee(123, "Jagadeesh", 112211);

    Configuration configuration = new Configuration();
    configuration.configure();
    SessionFactory sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();

    transaction.commit();
    session.close();
    sessionFactory.close();
  }
コード例 #28
0
  public static boolean reg(String username, String password) {
    boolean flag = false;

    SessionFactory sf = new Configuration().configure().buildSessionFactory();
    Session session = sf.openSession();
    session.beginTransaction();
    Users s = new Users();
    s.setUsername(username);
    s.setPassword(password);
    session.save(s);
    session.getTransaction().commit();
    sf.close();
    return flag;
  }
コード例 #29
0
  @Override
  protected void runChild(FrameworkMethod method, RunNotifier notifier) {
    // create test method scoped SF if required; it will be injected in createTest()
    if (isTestMethodScopedSessionFactoryRequired(method)) {
      testMethodScopedSessionFactory = buildSessionFactory();
    }

    try {
      super.runChild(method, notifier);
    } finally {
      if (testMethodScopedSessionFactory != null) {
        testMethodScopedSessionFactory.close();
      }
    }
  }
 public static void shutdownHsql() {
   try {
     if (sessionFactory == null) return;
     logger.info("Shutting down HSQLDB...");
     org.hibernate.Session s = HibernateUtils.getSessionFactory().getCurrentSession();
     s.beginTransaction();
     s.connection().createStatement().execute("SHUTDOWN");
     s.getTransaction().commit();
     closeSession();
     sessionFactory.close();
     sessionFactory = null;
   } catch (Exception e) {
     logger.error(e.getMessage());
   }
 }