public List<PlannedNotification> getPlannedNotificationsForCorrespondence() { List<PlannedNotification> result; SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory"); Session session = sessionFactory.openSession(sessionFactory.getCurrentSession().connection()); session.setFlushMode(FlushMode.MANUAL); result = new ArrayList<PlannedNotification>(); try { Query query = session .createQuery( "from PlannedNotification p left join fetch p.userBasedRecipientInternal where p.eventName = :var") .setString( "var", NotificationEventTypeEnum.CORRESPONDENCE_CREATED_OR_UPDATED_EVENT.toString()); result = query.list().subList(0, 1); } catch (DataAccessResourceFailureException e) { log.error(e.getMessage()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (HibernateException e) { log.error(e.getMessage()); } catch (Exception e) { log.error(e.getMessage()); } finally { session.close(); } return result; }
protected long getRowCountFromDataBase() { long rowCount = 0; SessionFactory factory = FLRSessionFactory.getFactory(); Session session = null; try { session = factory.openSession(); session = setFilter(session); String queryString = "SELECT COUNT(*) FROM FLRLohnartstundenfaktor AS lohnartstundenfaktor" + buildWhereClause(); Query query = session.createQuery(queryString); List<?> rowCountResult = query.list(); if (rowCountResult != null && rowCountResult.size() > 0) { rowCount = ((Long) rowCountResult.get(0)).longValue(); } } catch (Exception e) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e); } finally { if (session != null) { try { session.close(); } catch (HibernateException he) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER, he); } } } return rowCount; }
public void insertTarjetaHistorico(PsTarjeta tarjeta, String xml) { try { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session newSession = sessionFactory.openSession(); newSession.beginTransaction(); ArmResponsePsTarjeta j = new ArmResponsePsTarjeta(); j.setIdTarjetaArm(tarjeta.getIDTarjetaARM()); j.setIdTarjetaFrida(tarjeta.getIDTarjetaFrida()); j.setNombreTarjeta(tarjeta.getNombreTarjeta()); j.setMeesageId(tarjeta.getMeesageID()); j.setXmlMessage(xml); j.setFechaMensaje(new Date()); newSession.persist(j); newSession.getTransaction().commit(); newSession.close(); } catch (HibernateException e) { } finally { } }
/** * Create a single <code>Patient</code> record. The generated id will be available in the * patientRecord. * * @param patientRecord * @return boolean */ public boolean create(Patient patientRecord) { log.debug("PatientDAO.create() - Begin"); Session session = null; Transaction tx = null; boolean result = true; if (patientRecord != null) { try { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.openSession(); tx = session.beginTransaction(); log.info("Inserting Record..."); session.persist(patientRecord); log.info("Patient Inserted seccussfully..."); tx.commit(); } catch (Exception e) { result = false; if (tx != null) { tx.rollback(); } log.error("Exception during insertion caused by :" + e.getMessage(), e); } finally { // Actual Patient insertion will happen at this step if (session != null) { session.close(); } } } log.debug("PatientDAO.create() - End"); return result; }
/** * Gets Hibernate session. * * @param tx Cache transaction. * @return Session. */ Session session(@Nullable GridCacheTx tx) { Session ses; if (tx != null) { ses = tx.meta(ATTR_SES); if (ses == null) { ses = sesFactory.openSession(); ses.beginTransaction(); // Store session in transaction metadata, so it can be accessed // for other operations on the same transaction. tx.addMeta(ATTR_SES, ses); if (log.isDebugEnabled()) log.debug("Hibernate session open [ses=" + ses + ", tx=" + tx.xid() + "]"); } } else { ses = sesFactory.openSession(); ses.beginTransaction(); } return ses; }
@BeforeClass public void beforeClass() { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); publicMessageDao = new PublicMessageHibernateDao(sessionFactory); session = sessionFactory.getCurrentSession(); session.beginTransaction(); }
@Override public void removeRequest(Requests request) { if (null != request) { org.hibernate.Session sess = sessionFactory.getCurrentSession(); request = (Requests) sess.get(Requests.class, request.getId()); List<Contacts> contTemp = request.getContacts(); List<Products> prodTemp = request.getProducts(); if (contTemp != null && contTemp.size() != 0) { sess.enableFetchProfile("requests-with-products"); contTemp = contactsDAO.getFromProxy(contTemp); for (Contacts contact : contTemp) { contact.getConnectedRequests().remove(request); sess.update(contact); } } if (prodTemp != null && prodTemp.size() != 0) { sess.enableFetchProfile("requests-with-products"); prodTemp = productsDAO.getFromProxy(prodTemp); for (Products product : prodTemp) { product.getRequestsForProduct().remove(request); sess.update(product); } } sess.update(request); sessionFactory.getCurrentSession().delete(request); } }
@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(); } }
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); }
public List<DeviceList> getDeviceList(String location) { SessionFactory sessionFactory = HibernateSessionFactory.getSessionFactory(); List<DeviceList> results = new ArrayList<DeviceList>(); Session session = sessionFactory.openSession(); if (session != null) { SQLQuery query = session.createSQLQuery( "select d.*,da.*,du.* " + "from device_app.device d, device_app.device_availability da, device_app.device_user du " + "where d.id=da.device_id and " + "da.checked_out_user = du.email_id and " + "d.device_status='active' and " + "du.user_location=:location"); query.addEntity(Device.class); query.addEntity(DeviceAvailability.class); query.addEntity(DeviceUser.class); query.setString("location", location); List<Object[]> resultList = query.list(); if (resultList != null && resultList.size() > 0) { System.out.println("results size is " + resultList.size()); for (Object[] array : resultList) { DeviceList row = new DeviceList(); for (Object resultObject : array) { System.out.println(resultObject.getClass()); if (resultObject instanceof Device) { Device device = (Device) resultObject; row.setBarCodeIdentifier(device.getBarCodeId()); row.setDeviceCapacity(device.getDeviceCapacity()); row.setDeviceName(device.getDeviceName()); row.setDeviceNickname(device.getDeviceNickName()); row.setDeviceOs(device.getDeviceOs()); row.setDeviceOsVersion(device.getDeviceOsVersion()); row.setDeviceSerialNumber(device.getDeviceSerialNumber()); row.setDeviceStatus(device.getDeviceStatus()); row.setDeviceType(device.getDeviceType()); row.setId(device.getId()); row.setOwnedBy(device.getDeviceOwner()); } else if (resultObject instanceof DeviceAvailability) { DeviceAvailability availability = (DeviceAvailability) resultObject; // // row.setCheckedOutAt(DateUtils.truncate(availability.getModifiedDate(),Calendar.MINUTE).toString()); row.setCheckedOutAt( DateFormatUtils.format(availability.getModifiedDate(), "yyyy-MM-dd HH:mm:ss")); row.setCurrentlyCheckedOutById(availability.getDeviceUser().getEmailId()); row.setIsCheckedOut(availability.isIsCheckedOut()); row.setLocation(location); } else { DeviceUser user = (DeviceUser) resultObject; } } results.add(row); } } } return results; }
@Before public void setUp() throws Exception { logger.info("初始化Hibernate环境...."); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); session = sessionFactory.openSession(); session.beginTransaction(); }
public static void main(String[] args) { Session session = null; try { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); session = sessionFactory.openSession(); Contact contact; String SQL_QUERY = "select c.id, c.firstName from Contact c where c.id >= 3"; Query query = session.createQuery(SQL_QUERY); Iterator it = query.iterate(); while (it.hasNext()) { Object[] row = (Object[]) it.next(); System.out.println("------------------------------------------------------"); System.out.println("ID : " + row[0]); System.out.println("First Name : " + row[1]); } System.out.println("Done"); } catch (Exception e) { // tx.rollback(); System.out.println(e.getMessage()); } finally { // session.flush(); session.close(); } }
/* * loadStartandEndDates()-->this function is used for load the start and end date */ private void loadStartandEndDates() { try { SessionFactory sf = serviceAttendanceProcess.getConnection(); Session session = sf.openSession(); session.beginTransaction(); session.doWork( new Work() { @Override public void execute(Connection connection) throws SQLException { // TODO Auto-generated method stub statement = connection.prepareCall("{ call PROC_DATE_CALC (?,?,?) }"); statement.setLong(1, payPeriodId); statement.registerOutParameter(2, Types.VARCHAR); statement.registerOutParameter(3, Types.VARCHAR); statement.execute(); startDate = statement.getString(2); endDate = statement.getString(3); connection.close(); } }); tfProcessPeriod.setReadOnly(false); tfProcessPeriod.setValue(" " + startDate + " to " + endDate); tfProcessPeriod.setReadOnly(true); } catch (Exception e) { logger.info("Load Start and end Date Using Procedure" + e); } finally { try { statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.info("Load Start and end Date Using Procedure" + e); } } }
@Test public void test() { Configuration cfg = new Configuration(); cfg.addAnnotatedClass(Employee.class); cfg.configure("hbm2ddl.xml"); new SchemaExport(cfg).create(true, true); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.getCurrentSession(); session.beginTransaction(); { Employee emp = new Employee(); emp.setEmpName("seungbeomi"); emp.setEmpPassword("password"); emp.setEmpEmailAddress("*****@*****.**"); emp.setPermanent(true); emp.setEmpJoinDate(new GregorianCalendar(2012, 9, 30)); emp.setEmpLoginTime(new Date()); session.save(emp); } session.getTransaction().commit(); }
public void AverageRatingByProductName(String prodName) { SessionFactory sf = HibernateUtility.getSessionfactory(); Session session = sf.openSession(); session.beginTransaction(); String sql1 = "SELECT * FROM product where productName = :productName"; SQLQuery query1 = session.createSQLQuery(sql1); query1.setParameter("productName", prodName); query1.addEntity(Product.class); Product product = (Product) query1.uniqueResult(); String sql2 = "SELECT * FROM ratingdetails where productId = :productId"; SQLQuery query2 = session.createSQLQuery(sql2); query2.setParameter("productId", product.getProductId()); query2.addEntity(RatingDetails.class); List ratings = query2.list(); session.getTransaction().commit(); float count = ratings.size(); int sum = 0; for (Object r : ratings) { RatingDetails rate = (RatingDetails) r; sum = sum + rate.getRating(); } float averageRating = (sum / count); System.out.println("pid " + product + " avg " + averageRating); }
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(); } }
public void insert(ValueObject vo) { // TODO Auto-generated method stub Session session = null; List ls = null; try { // This step will read hibernate.cfg.xml and prepare Hibernate for use SessionFactory sessionFactory = new // read cgf file.and create an object. Configuration() .configure() .buildSessionFactory(); session = sessionFactory.openSession(); // for more then transaction. Transaction y = session.beginTransaction(); // Create new instance of Contact and set // values in it by reading them from form object session.save(vo); // insert query y.commit(); } catch (Exception e) { e.printStackTrace(); } finally { session.flush(); session.close(); } }
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(); } }
@Override public void addRequest(Requests request) { sessionFactory.getCurrentSession().save(request); List<Contacts> contTemp = request.getContacts(); List<Products> prodTemp = request.getProducts(); if (contTemp != null && contTemp.size() != 0) { org.hibernate.Session sess = sessionFactory.getCurrentSession(); sess.enableFetchProfile("requests-with-products"); contTemp = contactsDAO.getFromProxy(contTemp); for (Contacts contact : contTemp) { contact.getConnectedRequests().add(request); contactsDAO.changeContact(contact); } } if (prodTemp != null && prodTemp.size() != 0) { org.hibernate.Session sess = sessionFactory.getCurrentSession(); sess.enableFetchProfile("requests-with-products"); prodTemp = productsDAO.getFromProxy(prodTemp); for (Products product : prodTemp) { product.getRequestsForProduct().add(request); productsDAO.changeProduct(product); } } }
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 void addMansion(Mansion m) { Session session = sf.getCurrentSession(); session.beginTransaction(); session.save(m); session.getTransaction().commit(); Session session2 = sf.getCurrentSession(); session2.beginTransaction(); Query query = session2.createQuery("from Mansion"); List<Mansion> mlist = query.list(); for (Mansion onem : mlist) { System.out.println(onem.getA().size()); } Query query2 = session2.createQuery("from Aristocrat"); List<Aristocrat> alist = query2.list(); for (Aristocrat onea : alist) { System.out.println("An aristocrat..."); } session2.close(); }
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(); } }
public RoleView() { SessionFactory sessionFactory = DatabaseUtil.getSessionFactory(); Session openSession = sessionFactory.openSession(); openSession.beginTransaction(); Query query = openSession.createQuery("from Role"); list = query.list(); for (Role acconunt : list) { addComponent(new Label(acconunt.getRoleName())); } openSession.getTransaction().commit(); openSession.flush(); Button button = new Button("roles"); button.addClickListener( new ClickListener() { @Override public void buttonClick(ClickEvent event) { for (Role account : list) { for (Permission role : account.getPermissions()) { System.out.println(role.getPermissionName()); } } } }); addComponent(button); }
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(); } }
protected Session getSession() { Session session = sessionFactory.getCurrentSession(); if (null == session || false == session.isOpen()) { session = sessionFactory.openSession(); } return session; }
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(); } }
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); }
@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(); } }
public static void reservar( Hospede hospede, Apartamento apartamento, Date dt_inicio, Date dt_fim) { Session session = null; Transaction tx = null; try { SessionFactory factory = new Configuration().configure().buildSessionFactory(); session = factory.openSession(); tx = session.beginTransaction(); Reserva reserva = new Reserva(); reserva.setHospede(hospede); reserva.setApartamento(apartamento); reserva.setDataInicio(dt_inicio); reserva.setDataFim(dt_fim); session.save(reserva); /*Depois de salvar a RESERVA tem que mudar a situação do apartamento para não disponível*/ // Apartamento apBd = ApartamentoDAO.buscarApartamento(apartamento.getId()); // apBd.setDisponivel(false); session.update(apartamento); tx.commit(); } catch (Exception e) { if (tx != null) tx.rollback(); System.out.println("Erro: " + e.getMessage()); } finally { session.close(); } }
/** * Gets the planned notifications for the list of sites that are passed in. This method access the * db using a new session from the hibernate session factory. * * @param hcsList the hcs list * @return the planned notifications */ public List<PlannedNotification> getPlannedNotificationsForUpdateMasterSubject() { List<PlannedNotification> result; SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory"); Session session = sessionFactory.openSession(sessionFactory.getCurrentSession().connection()); session.setFlushMode(FlushMode.MANUAL); result = new ArrayList<PlannedNotification>(); try { Query query = session .createQuery("from PlannedNotification p where p.eventName = :var") .setString("var", NotificationEventTypeEnum.MASTER_SUBJECT_UPDATED_EVENT.toString()); result = query.list(); } catch (DataAccessResourceFailureException e) { log.error(e.getMessage()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (HibernateException e) { log.error(e.getMessage()); } catch (Exception e) { log.error(e.getMessage()); } finally { session.close(); } return result; }