Пример #1
0
  public static void main(String[] args) {

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    // CREATE
    for (int i = 1; i <= 30; i++) {
      UserInfo user = new UserInfo();

      user.setName("User" + i);
      session.save(user);
    }
    session.getTransaction().commit();
    session.close();

    UserInfo user = new UserInfo();
    session = sessionFactory.openSession();
    session.beginTransaction();
    // Retreive
    user = (UserInfo) session.get(UserInfo.class, 6);
    // Update
    user.setName("Updated User Name");
    session.update(user);

    // Delete
    user = (UserInfo) session.get(UserInfo.class, 5);
    session.delete(user);
    session.getTransaction().commit();
    session.close();

    //		System.out.println("User Object retrieved is: " + user);

  }
Пример #2
0
  public void testInsert() throws HibernateException, SQLException {
    if (isUsingIdentity()) {
      reportSkip("hand sql expecting non-identity id gen", "Custom SQL");
      return;
    }

    Role p = new Role();

    p.setName("Patient");

    Session s = openSession();

    s.save(p);
    s.flush();

    s.connection().commit();
    s.close();

    getSessions().evict(Role.class);
    s = openSession();

    Role p2 = (Role) s.get(Role.class, new Long(p.getId()));
    assertNotSame(p, p2);
    assertEquals(p2.getId(), p.getId());
    assertTrue(p2.getName().equalsIgnoreCase(p.getName()));
    s.delete(p2);
    s.flush();

    s.connection().commit();
    s.close();
  }
Пример #3
0
 @Override
 public void addToFavorites(List<Favorite> favorites, Poem poem) {
   Session session = sessionFactory.openSession();
   Transaction tx = session.beginTransaction();
   Poem p = (Poem) session.get(Poem.class, poem.getPid());
   Set<Favorite> set = new HashSet<Favorite>(favorites);
   p.setFavoriteLists(set);
   session.update(p);
   tx.commit();
   session.close();
 }
Пример #4
0
  public void testCRUD() throws HibernateException, SQLException {
    if (isUsingIdentity()) {
      reportSkip("hand sql expecting non-identity id gen", "Custom SQL");
      return;
    }

    Person p = new Person();

    p.setName("Max");
    p.setLastName("Andersen");
    p.setNationalID("110974XYZ�");
    p.setAddress("P. P. Street 8");

    Session s = openSession();

    s.save(p);
    s.flush();

    s.connection().commit();
    s.close();

    getSessions().evict(Person.class);
    s = openSession();

    Person p2 = (Person) s.get(Person.class, p.getId());
    assertNotSame(p, p2);
    assertEquals(p2.getId(), p.getId());
    assertEquals(p2.getLastName(), p.getLastName());
    s.flush();

    List list = s.createQuery("select p from Party as p").list();
    assertTrue(list.size() == 1);

    s.connection().commit();
    s.close();

    s = openSession();

    list = s.createQuery("select p from Person as p where p.address = 'L�rkev�nget 1'").list();
    assertTrue(list.size() == 0);
    p.setAddress("L�rkev�nget 1");
    s.update(p);
    list = s.createQuery("select p from Person as p where p.address = 'L�rkev�nget 1'").list();
    assertTrue(list.size() == 1);
    list = s.createQuery("select p from Party as p where p.address = 'P. P. Street 8'").list();
    assertTrue(list.size() == 0);

    s.delete(p);
    list = s.createQuery("select p from Person as p").list();
    assertTrue(list.size() == 0);

    s.connection().commit();
    s.close();
  }
  public void testPojoRetreival() {
    Session session = openSession();
    Transaction txn = session.beginTransaction();

    prepareTestData(session);

    Stock stock = (Stock) session.get(Stock.class, new Long(1));
    assertEquals("Something wrong!", new Long(1), stock.getId());

    txn.rollback();
    session.close();
  }
 @Override
 public Response loadData(Class valueObjectClass) {
   Session s = HibernateUtil.getSessionFactory().openSession();
   Siniestro sin = (Siniestro) s.get(Siniestro.class, ((Siniestro) beanVO).getId());
   Hibernate.initialize(sin.getDetalleSiniestro());
   Hibernate.initialize(sin.getObservaciones());
   Hibernate.initialize(sin.getDocumentos());
   Hibernate.initialize(sin.getNotasTecnicas());
   s.close();
   beanVO = sin;
   return new VOResponse(beanVO);
 }
