List of usage examples for org.hibernate Session getSessionFactory
SessionFactory getSessionFactory();
From source file:ariba.ui.meta.jpa.HibernateContext.java
License:Apache License
public Object getPrimaryKey(Object o) { Session session = getSession(); ClassMetadata classMeta = session.getSessionFactory().getClassMetadata(o.getClass()); return classMeta.getIdentifier(o, EntityMode.POJO); }
From source file:at.molindo.esi4j.module.hibernate.scrolling.DefaultQueryScrollingSession.java
License:Apache License
@Override public List<?> fetch(Session session, int batchSize) { Criteria criteria = session.createCriteria(_type); if (_lastId != null) { criteria.add(Restrictions.gt("id", _lastId)); }//from w w w .j a va2 s . c om criteria.addOrder(Order.asc("id")); criteria.setMaxResults(batchSize); criteria.setCacheable(false); for (Map.Entry<String, FetchMode> e : _fetchModes.entrySet()) { criteria.setFetchMode(e.getKey(), e.getValue()); } List<?> list = criteria.list(); if (list.size() > 0) { ClassMetadata meta = session.getSessionFactory().getClassMetadata(_type); Object last = list.get(list.size() - 1); _lastId = meta.getIdentifier(last, (SessionImpl) session); } return list; }
From source file:br.com.agendamento.model.daos.AbstractFacade.java
public Connection getConnection() throws SQLException { Session session = em.unwrap(Session.class); SessionFactory sf = session.getSessionFactory(); SessionImplementor si = (SessionImplementor) sf.getCurrentSession(); JdbcConnectionAccess access = si.getJdbcConnectionAccess(); return access.obtainConnection(); }
From source file:br.com.utfpr.pb.config.DatabaseConnection.java
private DatabaseConnection() { this.emf = Persistence.createEntityManagerFactory("default"); Session session = getEntityManager().unwrap(Session.class); SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session .getSessionFactory();//from w ww.j a va 2 s. c o m ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider(); try { this.conn = connectionProvider.getConnection(); } catch (SQLException ex) { ex.printStackTrace(); } }
From source file:br.genericrepository.util.ManagerFactory.java
public Connection getConnection() { Connection connection = null; try {//w ww . j a v a 2 s . c om Session session = (Session) em.getDelegate(); SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory(); ConnectionProvider cp = sfi.getConnectionProvider(); connection = (Connection) cp.getConnection(); return connection; } catch (Exception ex) { ex.printStackTrace(); } return connection; }
From source file:br.gov.jfrj.siga.model.dao.HibernateUtil.java
License:Open Source License
public static void configurarHibernate(Session session) { try {/*from www . ja v a 2s.c o m*/ sessionFactory = session.getSessionFactory(); } catch (final Throwable ex) { // Make sure you log the exception, as it might be swallowed HibernateUtil.logger.error("No foi possvel configurar o hibernate.", ex); throw new ExceptionInInitializerError(ex); } }
From source file:br.gov.jfrj.siga.model.Objeto.java
License:Open Source License
public Object _key() { Session session = (Session) (em().getDelegate()); ClassMetadata meta = session.getSessionFactory().getClassMetadata(this.getClass()); return meta.getIdentifier(this, (SessionImplementor) session); }
From source file:com.atsamour.habitatweave.controller.CurrentCostServlet.java
License:Open Source License
public void showCharts(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); //Connection con = (Connection) getServletContext().getAttribute("DBConnection"); Session session = HibernateUtil.getSessionFactory().getCurrentSession(); SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session .getSessionFactory();/*from w ww. j a va 2s.c o m*/ ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider(); PreparedStatement ps = null; ResultSet rs = null; //List of SensorInfo Object, each of one contains corresponding sensor probes List<SensorInfo> _sensors = new ArrayList<>(); List<Integer> _sensorIDs = new ArrayList<>(); try { Connection con = connectionProvider.getConnection(); // ps = con.prepareStatement("SELECT `sensorID`, SUM(ccdata.phasesum) AS phasesum," // + " `date`, `time` FROM ccdata ORDER BY `sensorID`, date, HOUR(time)"); // did not yet implemented select by sensorID ps = con.prepareStatement("SELECT * FROM ccdata ORDER BY `sensorID`"); rs = ps.executeQuery(); // Extract data from result set while (rs.next()) { //Retrieve by column name int sensorID = rs.getInt("sensorID"); String date = rs.getString("date"); String time = rs.getString("time"); float watts = rs.getFloat("phasesum"); if (_sensorIDs.contains(sensorID)) { _sensors.get(_sensorIDs.indexOf(sensorID)).addInfo(date, time, watts); } else { SensorInfo tmpSensor = new SensorInfo(); tmpSensor.addInfo(sensorID, date, time, watts); _sensors.add(tmpSensor); _sensorIDs.add(sensorID); } } //HttpSession session = request.getSession(); request.setAttribute("sensorIDs", _sensorIDs); request.setAttribute("sensors", _sensors); int sensor; if (request.getParameter("sensor") != null) { sensor = Integer.parseInt(request.getParameter("sensor")); } else { sensor = _sensorIDs.get(0); } request.setAttribute("sensor", sensor); request.setAttribute("sensorObj", _sensors.get(_sensorIDs.indexOf(sensor))); //set last probe of selected sensor List<Float> watts = _sensors.get(_sensorIDs.indexOf(sensor)).getWatts(); float probe = watts.get(watts.size() - 1); //System.out.println(probe); //request.setAttribute("indication", Float.toString(probe)); request.setAttribute("indication", probe); //System.out.println(request.getRequestURI()); RequestDispatcher rd = getServletContext().getRequestDispatcher("/secure/currentcost.jsp"); rd.forward(request, response); } catch (SQLException e) { e.printStackTrace(); //logger.error("Database connection problem"); throw new ServletException("DB Connection problem."); } finally { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } } catch (SQLException e) { System.out.println("SQLException in closing PreparedStatement or ResultSet"); } } }
From source file:com.atsamour.habitatweave.controller.IndexServlet.java
License:Open Source License
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// www . ja va 2 s.c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); Session session = HibernateUtil.getSessionFactory().getCurrentSession(); SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session .getSessionFactory(); ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider(); PreparedStatement ps = null; ResultSet rs = null; //List of SensorInfo Object, each of one contains corresponding sensor probes List<SensorInfo> _sensors = new ArrayList<SensorInfo>(); List<Integer> _sensorIDs = new ArrayList<Integer>(); try { Connection con = connectionProvider.getConnection(); ps = con.prepareStatement("SELECT * FROM ccdata WHERE sensorID = '0'"); rs = ps.executeQuery(); // Extract data from result set while (rs.next()) { //Retrieve by column name int sensorID = rs.getInt("sensorID"); String date = rs.getString("date"); String time = rs.getString("time"); float watts = rs.getFloat("phasesum"); if (_sensorIDs.contains(sensorID)) { _sensors.get(_sensorIDs.indexOf(sensorID)).addInfo(date, time, watts); } else { SensorInfo tmpSensor = new SensorInfo(); tmpSensor.addInfo(sensorID, date, time, watts); _sensors.add(tmpSensor); _sensorIDs.add(sensorID); } } request.setAttribute("sensorIDs", _sensorIDs); request.setAttribute("sensors", _sensors); int sensor; if (request.getParameter("sensor") != null) { sensor = Integer.parseInt(request.getParameter("sensor")); } else { sensor = _sensorIDs.get(0); } request.setAttribute("sensor", sensor); request.setAttribute("sensorObj", _sensors.get(_sensorIDs.indexOf(sensor))); //set last probe of selected sensor List<Float> watts = _sensors.get(_sensorIDs.indexOf(sensor)).getWatts(); float probe = watts.get(watts.size() - 1); request.setAttribute("indication", probe); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date1 = new Date(); Date date2 = new Date(); try { date1 = dateFormat.parse("2014/05/21"); date2 = dateFormat.parse("2014/05/28"); } catch (ParseException ex) { Logger.getLogger(SchedulesServlet.class.getName()).log(Level.SEVERE, null, ex); } session.beginTransaction(); String person_id = "10000";//???????????? List<Object[]> result = getSleepMeasurement(session, person_id, date1, date2); List<MeasurementDay> mdList = new ArrayList<>(); //Date currDate = new Date(0); MeasurementDay md = new MeasurementDay(); //Iterate throught rows and create a MeasurementDay Object every new date for (Object[] row : result) { //new day if (md.getDate() == null) { md.setDate(row[0]); setTypeValue(md, row[1].toString(), row[2].toString()); //same day, new measurement } else if (md.getDate().compareTo((Date) row[0]) == 0) { setTypeValue(md, row[1].toString(), row[2].toString()); } else if (md.getDate().compareTo((Date) row[0]) != 0) { mdList.add(md); md = new MeasurementDay(); md.setDate(row[0]); setTypeValue(md, row[1].toString(), row[2].toString()); } } mdList.add(md); //adding the last Day //Rearange data from /day to /SleepType List<List<Double>> measurementsPerType = new ArrayList<>(); for (int i = 0; i < 4; i++) { List<Double> typeMeasurement = new ArrayList<>(); for (MeasurementDay day : mdList) { if (i == 0) typeMeasurement.add(day.getSleepLatency()); if (i == 1) typeMeasurement.add(day.getTotalTimeDeepSleep()); if (i == 2) typeMeasurement.add(day.getTotalTimeInBedButAwake()); if (i == 3) typeMeasurement.add(day.getTotalTimeShallowSleep()); } measurementsPerType.add(typeMeasurement); } List<String> dates = new ArrayList<>(); for (MeasurementDay day : mdList) { dates.add(day.getDate().toString()); } request.setAttribute("measurementsPerType", measurementsPerType); request.setAttribute("dates", dates); // Session session2 = HibernateUtil.getSessionFactory().openSession(); // session2.beginTransaction(); //session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.flush(); //session.beginTransaction(); try { date1 = dateFormat.parse("2014/07/09"); date2 = dateFormat.parse("2014/07/28"); } catch (ParseException ex) { Logger.getLogger(SchedulesServlet.class.getName()).log(Level.SEVERE, null, ex); } List<Object[]> result2 = getActivityMeasurement(session, person_id, date1, date2); List<CaloriesHour> chList = new ArrayList<>(); CaloriesHour ch = new CaloriesHour(); //Iterate throught rows and create a MeasurementDay Object every new hour for (Object[] row : result2) { //new day if (ch.getHour() == -1) { //ch.setHour(((Timestamp)row[2]).getHours() ); for the oldquery ch.setHour(row[2]); ch.setDate(row[0]); if (row[3].equals("Calories")) ch.addCalories((Double) row[1]); //or setCalories else ch.addMi((Double) row[1]); //or setCalories //same day, new measurement } else if (ch.getHour() == (int) row[2]) { if (row[3].equals("Calories")) ch.addCalories(Double.valueOf(row[1].toString())); else ch.addMi(Double.valueOf(row[1].toString())); } else if (ch.getHour() != (int) row[2]) { chList.add(ch); ch = new CaloriesHour(); //ch.setHour(((Timestamp)row[2]).getHours() ); old query ch.setHour(row[2]); ch.setDate(row[0]); if (row[3].equals("Calories")) ch.addCalories(Double.valueOf(row[1].toString())); //or setCalories else ch.addMi(Double.valueOf(row[1].toString())); } } chList.add(ch); //adding the last Day request.setAttribute("chList", chList); if (session.isOpen()) { session.close(); } } catch (SQLException e) { e.printStackTrace(); //logger.error("Database connection problem"); throw new ServletException("DB Connection problem."); } finally { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } } catch (SQLException e) { System.out.println("SQLException in closing PreparedStatement or ResultSet"); } } RequestDispatcher rd = getServletContext().getRequestDispatcher("/secure/index.jsp"); rd.forward(request, response); }
From source file:com.atsamour.habitatweave.controller.PlugWiseServlet.java
License:Open Source License
public void showCharts(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); //Connection con = (Connection) getServletContext().getAttribute("DBConnection"); PreparedStatement ps = null;/*from ww w . ja v a 2s . co m*/ ResultSet rs = null; PreparedStatement ps2 = null; ResultSet rs2 = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session .getSessionFactory(); ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider(); //List of SensorInfo Object, each of one contains corresponding sensor probes //List<SensorInfo> _sensors = new ArrayList<SensorInfo>(); List<String> _sensorIDs = new ArrayList<String>(); //else { //sensor = _sensorIDs.get(0); } try { Connection con = connectionProvider.getConnection(); ps = con.prepareStatement("SELECT DISTINCT `sensorID` FROM pwdata"); rs = ps.executeQuery(); while (rs.next()) { //Retrieve by column name String sensorID = rs.getString("sensorID"); _sensorIDs.add(sensorID); } request.setAttribute("sensorIDs", _sensorIDs); } catch (SQLException e) { e.printStackTrace(); //logger.error("Database connection problem"); throw new ServletException("DB Connection problem."); } finally { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } } catch (SQLException e) { System.out.println("SQLException in closing PreparedStatement or ResultSet"); } } try { String sensor = ""; if (request.getParameter("sensor") != null && !request.getParameter("sensor").isEmpty()) sensor = (request.getParameter("sensor")); else sensor = _sensorIDs.get(0); Connection con2 = connectionProvider.getConnection(); ps2 = con2.prepareStatement("SELECT `sensorID`, SUM(pwdata.value) AS value," + " `date`, `time` FROM pwdata WHERE pwdata.sensorID = ? GROUP BY date, HOUR(time)"); ps2.setString(1, sensor); rs2 = ps2.executeQuery(); // Extract data from result set SensorInfo tmpSensor = new SensorInfo(); while (rs2.next()) { //Retrieve by column name String date = rs2.getString("date"); String time = rs2.getString("time"); float watts = rs2.getFloat("value"); tmpSensor.addInfo(sensor, date, time, watts); } request.setAttribute("sensorObj", tmpSensor); request.setAttribute("sensor", sensor); //set last probe of selected sensor List<Float> watts = tmpSensor.getWatts(); float probe = watts.get(watts.size() - 1); request.setAttribute("indication", probe); RequestDispatcher rd = getServletContext().getRequestDispatcher("/secure/plugwise.jsp"); rd.forward(request, response); } catch (SQLException e) { e.printStackTrace(); //logger.error("Database connection problem"); throw new ServletException("DB Connection problem."); } finally { try { if (rs2 != null) { rs2.close(); } if (ps2 != null) { ps2.close(); } } catch (SQLException e) { System.out.println("SQLException in closing PreparedStatement or ResultSet"); } } }