public void testBroken() throws Exception { if (getDialect() instanceof Oracle9Dialect) return; Session s = openSession(); Transaction t = s.beginTransaction(); Broken b = new Fixed(); b.setId(new Long(123)); b.setOtherId("foobar"); s.save(b); s.flush(); b.setTimestamp(new Date()); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); s.update(b); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); b = (Broken) s.load(Broken.class, b); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); s.delete(b); t.commit(); s.close(); }
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(); }
public void testSqlFunctionAsAlias() throws Exception { String functionName = locateAppropriateDialectFunctionNameForAliasTest(); if (functionName == null) { log.info("Dialect does not list any no-arg functions"); return; } log.info("Using function named [" + functionName + "] for 'function as alias' test"); String query = "select " + functionName + " from Simple as " + functionName + " where " + functionName + ".id = 10"; Session s = openSession(); Transaction t = s.beginTransaction(); Simple simple = new Simple(); simple.setName("Simple 1"); s.save(simple, new Long(10)); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); List result = s.find(query); assertTrue(result.size() == 1); assertTrue(result.get(0) instanceof Simple); s.delete(result.get(0)); t.commit(); s.close(); }
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); }
public void testCachedQuery() throws Exception { Session s = openSession(); Transaction t = s.beginTransaction(); Simple simple = new Simple(); simple.setName("Simple 1"); s.save(simple, new Long(10)); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); Query q = s.createQuery("from Simple s where s.name=?"); q.setCacheable(true); q.setString(0, "Simple 1"); assertTrue(q.list().size() == 1); assertTrue(q.list().size() == 1); assertTrue(q.list().size() == 1); q = s.createQuery("from Simple s where s.name=:name"); q.setCacheable(true); q.setString("name", "Simple 1"); assertTrue(q.list().size() == 1); simple = (Simple) q.list().get(0); q.setString("name", "Simple 2"); assertTrue(q.list().size() == 0); assertTrue(q.list().size() == 0); simple.setName("Simple 2"); assertTrue(q.list().size() == 1); assertTrue(q.list().size() == 1); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); q = s.createQuery("from Simple s where s.name=:name"); q.setString("name", "Simple 2"); q.setCacheable(true); assertTrue(q.list().size() == 1); assertTrue(q.list().size() == 1); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); s.update(simple, new Long(10)); s.delete(simple); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); q = s.createQuery("from Simple s where s.name=?"); q.setCacheable(true); q.setString(0, "Simple 1"); assertTrue(q.list().size() == 0); assertTrue(q.list().size() == 0); t.commit(); s.close(); }
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(); }
/** * @param nameSMD : le Nom de SMD qui a envoyer la requete * @param newVersion : la nouvelle versions (le cas de MAJ) * @return "SMD Not Found" : si le SMD n'existe pas "Version Updated" : sinon */ @POST @Path("setVersion") public String setVersion( @FormParam("nameSMD") String nameSMD, @FormParam("newVersion") String newVersion) { OperationInformationResources.logger.log( Level.INFO, "Version with (SMD = " + nameSMD + ", newVersion = " + newVersion + ")"); Session connect = HibernateUtil.getSessionFactory().openSession(); SiteSMD smd = SiteSMD.findByName(connect, nameSMD); String result = "SMD Not Found"; if (smd != null) { String lst[] = newVersion.split("-"); if (lst.length == 2) { smd.setVersion_code(lst[0]); smd.setVersion_system(lst[1]); connect.beginTransaction(); connect.saveOrUpdate(smd); connect.getTransaction().commit(); result = "Version Updated"; } else { result = "Version Envoyer Incorrect"; } } connect.close(); OperationInformationResources.logger.log(Level.FINEST, "Returned Value " + result); return result; }
public void testInterceptorWithNewSessionAndFlushNever() throws HibernateException { MockControl sfControl = MockControl.createControl(SessionFactory.class); SessionFactory sf = (SessionFactory) sfControl.getMock(); MockControl sessionControl = MockControl.createControl(Session.class); Session session = (Session) sessionControl.getMock(); sf.openSession(); sfControl.setReturnValue(session, 1); session.getSessionFactory(); sessionControl.setReturnValue(sf); session.setFlushMode(FlushMode.MANUAL); sessionControl.setVoidCallable(1); session.close(); sessionControl.setReturnValue(null, 1); sfControl.replay(); sessionControl.replay(); HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setFlushModeName("FLUSH_NEVER"); interceptor.setSessionFactory(sf); try { interceptor.invoke(new TestInvocation(sf)); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } sfControl.verify(); sessionControl.verify(); }
public void testInterceptorWithThreadBoundEmptyHolder() { MockControl sfControl = MockControl.createControl(SessionFactory.class); SessionFactory sf = (SessionFactory) sfControl.getMock(); MockControl sessionControl = MockControl.createControl(Session.class); Session session = (Session) sessionControl.getMock(); sf.openSession(); sfControl.setReturnValue(session, 1); session.getSessionFactory(); sessionControl.setReturnValue(sf, 1); session.flush(); sessionControl.setVoidCallable(1); session.close(); sessionControl.setReturnValue(null, 1); sfControl.replay(); sessionControl.replay(); SessionHolder holder = new SessionHolder("key", session); holder.removeSession("key"); TransactionSynchronizationManager.bindResource(sf, holder); HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setSessionFactory(sf); try { interceptor.invoke(new TestInvocation(sf)); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } sfControl.verify(); sessionControl.verify(); }
public void testInterceptorWithFlushFailure() throws Throwable { MockControl sfControl = MockControl.createControl(SessionFactory.class); SessionFactory sf = (SessionFactory) sfControl.getMock(); MockControl sessionControl = MockControl.createControl(Session.class); Session session = (Session) sessionControl.getMock(); sf.openSession(); sfControl.setReturnValue(session, 1); session.getSessionFactory(); sessionControl.setReturnValue(sf, 1); SQLException sqlEx = new SQLException("argh", "27"); session.flush(); ConstraintViolationException jdbcEx = new ConstraintViolationException("", sqlEx, null); sessionControl.setThrowable(jdbcEx, 1); session.close(); sessionControl.setReturnValue(null, 1); sfControl.replay(); sessionControl.replay(); HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setSessionFactory(sf); try { interceptor.invoke(new TestInvocation(sf)); fail("Should have thrown DataIntegrityViolationException"); } catch (DataIntegrityViolationException ex) { // expected assertEquals(jdbcEx, ex.getCause()); } sfControl.verify(); sessionControl.verify(); }
private void deleteData() throws Exception { Session s = openSession(); Transaction t = s.beginTransaction(); s.delete("from Componentizable"); t.commit(); s.close(); }
@Override public Response deleteRecords(ArrayList persistentObjects) throws Exception { Session s = null; try { boolean allOk = true; s = HibernateUtil.getSessionFactory().openSession(); Transaction t = s.beginTransaction(); for (Object o : persistentObjects) { s.delete(o); } try { t.commit(); } catch (Exception ex) { LoggerUtil.error(this.getClass(), "deleteRecords", ex); t.rollback(); allOk = false; } if (allOk) { return new VOResponse(true); } else { return new ErrorResponse("delete.constraint.violation"); } } finally { s.close(); } }
public void testInterceptorWithEntityInterceptor() throws HibernateException { MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class); org.hibernate.Interceptor entityInterceptor = (org.hibernate.Interceptor) interceptorControl.getMock(); interceptorControl.replay(); MockControl sfControl = MockControl.createControl(SessionFactory.class); SessionFactory sf = (SessionFactory) sfControl.getMock(); MockControl sessionControl = MockControl.createControl(Session.class); Session session = (Session) sessionControl.getMock(); sf.openSession(entityInterceptor); sfControl.setReturnValue(session, 1); session.getSessionFactory(); sessionControl.setReturnValue(sf, 1); session.flush(); sessionControl.setVoidCallable(1); session.close(); sessionControl.setReturnValue(null, 1); sfControl.replay(); sessionControl.replay(); HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setSessionFactory(sf); interceptor.setEntityInterceptor(entityInterceptor); try { interceptor.invoke(new TestInvocation(sf)); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } interceptorControl.verify(); sfControl.verify(); sessionControl.verify(); }
/** * @param nameSMD : le Nom de SMD a mettre à jour * @return "SMD Not Found" : si le SMD n'existe pas "Connected OK" : sinon */ @POST @Path("setConnected") public String setConnected( @FormParam("nameSMD") String nameSMD, @FormParam("what") boolean what) { OperationInformationResources.logger.log( Level.INFO, "Connect with (SMD = " + nameSMD + ", what = " + what + " )"); Session connect = HibernateUtil.getSessionFactory().openSession(); SiteSMD smd = SiteSMD.findByName(connect, nameSMD); String result = "SMD Not Found"; if (smd != null) { smd.setConnected(what); connect.beginTransaction(); connect.saveOrUpdate(smd); connect.getTransaction().commit(); result = "Connected OK"; } connect.close(); OperationInformationResources.logger.log(Level.FINEST, "Returned Value " + result); return result; }
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; }
@SuppressWarnings("unchecked") public List<Token> findTokens( Token search, int first, int pageSize, String sortField, SortOrder sortOrder) throws DAOException { List<Token> results = null; Session session = null; try { session = getSession(); Criteria criteria = criteria(session, search); criteria.setFirstResult(first); criteria.setMaxResults(pageSize); if (sortField == null) { sortField = "tokenId"; } Order ord = (sortOrder == null || sortOrder.equals(SortOrder.UNSORTED) || sortOrder.equals(SortOrder.ASCENDING)) ? Order.asc(sortField) : Order.desc(sortField); criteria.addOrder(ord); results = criteria.list(); } catch (Exception e) { throw new DAOException(e); } finally { if (session != null) { session.close(); } } return results; }
@Override public Response updateRecords( int[] rowNumbers, ArrayList oldPersistentObjects, ArrayList persistentObjects) throws Exception { Response r = super.updateRecords(rowNumbers, oldPersistentObjects, persistentObjects); for (Object e : persistentObjects) { DireccionPersona d = (DireccionPersona) e; if (d.getTipoDireccion().getNombre().toLowerCase().contains("fiscal")) { Session s = null; try { s = HibernateUtil.getSessionFactory().openSession(); Transaction tr = s.beginTransaction(); Persona p = (Persona) beanVO; p.setDireccionFiscal(d); s.update(beanVO); tr.commit(); } catch (Exception ex) { ex.printStackTrace(); } finally { s.close(); } break; } } return r; }
public void testDom4jRetreival() { Session session = openSession(); Transaction txn = session.beginTransaction(); org.hibernate.Session dom4j = session.getSession(EntityMode.DOM4J); prepareTestData(session); Object rtn = dom4j.get(Stock.class.getName(), stockId); Element element = (Element) rtn; assertEquals("Something wrong!", stockId, Long.valueOf(element.attributeValue("id"))); System.out.println("**** XML: ****************************************************"); prettyPrint(element); System.out.println("**************************************************************"); Element currVal = element.element("currentValuation"); System.out.println("**** XML: ****************************************************"); prettyPrint(currVal); System.out.println("**************************************************************"); txn.rollback(); session.close(); }
public void testDom4jSave() { Session pojos = openSession(); Transaction txn = pojos.beginTransaction(); prepareTestData(pojos); org.hibernate.Session dom4j = pojos.getSession(EntityMode.DOM4J); Element stock = DocumentFactory.getInstance().createElement("stock"); stock.addElement("tradeSymbol").setText("IBM"); Element val = stock.addElement("currentValuation").addElement("valuation"); val.appendContent(stock); val.addElement("valuationDate").setText(new java.util.Date().toString()); val.addElement("value").setText("121.00"); dom4j.save(Stock.class.getName(), stock); dom4j.flush(); txn.rollback(); pojos.close(); assertTrue(!pojos.isOpen()); assertTrue(!dom4j.isOpen()); prettyPrint(stock); }
@POST @Path("progress") public String setProgress( @FormParam("idOperation") long idOperation, @FormParam("progressStatus") double progressStatus) { OperationInformationResources.logger.log( Level.INFO, "Progress with (id = " + idOperation + ", etat = " + progressStatus + ")"); String result = "Operation With id= '" + idOperation + "' does not exist"; Session connect = HibernateUtil.getSessionFactory().openSession(); if (progressStatus < 0) { result = progressStatus + "is invalid (must be between 0..100)"; } else { OperationAbstract getOperation = OperationAbstract.findById(connect, idOperation); if (getOperation != null) { getOperation.setState(progressStatus); connect.beginTransaction(); connect.saveOrUpdate(getOperation); connect.getTransaction().commit(); result = "Status is updated"; } } connect.close(); OperationInformationResources.logger.log(Level.FINEST, "Returned Value " + result); return result; }
public static void adicionarHorario(Horario horario) { session = (Session) PreparaSessao.pegarSessao(); session.save(horario); session.beginTransaction().commit(); session.close(); }
@Override public Response insertRecords(int[] rowNumbers, ArrayList newValueObjects) throws Exception { Session s = null; if (getSet() != null) { ValueObject o = (ValueObject) newValueObjects.get(0); try { s = HibernateUtil.getSessionFactory().openSession(); Transaction t = s.beginTransaction(); AuditoriaBasica ab = new AuditoriaBasica(new Date(), General.usuario.getUserName(), true); if (o instanceof Auditable) { ((Auditable) o).setAuditoria(ab); } // getSet().add(o); ((Diagnostico) o).setEspecialidad((Especialidad) super.beanVO); // s.update(super.beanVO); s.save(o); selectedCell(0, 0, null, o); t.commit(); return new VOListResponse(newValueObjects, false, newValueObjects.size()); } catch (Exception ex) { getSet().remove(o); return new ErrorResponse( LoggerUtil.isInvalidStateException(this.getClass(), "insertRecords", ex)); } finally { s.close(); } } else { return new ErrorResponse("Primero tienes que guardar el Registro Principal"); } }
private void delete() { Session s = null; try { s = HibernateUtil.getSessionFactory().openSession(); Transaction t = s.beginTransaction(); s.createQuery("UPDATE " + Usuario.class.getName() + " SET rol = NULL").executeUpdate(); System.out.println("----Roles desligados---"); System.out.println(s.createQuery("DELETE FROM " + Rol.class.getName()).executeUpdate()); System.out.println("----Roles Eliminados---"); System.out.println(s.createQuery("DELETE FROM " + MenuByRol.class.getName()).executeUpdate()); System.out.println("----MenuByRols Eliminados---"); List<Item> lista = (List<Item>) s.createQuery("FROM " + Item.class.getName()).list(); borrarItems(s, lista); t.commit(); } catch (Exception e) { e.printStackTrace(); } finally { s.close(); } }
public void testSetProperties() throws Exception { Session s = openSession(); Transaction t = s.beginTransaction(); Simple simple = new Simple(); simple.setName("Simple 1"); s.save(simple, new Long(10)); Query q = s.createQuery("from Simple s where s.name=:name and s.count=:count"); q.setProperties(simple); assertTrue(q.list().get(0) == simple); // misuse of "Single" as a propertyobject, but it was the first testclass i found with a // collection ;) Single single = new Single() { // trivial hack to test properties with arrays. String[] getStuff() { return (String[]) getSeveral().toArray(new String[getSeveral().size()]); } }; List l = new ArrayList(); l.add("Simple 1"); l.add("Slimeball"); single.setSeveral(l); q = s.createQuery("from Simple s where s.name in (:several)"); q.setProperties(single); assertTrue(q.list().get(0) == simple); q = s.createQuery("from Simple s where s.name in (:stuff)"); q.setProperties(single); assertTrue(q.list().get(0) == simple); s.delete(simple); t.commit(); s.close(); }
// Ensure close is called on the stateful session correctly. @Test public void testStatefulClose() { SessionFactory sessionFactory = createMock(SessionFactory.class); Session session = createMock(Session.class); Query scrollableResults = createNiceMock(Query.class); HibernateCursorItemReader<Foo> itemReader = new HibernateCursorItemReader<Foo>(); itemReader.setSessionFactory(sessionFactory); itemReader.setQueryString("testQuery"); itemReader.setUseStatelessSession(false); expect(sessionFactory.openSession()).andReturn(session); expect(session.createQuery("testQuery")).andReturn(scrollableResults); expect(scrollableResults.setFetchSize(0)).andReturn(scrollableResults); expect(session.close()).andReturn(null); replay(sessionFactory); replay(session); replay(scrollableResults); itemReader.open(new ExecutionContext()); itemReader.close(); verify(sessionFactory); verify(session); }
private void close() throws Exception { try { t.commit(); } catch (Exception e) { throw e; } finally { s.close(); } }
public Integer save(final Token token) throws DAOException { Session session = null; Transaction tr = null; final Integer[] r = {null}; try { session = getSession(); tr = session.beginTransaction(); final String sql = queryCache.getQuery("save_token.sql"); Work work = new Work() { @Override public void execute(Connection c) throws SQLException { PreparedStatement st = c.prepareStatement(sql); int ix = 1; { Integer id = token.getTokenId(); if (id == null) { st.setNull(ix++, Types.INTEGER); } else { st.setInt(ix++, id); } } { String value = token.getValue(); if (value == null) { st.setNull(ix++, Types.VARCHAR); } else { st.setString(ix++, value); } } st.executeUpdate(); ResultSet rs = st.getGeneratedKeys(); if (rs.next()) { r[0] = rs.getInt(1); } } }; session.doWork(work); tr.commit(); return r[0]; } catch (Exception e) { if (tr != null) { tr.rollback(); } throw new DAOException(e); } finally { if (session != null) { session.close(); } } }
// Método duplicado na classe MonitorDAO ver qual é o verdadeiro public static void adicionarMonitorAoHorario(long idHorario, Monitor monitor) { session = (Session) PreparaSessao.pegarSessao(); session.beginTransaction(); Horario horario = new Horario(); session.load(horario, idHorario); horario.setMonitor(monitor); session.save(horario); session.getTransaction().commit(); session.close(); }
@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(); }
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(); }