Пример #7
0
 @Override
 public Poem findById(Poem poem) {
   Session session = sessionFactory.openSession();
   poem = (Poem) session.get(Poem.class, poem.getPid());
   if (poem != null) {
     Hibernate.initialize(poem.getAuthor());
     Hibernate.initialize(poem.getFavoriteLists());
     Hibernate.initialize(poem.getNewLists());
     session.close();
     return poem;
   } else {
     return null;
   }
 }
 @Test
 @Transactional
 public void testSaveAndGet() throws Exception {
   Session session = sessionFactory.getCurrentSession();
   Order order = new Order();
   order.getItems().add(new Item());
   session.save(order);
   session.flush();
   // Otherwise the query returns the existing order (and we didn't set the
   // parent in the item)...
   session.clear();
   Order other = (Order) session.get(Order.class, order.getId());
   assertEquals(1, other.getItems().size());
   assertEquals(other, other.getItems().iterator().next().getOrder());
 }
  @Override
  public void actionPerformed(ActionEvent e) {
    VOListTableModel model =
        ((VOListTableModel) gridFrame.getGridControl().getTable().getGrid().getModel());

    if (e.getSource() instanceof CheckBoxControl) {
      for (int i = 0; i < model.getRowCount(); i++) {
        model.setField(i, "selected", ((CheckBoxControl) e.getSource()).isSelected());
      }
      gridFrame.getGridControl().repaint();
    } else {
      Session s = null;
      try {
        s = HibernateUtil.getSessionFactory().openSession();
        s.beginTransaction();
        EtapaSiniestro es =
            (EtapaSiniestro)
                s.createQuery("FROM " + EtapaSiniestro.class.getName() + " C WHERE " + "idPropio=?")
                    .setString(0, "ORD_PAG")
                    .uniqueResult();
        OrdenDePago p = (OrdenDePago) s.get(OrdenDePago.class, ordenDePago.getId());

        List lista = model.getChangedRows();
        if (lista == null || lista.isEmpty()) {
          lista = getSubList(model.getDataVector());
        }
        s.createQuery(
                "UPDATE "
                    + DetalleSiniestro.class.getName()
                    + " D SET D.etapaSiniestro=:es, D.ordenDePago=:ord WHERE D in(:ds)")
            .setEntity("es", es)
            .setEntity("ord", p)
            .setParameterList("ds", lista)
            .executeUpdate();

        s.getTransaction().commit();
        gridFrame.dispose();

      } catch (Exception ex) {
        LoggerUtil.error(this.getClass(), "actionPerformed", ex);
      } finally {
        s.close();
        controller.getVista().getMainPanel().getReloadButton().doClick();
      }
    }
  }
Пример #10
0
 public static <T> int delete(Session session, Class<T> cls, int id) {
   try {
     session.delete(session.get(cls, id));
     return 1;
   } catch (HibernateException e) {
     LOGGER.error(
         "Delete Exception. Record not found by id="
             + id
             + " for class "
             + cls
             + " on session "
             + session
             + ". Method delete return 0.",
         e);
     return 0;
   }
 }
Пример #11
0
  public TempBanner getTempBannerById(Integer tempDataId) {
    System.out.println("TempDataDaoImpl.getTempBannerById()");
    System.out.println("tempDataId = " + tempDataId); // / XXX remove me

    Session session = null;
    TempBanner data = null;

    try {
      session = HibernateUtil.getSessionFactory().openSession();
      data = (TempBanner) session.get(TempBanner.class, tempDataId);
    } finally {
      if (session != null && session.isOpen()) {
        session.flush();
        session.close();
      }
    }

    return data;
  }
Пример #12
0
  public int checkLogin(String insName, String user, String pwd) throws CentralStockDAOException {
    try {
      org.hibernate.classic.Session session = sessionFactory.getCurrentSession();

      Login existingUser = (Login) session.get(Login.class, insName);

      if (insName.equals("Centeral Admin")
          && user.equals(existingUser.getUserId())
          && pwd.equals(existingUser.getUserPw())) {
        return 1;
      } else if (insName.equals(existingUser.getInsName())
          && user.equals(existingUser.getUserId())
          && pwd.equals(existingUser.getUserPw())) {
        return 2;
      } else {
        return 0;
      }
    } catch (HibernateException he) {
      throw new CentralStockDAOException(he + "");
    } catch (Exception sl) {
      throw new CentralStockDAOException(sl + "");
    }
  }
 // GET A SINGLE RECORD FROM tblempbank USING empbankId
 public EmployeeBank getEmployeeBankId(int empbankId)
     throws HibernateException, ConstraintViolationException {
   Session session = SessionFactoryUtil.getSessionFactory().openSession();
   try {
     session.beginTransaction();
     EmployeeBank employeebank = (EmployeeBank) session.get(EmployeeBank.class, empbankId);
     if (employeebank != null) {
       if (!employeebank.getDeleteFlag()) {
         return employeebank;
       } else {
         return null;
       }
     } else {
       return null;
     }
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   } finally {
     session.getTransaction().commit();
     session.close();
   }
 }
Пример #14
0
  public int passwordChange(String insName, String oldpw, String newpw)
      throws CentralStockDAOException {
    try {
      org.hibernate.classic.Session session = sessionFactory.getCurrentSession();

      Login existingUser = (Login) session.get(Login.class, insName);

      if (insName.equals(existingUser.getInsName()) && oldpw.equals(existingUser.getUserPw())) {

        String hql =
            "UPDATE Login i set i.userPw = '" + newpw + "'WHERE i.insName = '" + insName + "'";

        session.createQuery(hql).executeUpdate();

        return 1;
      } else {
        return 0;
      }
    } catch (HibernateException he) {
      throw new CentralStockDAOException(he + "");
    } catch (Exception sl) {
      throw new CentralStockDAOException(sl + "");
    }
  }
Пример #15
0
  public void testJoinedSubclass() throws HibernateException, SQLException {
    Medication m = new Medication();

    m.setPrescribedDrug(new Drug());

    m.getPrescribedDrug().setName("Morphine");

    Session s = openSession();

    s.save(m.getPrescribedDrug());
    s.save(m);

    s.flush();
    s.connection().commit();
    s.close();
    s = openSession();

    Medication m2 = (Medication) s.get(Medication.class, m.getId());
    assertNotSame(m, m2);

    s.flush();
    s.connection().commit();
    s.close();
  }
Пример #16
0
  public void testCollectionCUD() throws HibernateException, SQLException {
    if (isUsingIdentity()) {
      reportSkip("hand sql expecting non-identity id gen", "Custom SQL");
      return;
    }

    Role role = new Role();

    role.setName("Jim Flanders");

    Intervention iv = new Medication();
    iv.setDescription("JF medical intervention");

    role.getInterventions().add(iv);

    List sx = new ArrayList();
    sx.add("somewhere");
    sx.add("somehow");
    sx.add("whatever");
    role.setBunchOfStrings(sx);

    Session s = openSession();

    s.save(role);
    s.flush();
    s.connection().commit();
    s.close();

    s = openSession();

    Role r = (Role) s.get(Role.class, new Long(role.getId()));
    assertNotSame(role, r);

    assertEquals(1, r.getInterventions().size());

    assertEquals(3, r.getBunchOfStrings().size());

    r.getBunchOfStrings().set(1, "replacement");
    s.flush();
    s.connection().commit();
    s.close();

    s = openSession();

    r = (Role) s.get(Role.class, new Long(role.getId()));
    assertNotSame(role, r);

    assertEquals(r.getBunchOfStrings().get(1), "replacement");
    assertEquals(3, r.getBunchOfStrings().size());

    r.getBunchOfStrings().set(1, "replacement");

    r.getBunchOfStrings().remove(1);
    s.flush();

    r.getBunchOfStrings().clear();
    s.flush();

    s.connection().commit();
    s.close();
  }